【发布时间】:2021-10-04 14:24:30
【问题描述】:
我想在gatsby-source-graphq 标头选项中异步生成Auth token。根据文档,我可以使用异步函数来生成我的Bearer token,但我也想将它存储在某个地方。我无法使用sessionStorage 或localStorage,因为我无权访问gatsby-config.js 中的窗口对象。有什么办法可以做到这一点?这是我的代码:
require("dotenv").config({
path: `.env.${process.env.NODE_ENV}`,
});
const axios = require("axios");
const getAuthToken = async () => {
const token = btoa(
`${process.env.CTP_CLIENT_ID}:${process.env.CTP_CLIENT_SECRET}`
);
try {
const { data } = await axios.post(
// I would like to save the Auth token here
`${process.env.CTP_AUTH_URL}/oauth/token?grant_type=client_credentials`,
null,
{
headers: {
Authorization: `Basic ${token}`,
},
}
);
return `Bearer ${data.access_token}`;
} catch (err) {
console.warn(err);
}
};
module.exports = {
siteMetadata: {
siteUrl: "https://www.yourdomain.tld",
title: "test_shop",
},
plugins: [
"gatsby-plugin-typescript",
"gatsby-plugin-postcss",
"gatsby-plugin-image",
{
resolve: "gatsby-plugin-google-analytics",
options: {
trackingId: "test_shop",
},
},
"gatsby-plugin-react-helmet",
"gatsby-plugin-sharp",
"gatsby-transformer-sharp",
{
resolve: "gatsby-source-graphql",
options: {
// Arbitrary name for the remote schema Query type
typeName: "Merchant",
// Field under which the remote schema will be accessible. You'll use this in your Gatsby query
fieldName: "merchant",
// Url to query from
url: "https://api.europe-west1.gcp.commercetools.com/wj_trial/graphql",
// TODO: add token dynamically
headers: async () => {
return {
Authorization: await getAuthToken(),
};
},
},
},
{
resolve: "gatsby-source-filesystem",
options: {
name: "images",
path: "./src/images/",
},
__key: "images",
},
],
};
【问题讨论】:
标签: graphql config gatsby gatsby-plugin