question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[QUESTION] Middleware binding on graphql requests?

See original GitHub issue

[x] I’ve read the docs of nestjs-pino

[x] I’ve read the docs of pino

[x] I couldn’t find the same question about nestjs-pino

Question I saw it mentioned in this issue that the module should work on graphql requests, however, as far as I can tell, middleware applied via MiddlewareConsumer is not executed when using the nestjs/graphql module. While the logger will work, there is no instance bound to the request from asynclocalstorage, and using the assign method result in an error being thrown.

Is my understanding incorrect? Does something special need to be done to get this functional on graphql requests? I’m thinking the bindLoggerMiddleware needs to be exposed so it can be bound by the graphql context.

Please mention other relevant information such as Node.js version and Operating System.

n/a

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:18 (6 by maintainers)

github_iconTop GitHub Comments

3reactions
iamoleggacommented, May 3, 2022

@julestruong if you need such info you have to use plugins. Here is the reference from my current project:

import { Logger } from '@nestjs/common';
import { Plugin } from '@nestjs/graphql';
import { GraphQLRequestContext } from 'apollo-server-core';
import {
  ApolloServerPlugin,
  GraphQLRequestListener,
  GraphQLRequestContextDidEncounterErrors,
} from 'apollo-server-plugin-base';

@Plugin()
export class GraphQLLogger implements ApolloServerPlugin {
  private readonly logger = new Logger(GraphQLLogger.name);

  async requestDidStart(
    startCtx: GraphQLRequestContext,
  ): Promise<GraphQLRequestListener> {
    return new Listener(
      {
        query: startCtx.request.query,
        operationName: startCtx.request.operationName,
      },
      this.logger,
      // bad bad bad bad typings in lib
    ) as unknown as GraphQLRequestListener;
  }
}

class Listener<T = unknown>
  // bad bad bad bad typings in lib
  implements
    Pick<GraphQLRequestListener<T>, 'didEncounterErrors' | 'willSendResponse'>
{
  private readonly start: number;

  constructor(
    private readonly logData: Record<string, unknown>,
    private readonly logger: Logger,
  ) {
    this.start = Date.now();
  }

  async didEncounterErrors(
    errorsCtx: GraphQLRequestContextDidEncounterErrors<T>,
  ): Promise<void> {
    this.logData.errors = errorsCtx.errors;
  }

  async willSendResponse(): Promise<void> {
    this.logger.log(
      {
        graphql: this.logData,
        responseTime: Date.now() - this.start,
      },
      this.logData.errors ? 'request errored' : 'request completed',
    );
  }
}

also I recommend add to config:

  autoLogging: {
    ignorePaths: [
      // ...

      '/graphql',
    ],
  },
1reaction
iamoleggacommented, May 3, 2022

@julestruong current plugin will work pretty the same as autologging, but with your custom data. It’s just to prevent log duplication, but it’s up to you

Read more comments on GitHub >

github_iconTop Results From Across the Web

Split up your GraphQL resolvers in middleware functions
GraphQL Middleware lets you run arbitrary code before or after a resolver is invoked. It improves your code structure by enabling code reuse...
Read more >
Authentication and Express Middleware - GraphQL
In a REST API, authentication is often handled with a header, that contains an auth token which proves what user is making this...
Read more >
GraphQL error handling to the max with Typescript, codegen ...
In GraphQL, all requests must go to a single endpoint: ... After its creation using the ADT Do or bind / bindTo functions,...
Read more >
Building and consuming GraphQL API in ASP.NET Core 5
One of the significant differences between REST and GraphQL is that the API determines the request and response in REST, whereas, in GraphQL, ......
Read more >
graphql - Log Query/Mutation actions to database for Auditing
How can this be implemented using some kind of middleware between graphql and DB (say mongo for now)? Means that middleware should be ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found