我正在使用带有React Query的 GraphQL 代码生成器,这是我的codegen.yml
:
overwrite: true
schema: http://localhost:4000/graphql
generates:
src/lib/__generated__/graphql.ts:
documents:
- "**/graphql/**/*.graphql"
- "!mysqldata/**"
plugins:
- add:
content: &comment "/* DO NOT EDIT! this file was generated by graphql-codegen */\n/* eslint-disable */"
- add:
placement: append
content: "export { fetcher }"
- typescript
- typescript-operations
- typescript-react-query
config:
fetcher:
endpoint: "`${process.env.NEXT_PUBLIC_API_URL}/graphql`"
fetchParams:
credentials: include
headers:
Content-Type: application/json
这会生成以下提取器:
function fetcher<TData, TVariables>(query: string, variables?: TVariables) {
return async (): Promise<TData> => {
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/graphql` as string, {
method: "POST",
credentials: "include",
headers: {"Content-Type":"application/json"},
body: JSON.stringify({ query, variables }),
});
const json = await res.json();
if (json.errors) {
const { message } = json.errors[0];
throw new Error(message);
}
return json.data;
}
}
NEXT_PUBLIC_API_URL
指的是外部 GraphQL API。在我的 Next.js 应用程序中,我尝试使用nextjs-auth0和auth0-react。
nextjs-auth0
允许我从 Next.js API 路由访问 Auth0 的 ID 令牌:
export default (req: NextApiRequest, res: NextApiResponse) => {
const session = getSession(req, res)
const idToken = session?.idToken
同时auth0-react
允许我获取令牌客户端:
const claims = await auth0.getIdTokenClaims();
const idToken = claims.__raw;
问题是,由于这些抽象,我无法找到一种方法将此令牌包含在对我的 GraphQL 端点的请求中,例如:
headers: {
authorization: `Bearer ${session?.idToken}`,
},