如何制作 apollo 服务器预处理器
How to make apollo server prehandler
有没有办法为 apollo 服务器添加预处理器,这样我就可以从预处理器抛出错误,apollo 会捕获并以 apollo 格式作为响应发送?或者也许有一个帮助程序来格式化响应错误?
我如何使用自定义 getGqlErr 帮助程序来执行此操作,它将获取现有错误或生成错误:
onst apolloHandler = apolloServer.createHandler({ path: '/api/graphql' })
const apiHandler = async (req: NextApiRequest, res: NextApiResponse): Promise<void> => {
try {
await prehandler({ req, res } as Ctx)
} catch (e) {
res.setHeader('Content-Type', 'application/json')
res.end(
JSON.stringify({
errors: [
{
message: 'Prehandler Error',
extensions: {
langsMsg: getGqlErr(e),
code: 'prehandler custom error',
},
},
],
})
)
return
}
apolloHandler(req, res)
}
可以在上下文函数中完成。
const apolloServer = new ApolloServer({
schema,
formatError: (err): any => {
console.log(err)
return err
},
async context(ctx: Ctx): Promise<Ctx> {
await prehandler(ctx)
return ctx
},
})
有没有办法为 apollo 服务器添加预处理器,这样我就可以从预处理器抛出错误,apollo 会捕获并以 apollo 格式作为响应发送?或者也许有一个帮助程序来格式化响应错误?
我如何使用自定义 getGqlErr 帮助程序来执行此操作,它将获取现有错误或生成错误:
onst apolloHandler = apolloServer.createHandler({ path: '/api/graphql' })
const apiHandler = async (req: NextApiRequest, res: NextApiResponse): Promise<void> => {
try {
await prehandler({ req, res } as Ctx)
} catch (e) {
res.setHeader('Content-Type', 'application/json')
res.end(
JSON.stringify({
errors: [
{
message: 'Prehandler Error',
extensions: {
langsMsg: getGqlErr(e),
code: 'prehandler custom error',
},
},
],
})
)
return
}
apolloHandler(req, res)
}
可以在上下文函数中完成。
const apolloServer = new ApolloServer({
schema,
formatError: (err): any => {
console.log(err)
return err
},
async context(ctx: Ctx): Promise<Ctx> {
await prehandler(ctx)
return ctx
},
})