我是graphQL的相对新手,但这让我很烦。我想从客户端发送的请求正文中获取用户代理。我可以访问中间件中的用户代理,但是当我用任何参数调用下一个函数以发送到解析器时,都不会从中获取任何数据。如果我没有将任何参数传递给next(),则解析器将按预期工作,但是父级,参数,用户和会话不包含有关请求标头的任何信息。任何帮助或一般提示将不胜感激!谢谢!
import express from 'express';
import bodyParser from 'body-parser';
import mongoose from 'mongoose';
import { graphiqlExpress, graphqlExpress } from 'apollo-server-express';
import { makeExecutableSchema } from 'graphql-tools';
import typeDefs from './Graphql/typeDefs';
import resolvers from './Graphql/resolver';
import { User } from './Mongoose/Schemas/user';
import { Session } from './Mongoose/Schemas/session';
mongoose.connect('mongodb://localhost/test');
const schema = makeExecutableSchema({
typeDefs,
resolvers,
});
const helperMiddleware = [
bodyParser.json(),
bodyParser.text({ type: 'application/graphql' }),
(req, res, next) => {
if ( req.body ) {
console.log(req.headers['user-agent']);
}
next();
},
];
const PORT = 3009;
const app = express();
app.use('/graphql', ...helperMiddleware, graphqlExpress({ schema, context: { User, Session } }));
app.use('/graphiql', graphiqlExpress({ endpointURL: '/graphql' }));
app.listen(PORT);
console.log(`Running On Port ${PORT}`);
Mutation: {
createUser: async (parent, args, { User, Session }) => {
const user = await new User(args).save();
user._id = user._id.toString();
const session = await new Session({
user_id: user._id,
userAgent: 'Nothing ATM',
ip: 'Nothing ATM',
}).save();
return user;
},
答案 0 :(得分:1)
您需要使用创建GraphQL服务器中间件的回调版本,否则您将无法基于当前请求构造上下文:
https://www.apollographql.com/docs/apollo-server/setup.html#options-function