在nestjs应用程序中使用新的阿波罗服务器版本的打字稿错误
Posted
技术标签:
【中文标题】在nestjs应用程序中使用新的阿波罗服务器版本的打字稿错误【英文标题】:Typescript error using new apollo server version in nestjs application 【发布时间】:2021-10-28 05:54:59 【问题描述】:我已在我的 nestJS 应用程序中将 apollo-server-plugin-base
更新为 v3.2,现在这个简单的 nestjs 插件确实出现了两个打字错误:
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')
很遗憾,我根本不理解这个错误。所以我需要一些帮助。
requestDidStart():
TS2416: Property 'requestDidStart' in type 'LoggingPlugin' is not assignable to the same property in base type 'ApolloServerPlugin<BaseContext>'.
Type '() => GraphQLRequestListener<BaseContext>' is not assignable to type '(requestContext: GraphQLRequestContext<BaseContext>) => Promise<void | GraphQLRequestListener<BaseContext>>'.
Type 'GraphQLRequestListener<BaseContext>' is missing the following properties from type 'Promise<void | GraphQLRequestListener<BaseContext>>': then, catch, finally, [Symbol.toStringTag]
willSendResponse:
TS2322: Type '() => void' is not assignable to type '(requestContext: GraphQLRequestContextWillSendResponse<BaseContext>) => Promise<void>'.
Type 'void' is not assignable to type 'Promise<void>'.
【问题讨论】:
【参考方案1】:以下内容对我有用,并为日志添加了更多风味:
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 LoggingPlugin implements ApolloServerPlugin
logger: Logger;
constructor()
this.logger = new Logger('ApolloServer');
// Fires whenever a GraphQL request is received from a client.
async requestDidStart(requestContext: GraphQLRequestContext): Promise<GraphQLRequestListener>
this.logger.log(
'Request received:\n' +
requestContext.request.query +
'\nvariables:' +
JSON.stringify(requestContext.request.variables)
);
return
async willSendResponse()
// console.log('Will send response');
,
;
【讨论】:
【参考方案2】:从错误消息看来,您应该将 requestDidStart
设为异步函数,方法是返回一个 void promise return Promise<void>.resolve();
或将 async
关键字添加到方法声明 async requestDidStart()
。
【讨论】:
以上是关于在nestjs应用程序中使用新的阿波罗服务器版本的打字稿错误的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 NestJS GraphQL 实现 NuxtJS Apollo