如果将修改后的上下文传递给GraphQL解析器,这会传播到所有下游解析器吗?这是在GraphQL规范中还是在实现中指定的?
为了举例说明,我有一个类似以下的查询
{
companies {
employees {
positions {
title
}
}
}
}
假设我以contextA
开始进入companies
查询,然后在CompanyResolvers
处得到一个superSpecialContext
,并将其传递给{{1 }}数据加载器
employees
当我到达export const CompanyResolvers = {
employees: async ({ id }: CompanyDTO, args: object, contextA: Context) => {
const superSpecialContext = await getSuperSpecialContext();
return context.dataLoaders.employees.load({ id: company.id, context: superSpecialContext });
}
};
解析器时,我现在是在使用positions
还是原始的superSpecialContext
(我希望是这种情况)?
contextA
答案 0 :(得分:1)
如果将修改后的上下文传递给GraphQL解析器,则会传播到所有下游解析器。
是的,每个请求在请求期间将获得自己的上下文对象。它是在GraphQL服务器上的上下文函数中创建的。
import { ApolloServer, gql } from 'apollo-server'
import { ExpressContext } from 'apollo-server-express/dist/ApolloServer';
const typeDefs = gql`
type Book {
title: String
author: String
}
type Query {
books: [Book]
}
`;
const books = [
{
title: 'Harry Potter and the Chamber of Secrets',
author: 'J.K. Rowling',
},
{
title: 'Jurassic Park',
author: 'Michael Crichton',
},
];
const resolvers = {
Query: {
books: (obj: any, args: any, context: any) => {
console.log(context.name); // Khalil Stemmler
context.name = 'Billy Bob Thorton'
return books;
},
},
Book: {
title: (obj: any, args: any, context: any) => {
console.log(context.name); // Billy Bob Thorton.
// Should print "Billy Bob Thorton twice", once for each book.
return obj.title
},
}
};
const server = new ApolloServer({
typeDefs,
resolvers,
context: (expressContext: ExpressContext) => {
// The Apollo implementation of context allows you hook into the
// Express request to get access to headers, tokens, etc- in order
// to grab an authenticated user's session data and put it on context.
const { connection, res, req } = expressContext;
// A new context object is created for every request. This function
// should return an object.
return {
name: 'Khalil Stemmler'
}
}
});
// The `listen` method launches a web server.
server.listen().then(({ url }: { url: string }) => {
console.log(`? Server ready at ${url}`);
});
运行以下查询:
{
books {
title
author
}
}
我们得到:
? Server ready at http://localhost:4000/
Khalil Stemmler
Billy Bob Thorton
Billy Bob Thorton