You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesi贸n a prueba de IA

Antes: $249

Currency
$209
Suscr铆bete

Termina en:

1 D铆as
20 Hrs
53 Min
0 Seg

Conectado a ProductService

12/24
Resources

How to connect the service layer to the database?

To establish the connection to the database and manage real data in our application, we use SQLite. This is defined in the service layer, where the business model is implemented and the necessary queries are performed. Having the file structure well organized facilitates this process.

How are the services declared?

In the Product Resolvers file, we manage the declaration of the product service. Following the example of routes is useful. In routes, each endpoint has specific validations and services, such as the product service. An instance of this service is needed:

const productService = new ProductService();

This service contains the logic needed to manage products. For example, to get a product, the input parameters are used and a query is performed using findOne.

How to resolve queries to the database?

Using GraphQL allows us to specify what exact data we want to retrieve. When making a query, we can request only the necessary fields. For example, to get a list of products:

query { getProduct { id name name description price }}

This way we get a list of products with the required fields, directly from the database.

How to handle requests and errors in GraphQL?

When resolving requests in GraphQL, it is crucial to properly handle errors to ensure clear feedback to the user.

What happens when a product is not found?

When we request a product with an ID that does not exist, the application responds with a clear error message, thanks to the Boom library. This library facilitates the handling of HTTP errors, and although it was designed for REST API, it adapts to GraphQL. When the product is not found, Boom returns a "Product not-found" error message and a 404 code:

async findOne(id) { const product = await db.Product.findByPk(id); if (!product) { throw Boom.notFound('Product not-found'); } return product;}

This structure allows Apollo Server to interpret and reuse errors, generating a consistent response in GraphQL.

How are these responses verified in testing tools?

By using tools like Insomnia to verify responses, you can see how, when sending a request with an ID that does not exist, GraphQL returns a message similar to that of a REST API, showing that the integration is efficient and adaptive.

Exploring Apollo Server and error handling

Apollo Server has proven to be able to integrate with standard error messages, effortlessly combining REST and GraphQL architectures. This offers valuable flexibility for developers, allowing reuse of existing logic and ensuring a consistent workflow.

How to take advantage of these features?

A best practice is to always use popular and proven libraries for error handling in our applications, ensuring that messages are clear and behavior is consistent across all technologies used. This demonstrates an adaptive and user-centric approach to building modern applications.

With this knowledge, we are ready to continue extending our application capabilities, ensuring robust integration between services and databases. Continue exploring and learning to create exceptional applications!

Contributions 3

Questions 0

Sort by:

Want to see more contributions, questions and answers from the community?

lo que yo veo es que la forma en la que el trabaja es muy pulcra, cuando uno empieza a trabajar en nest js utilizando el camino the clean arquitecture que el propone en bastante sencillo entenderlo,no dice nada pero en cada cosa que hace nos inyecta patrones de dise帽o y un uso profundo del lenguaje. ademas con los tipos de graphql nos van haciendo una inmersion a typescript y eso a largo plazo nos impulsa a ser mas competentes.

Genial, Hasta el momento pensaba que solo era posible usar GraphQL con bases de datos no relacionales. Con esta explicaci贸n pr谩cticamente se puede centralizar cualquier recurso para que pase por GraphQL.

Cuando se intenta mandar un ID que no existe para traer los datos de ese producto si env铆a el error, sin embargo, no como se muestra en el video, en mi caso se muestra de esta manera:

{
  "data": {
    "product": null
  },
  "errors": [
    {
      "message": "product not found",
      "locations": [
        {
          "line": 3,
          "column": 3
        }
      ],
      "path": [
        "product"
      ],
      "extensions": {
        "code": "INTERNAL_SERVER_ERROR",
        "stacktrace": [
          "Error: product not found",
          "    at ProductsService.findOne (C:\\Users\\HP INTEL\\Documents\\Cursos Platzi\\API-graphQL\\src\\services\\product.service.js:49:18)",
          "    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)",
          "    at async Object.product (C:\\Users\\HP INTEL\\Documents\\Cursos Platzi\\API-graphQL\\src\\graphql\\product.resolvers.js:5:21)"
        ]
      }
    }
  ]
}

Imagino que se trata porque use apollo server 4, mientras que en el v铆deo es el 3.
En caso queremos saber solo los errores seguimos los pasos de la siguiente imagen

Luego de eso visualizamos algo como esto:

En conclusi贸n, creo que el apollo solo soporta el campo de message y no reconoce el statusCode ni error