在上下文中附加一个 属性(express.js 中的请求)对象
Attach a property in context(request in express.js) object
我是 GraphQL 的新手,我现在正在尝试使用 express-graphql
.
创建一个 API 服务器
我想要做的是在 context
对象中为解析器添加新的 属性,这可以在我初始化 express-graphql
服务器实例时完成。
根据官方文档,默认情况下,如果代码中没有指定任何内容,则每个解析器函数中的 context
对象都会有一个对象,该对象之前被 调用 req
在 Express.js.
app.use(
'/graphql',
graphqlHTTP({
schema: schema,
graphiql: true
})
)
// by this,
// in resolver there will be `context` available
// which includes the data previously available in `req` object (express.js case)
那么,如果我想在req
或context
对象中添加自己的自定义属性,将req
的所有成员一起添加怎么办? ?我只想添加一两个新值,而不是丢失其他值 req
已经有了。
app.use(
'/graphql',
graphqlHTTP({
schema: schema,
graphiql: true,
context: {
customData: 'Yay!'
}
})
)
// I was able to add my own data in `context`,
// but eventually I lost all of data which was previously in the `req` object!
任何好的想法或知识将不胜感激。
可以自己写一个中间件来添加,在配置graphqlHTTP之前使用。
const setMyContext = (myContext = {}) => {
return function (req, res, next) {
req.myContext = myContext;
next()
}
};
app.use(setMyContext({
customData: 'Yay!'
}));
app.use(
'/graphql',
graphqlHTTP({
schema: schema,
graphiql: true
})
)
您可以通过
访问自定义数据
req.myContext.customData
你可以这样使用
app.use('/graphql', expressGraphql(req => ({
schema,
graphiql: false,
context: {
...req,
customData: 'Yay!'
}
})))
参考文档https://github.com/graphql/express-graphql#providing-extensions
我是 GraphQL 的新手,我现在正在尝试使用 express-graphql
.
我想要做的是在 context
对象中为解析器添加新的 属性,这可以在我初始化 express-graphql
服务器实例时完成。
根据官方文档,默认情况下,如果代码中没有指定任何内容,则每个解析器函数中的 context
对象都会有一个对象,该对象之前被 调用 req
在 Express.js.
app.use(
'/graphql',
graphqlHTTP({
schema: schema,
graphiql: true
})
)
// by this,
// in resolver there will be `context` available
// which includes the data previously available in `req` object (express.js case)
那么,如果我想在req
或context
对象中添加自己的自定义属性,将req
的所有成员一起添加怎么办? ?我只想添加一两个新值,而不是丢失其他值 req
已经有了。
app.use(
'/graphql',
graphqlHTTP({
schema: schema,
graphiql: true,
context: {
customData: 'Yay!'
}
})
)
// I was able to add my own data in `context`,
// but eventually I lost all of data which was previously in the `req` object!
任何好的想法或知识将不胜感激。
可以自己写一个中间件来添加,在配置graphqlHTTP之前使用。
const setMyContext = (myContext = {}) => {
return function (req, res, next) {
req.myContext = myContext;
next()
}
};
app.use(setMyContext({
customData: 'Yay!'
}));
app.use(
'/graphql',
graphqlHTTP({
schema: schema,
graphiql: true
})
)
您可以通过
访问自定义数据req.myContext.customData
你可以这样使用
app.use('/graphql', expressGraphql(req => ({
schema,
graphiql: false,
context: {
...req,
customData: 'Yay!'
}
})))
参考文档https://github.com/graphql/express-graphql#providing-extensions