From 34841fc52edf3fcf40802464a4b81f57973881cb Mon Sep 17 00:00:00 2001 From: Emile Bex Date: Thu, 3 Jun 2021 16:37:57 +0200 Subject: [PATCH] fix(SSR): manage token --- src/core/api/interceptors.ts | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/src/core/api/interceptors.ts b/src/core/api/interceptors.ts index d3e5f138..58bb2982 100644 --- a/src/core/api/interceptors.ts +++ b/src/core/api/interceptors.ts @@ -1,23 +1,25 @@ import { AxiosInstance } from 'axios' import humps from 'humps' import { env } from 'src/core/env' -import { getTokenFromCookies } from 'src/core/services' +import { createAnonymousUser, getTokenFromCookies } from 'src/core/services' import { notifServerError } from 'src/utils/misc' export function addAxiosInterceptors(client: AxiosInstance) { - function getUserToken(): string | null { + async function getUserToken(): Promise { // TODO: improve with token cache in memory for browser side - return getTokenFromCookies() + return getTokenFromCookies() || createAnonymousUser() } - client.interceptors.request.use((request) => { + client.interceptors.request.use(async (request) => { const { params = {} } = request + const token = params.token || await getUserToken() + return { ...request, params: { ...humps.decamelizeKeys(request.params || {}), - token: params.token || getUserToken(), + token, api_key: env.API_KEY, // eslint-disable-line }, data: request.data && humps.decamelizeKeys(request.data),