Skip to content

Commit b164b31

Browse files
committed
feat(js-api-client): renew the token if expired or about to expire
1 parent c1429f8 commit b164b31

File tree

2 files changed

+10
-2
lines changed

2 files changed

+10
-2
lines changed

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
{
22
"name": "@crystallize/js-api-client",
33
"license": "MIT",
4-
"version": "2.3.2",
4+
"version": "2.4.0",
55
"author": "Crystallize <[email protected]> (https://crystallize.com)",
66
"contributors": [
77
"Sébastien Morel <[email protected]>",

src/core/client.ts

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -158,11 +158,19 @@ function createApiCaller(
158158
};
159159
}
160160

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

0 commit comments

Comments
 (0)