Skip to content

Commit

Permalink
feat(js-api-client): renew the token if expired or about to expire
Browse files Browse the repository at this point in the history
  • Loading branch information
Plopix committed Mar 20, 2024
1 parent 8386a6b commit ecae92c
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 2 deletions.
2 changes: 1 addition & 1 deletion components/js-api-client/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@crystallize/js-api-client",
"license": "MIT",
"version": "2.3.2",
"version": "2.4.0",
"author": "Crystallize <hello@crystallize.com> (https://crystallize.com)",
"contributors": [
"Sébastien Morel <sebastien@crystallize.com>",
Expand Down
10 changes: 9 additions & 1 deletion components/js-api-client/src/core/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -158,11 +158,19 @@ function createApiCaller(
};
}

const getExpirationAtFromToken = (token: string) => {
const payload = token.split('.')[1];
const decodedPayload = Buffer.from(payload, 'base64').toString('utf-8');
const parsedPayload = JSON.parse(decodedPayload);
return parsedPayload.exp * 1000;
};
function shopApiCaller(configuration: ClientConfiguration, options?: CreateClientOptions) {
const identifier = configuration.tenantIdentifier;
let shopApiToken = configuration.shopApiToken;
return async function callApi<T>(query: string, variables?: VariablesType): Promise<T> {
if (!shopApiToken && options?.shopApiToken?.doNotFetch !== true) {
const tokenExpiresAt: number | null = shopApiToken ? getExpirationAtFromToken(shopApiToken) : null;
const isTokenAboutToExpireOrIsExpired = tokenExpiresAt ? tokenExpiresAt - Date.now() < 1000 * 60 * 5 : true;
if ((!shopApiToken || isTokenAboutToExpireOrIsExpired) && options?.shopApiToken?.doNotFetch !== true) {
//static auth token must be removed to fetch the shop api token
const { staticAuthToken, ...withoutStaticAuthToken } = configuration;
const headers = {
Expand Down

0 comments on commit ecae92c

Please sign in to comment.