12th Practical Class:
Asynchronous BE and how to log on server
Asynchronous JavaScript
- We're already using it!
But what is async/await? Let's look first at promises and basics quickly.
- JS runs code line by line and synchronously
- Long task might block the main thread!!! See this great example by MDN
- We need asynchronous code! Promises!
- Code runs out of the main thread, notifies it when fulfilled or rejected using event loop
- JS continuously checks for events in a queue, if they are resolved JS take them from queue and return them
Let's put it in our resolvers example:
- We can return a new Promise in callback function and chain promises to keep order in asynchronous calls.
- And catch all errors from all promises called before calling .
- But with chaining Promises, it can get messy pretty fast!
Use async/await instead
- Handling promises like a synchronous code using keyword
- Functions with has to be marked with keyword
- Can't be used on top level unless you're working with modules
- Code inside the function always wait until the Promise called after is fulfilled or rejected
Common mistake when returning data from async function and handling errors:
Our quack resolver using try/catch/finally
How to properly log on GraphQL server?
s are not enough, why?
- No structure
- Every developer can log differently, are you using dots at the end of sentence?
- Missing metadata -> unless you manually add them to every log
- Problem with where to log things
Use tools or your implementation of log
- Start with using logger tool
- Uses api under the hood, but provides better structure and options
- Usually has main logging methods (levels): , , ,
- Each represent different severity
- Displaying each can be configured based on deployment based on levels -> show only and on PROD
- There are many logging tools, we'll be using Pino
- You can also write your own tool, an abstraction over api
How to log in ApolloServer
- Logs should be traceable
- To request, user, and mutated data
- Logs should be as automatic as can
- Lifecycle/event logging
- Pass your logger via context, or use ApolloServer logger prop
- Provides a way to work with GraphQL lifecycle
- You write a plugin method that are hooked to server lifecycle events or request lifecycle events
- All plugins and event handling functions have access to the context and request itself
