Created
January 5, 2022 11:10
-
-
Save ctrlaltdylan/57c1525dd1fce1a16c2b101e1bf7c2ce to your computer and use it in GitHub Desktop.
Shopify x-request-id logger with Apollo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { | |
ApolloClient, | |
createHttpLink, | |
InMemoryCache, | |
ApolloLink, | |
} from "@apollo/client"; | |
import fetch from "cross-fetch"; | |
/** | |
* Shopify x-request-id header logger | |
* | |
* @description When you encounter an error with the Shopify GraphQL API, the only way to get real support is with the corresponding "x-request-id" header | |
* This "afterware" will log the header to your console. | |
*/ | |
const headersLogger = new ApolloLink((operation, forward) => { | |
return forward(operation).map((data) => { | |
const context = operation.getContext(); | |
const { | |
response: { headers }, | |
} = context; | |
console.log(headers["x-request-id"]); | |
return data; | |
}); | |
}); | |
/** | |
* Create a Admin GraphQL client for the corresponding Shopify shop | |
* | |
* @param {Shop} shop | |
* @param {Object} options | |
* @returns {ApolloClient} | |
*/ | |
export default function getShopifyGraph(shop, options = {}) { | |
const httpLink = createHttpLink({ | |
fetch: fetch, | |
uri: `https://${shop.name}/admin/api/2021-07/graphql.json`, | |
credentials: "same-origin", | |
headers: { | |
"Content-Type": "application/json", | |
"X-Shopify-Access-Token": shop.accessToken, | |
}, | |
}); | |
const client = new ApolloClient({ | |
ssrMode: true, | |
link: headersLogger.concat(httpLink), | |
cache: new InMemoryCache(), | |
defaultOptions: options, | |
}); | |
return client; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment