Encountering a Typescript issue with the updated Apollo server version within a NestJS application

After upgrading my nestJS application to use version 3.2 of apollo-server-plugin-base, I encountered two TypeScript errors related to a simple nestJS plugin:

import { Plugin } from '@nestjs/graphql'
import {
  ApolloServerPlugin,
  GraphQLRequestListener
} from 'apollo-server-plugin-base'

@Plugin()
export class LoggingPlugin implements ApolloServerPlugin {
  requestDidStart(): GraphQLRequestListener {
    console.log('Request started')
    return {
      willSendResponse() {
        console.log('Will send response')
      }
    }
  }
}

I am having trouble understanding the nature of these errors and would appreciate some assistance.

requestDidStart():

TS2416: Property 'requestDidStart' in type 'LoggingPlugin' is not assignable to the same property in the base type 'ApolloServerPlugin<BaseContext>'.
  Type '() => GraphQLRequestListener<BaseContext>' is not assignable to type '(requestContext: GraphQLRequestContext<BaseContext>) => Promise<void | GraphQLRequestListener<BaseContext>>'.
    Type 'GraphQLRequestListener<BaseContext>' is missing certain properties required by 'Promise<void | GraphQLRequestListener<BaseContext>>'.

willSendResponse:

TS2322: Type '() => void' is not compatible with the expected type '(requestContext: GraphQLRequestContextWillSendResponse<BaseContext>) => Promise<void>'.
  The error lies in 'Type 'void' being incompatible with type 'Promise<void>'

Answer №1

Based on the error notification, it appears that adjusting requestDidStart to an asynchronous function is essential. This can be achieved by either returning a void promise like return Promise<void>.resolve();, or by simply including the async keyword in the method declaration - async requestDidStart().

Answer №2

Below is a snippet of code that I find effective in enhancing the logging experience:

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

@Plugin()
export class CustomLoggingPlugin implements ApolloServerPlugin {
    logger: Logger;

    constructor() {
        this.logger = new Logger('ApolloServer');
    }

    // This method is triggered every time a client sends a GraphQL request.
    async requestDidStart(requestContext: GraphQLRequestContext): Promise<GraphQLRequestListener> {
        this.logger.log(
            'Received request:\n' +
            requestContext.request.query +
            '\nVariables:' +
            JSON.stringify(requestContext.request.variables)
        );
        return {
            async willSendResponse() {
                // console.log('Preparing to send response...');
            },
        };
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best method for choosing visible elements within a scrollable container?

Is there a way to retrieve the list of visible elements within a scrollable container? The number of elements that are visible on the screen changes as one scrolls, making it challenging to add a specific class to only the last two visible elements. Any s ...

React-snap causing trouble with Firebase

I'm having trouble loading items from firebase on my homepage and I keep running into an error. Does anyone have any advice on how to fix this? I've been following the instructions on https://github.com/stereobooster/react-snap and here is how ...

Converting Enum Values into an Array

Is there a way to extract only the values of an enum and store them in an array? For example, if we have: enum A { dog = 1, cat = 2, ant = 3 } Desired output: ["dog", "cat", "ant"] achieved by: Object.values(A) Unfor ...

Matching TypeScript search field names with column names

Seeking ways to create an API that allows admins to search for users in the database using various fields. // Define allowed search fields type SearchFieldType = 'name' | 'memberNo' | 'email' | 'companyName'; const ...

Ensuring Type Compatibility Between Classes and Object Literals in TypeScript

When working with TypeScript, it is important to note that an object literal can be assigned to a class typed variable as long as the object provides all properties and methods required by the class. class MyClass { a: number; b: string; } // The co ...

Finding the IP address of a server in Angular: A Comprehensive Guide

Is there a way to dynamically retrieve the server host IP address in an Angular application launched with ng serve --host 0.0.0.0? This IP address will be necessary for communication with the backend server. As each coworker has their own unique IP addres ...

The absence of a 'body' argument in the send() json() method within the Next.js API, coupled with TypeScript, raises an important argument

Currently, I have set up an API route within Next.js. Within the 'api' directory, my 'file.tsx' consists of the following code: import type { NextApiRequest, NextApiResponse } from "next"; const someFunction = (req: NextApiReq ...

SwitchMap in Typescript allows you to switch to a

In my TypeScript code, I have implemented multiple interfaces, components, and a key/interface map. interface FooProps { 'keyInFoo': string } const Foo = (props: FooProps) => {} interface BarProps { 'keyInBar': string } cons ...

When utilizing the useRef hook in Material-UI, an error may arise stating: "The property 'value' is not found on the type 'never'."

Currently, I am utilizing material UI to construct a login and registration page. In the process, I am leveraging the useRef hook to retrieve a reference instance for a TextFiled, and using xxxRef.current.value to access the input value. Despite being abl ...

The 'Subscription' type does not contain the properties _isScalar, source, operator, lift, and several others that are found in the 'Observable<any>' type

Looking to retrieve data from two APIs in Angular 8. I have created a resolver like this: export class AccessLevelResolve implements Resolve<any>{ constructor(private accessLevel: AccessLevelService) { } resolve(route: ActivatedRouteSnapshot, sta ...

What is causing the warnings for a functional TypeScript multidimensional array?

I have an array of individuals stored in a nested associative array structure. Each individual is assigned to a specific location, and each location is associated with a particular timezone. Here is how I have defined my variables: interface AssociativeArr ...

In ReactJS, the way to submit a form using OnChange is by utilizing the

Is there a way to submit a form using Onchange without a button? I need to fire the form but can't insert routes as it's a component for multiple clients. My project is built using react hook forms. const handleChange = (e: any) => { c ...

Ionic 4's http.get.subscribe method fails to retain the retrieved value

I'm aware this might be a repeated question, but I haven't come across a straightforward answer yet, so here it goes. Below is the code snippet in question: fetchData() { let dataArray: Array<any> = [, , ,]; this.prepareDataReque ...

The type 'Handles' does not contain the properties present in type 'TextInput'

Implementing a phone number field using React Native Paper and react-native-text-input-mask: // Necessary Imports import {TextInput} from 'react-native-paper' import TextInputMask from 'react-native-text-input-mask' // Control Implemen ...

Changes made to one order's information can impact the information of another order

Currently, I am in the process of developing a unique shopping cart feature where users input a number and a corresponding product is added to a display list. Users have the ability to adjust both the price and quantity of the products, with the total pric ...

Utilize React to display a Selected button within a whitespace

Currently, I am encountering an issue in React where I have a group of buttons at the bottom. Upon selecting a button, the corresponding text should display at the top within a specified whitespace. However, I am looking to have the whitespace already occu ...

Tips for selecting objects based on property in Typescript?

Consider this scenario: import { Action, AnyAction } from 'redux'; // interface Action<Type> { type: Type } and type AnyAction = Action<any> export type FilterActionByType< A extends AnyAction, ActionType extends string > ...

Creating UI Bootstrap dropdowns using ng-repeat on the fly

As a newcomer to AngularJS and UI Bootstrap, I am facing an issue with adding dropdowns dynamically using ng-repeat. The main problem lies in the fact that when one dropdown is clicked, it triggers all of them simultaneously. It seems like there is some mi ...

NestJS Logger: Issue setting logger types in main.ts

When attempting to specify logger types in main.ts as illustrated in the official documentation: const app = await NestFactory.create(ApplicationModule, { logger: ['error', 'warn'], }); await app.listen(3000); I am encountering an i ...

Steps for determining if a string is compatible with a user-defined type in Typescript

Just getting started with Typescript and currently working on a sudoku game. Here are the types and interface I have set up: export type GridCellValue = 1|2|3|4|5|6|7|8|9; export interface GridCell { readonly: boolean, value: GridCellValue|null, } ex ...