express-graphql - 如何将 res 对象传递给上下文中的自定义函数?
express-graphql - how can I pass res object to a custom function in context?
在我的配置中,我有以下内容:-
expressGraphQL((req, res) => ({
...,
context: {
req,
res,
database,
},
}))
我希望能够将 res 传递给上下文中的自定义函数,如下所示:-
expressGraphQL((req, res) => ({
...,
context: {
req,
res,
database,
myCustomFunction: (res) => {
// do something with res object here
}
}))
但是,当我从解析器中的上下文中获取 myCustomFunction 并且 运行 是时,res 是未定义的。
我知道我可以将 res 与 myCustomFunction 一起从上下文中拉出并调用 myCustomFunction(res) 但我只想能够执行 myCustomFunction()。
有什么办法可以做到这一点吗?谢谢
由于您是在已作为参数传递 res
的函数内部定义函数,因此只需使用该参数即可。这意味着你应该从 myCustomFunction
的签名中删除 res
参数,否则你最终会 shadowing 你实际想要使用的 res
变量。
expressGraphQL((req, res) => ({
...,
context: {
...
myCustomFunction: () => {
console.log(res)
},
},
}))
您也可以在不同的范围内定义 myCustomFunction
,在这种情况下您可以这样做:
function myCustomFunction (res) {
console.log(res)
}
expressGraphQL((req, res) => ({
...,
context: {
...
myCustomFunction: () => myCustomFunction(res),
},
}))
在我的配置中,我有以下内容:-
expressGraphQL((req, res) => ({
...,
context: {
req,
res,
database,
},
}))
我希望能够将 res 传递给上下文中的自定义函数,如下所示:-
expressGraphQL((req, res) => ({
...,
context: {
req,
res,
database,
myCustomFunction: (res) => {
// do something with res object here
}
}))
但是,当我从解析器中的上下文中获取 myCustomFunction 并且 运行 是时,res 是未定义的。
我知道我可以将 res 与 myCustomFunction 一起从上下文中拉出并调用 myCustomFunction(res) 但我只想能够执行 myCustomFunction()。
有什么办法可以做到这一点吗?谢谢
由于您是在已作为参数传递 res
的函数内部定义函数,因此只需使用该参数即可。这意味着你应该从 myCustomFunction
的签名中删除 res
参数,否则你最终会 shadowing 你实际想要使用的 res
变量。
expressGraphQL((req, res) => ({
...,
context: {
...
myCustomFunction: () => {
console.log(res)
},
},
}))
您也可以在不同的范围内定义 myCustomFunction
,在这种情况下您可以这样做:
function myCustomFunction (res) {
console.log(res)
}
expressGraphQL((req, res) => ({
...,
context: {
...
myCustomFunction: () => myCustomFunction(res),
},
}))