Skip to content

Commit

Permalink
feat(middleware): allow functional url and custom request method in a…
Browse files Browse the repository at this point in the history
…uth middleware
  • Loading branch information
glebcha committed Nov 29, 2023
1 parent 0910faf commit 4a06d67
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 3 deletions.
6 changes: 4 additions & 2 deletions src/middleware/auth/authMiddleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,22 @@ import { AuthMiddlewareParams } from './types';
export function initAuthMiddleware(initParams: AuthMiddlewareParams) {
const {
url,
method = 'get',
errorCodes = [401],
getTokens,
setTokens,
getHeaders,
handleAuthError,
} = initParams;
const sanitizedUrl = typeof url === 'function' ? url() : url;

return async (...params: Parameters<MiddlewareHandler>) => {
const [options, meta] = params;
const currentSessionTokens = getTokens();
const headers =
typeof getHeaders === 'function' ?
getHeaders(meta) :
{ Authorization: `Bearer ${currentSessionTokens.accessToken}` };
{ Authorization: `Bearer ${currentSessionTokens.refreshToken}` };
const shouldProcessAuth = errorCodes.some(errorCode => errorCode === meta.status);

if (shouldProcessAuth) {
Expand All @@ -32,7 +34,7 @@ export function initAuthMiddleware(initParams: AuthMiddlewareParams) {
// eslint-disable-next-line no-console
() => console.warn('Failed to refresh authorization token');

return fetch(url, { method: 'post', body, headers })
return fetch(sanitizedUrl, { method, body, headers })
.then(async (response) => {
const tokens = await response.json().catch(() => null) as ReturnType<AuthMiddlewareParams['getTokens']> | null;
const { accessToken } = getTokens(tokens);
Expand Down
3 changes: 2 additions & 1 deletion src/middleware/auth/types.d.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export interface AuthMiddlewareParams {
url: string;
url: string | (() => string);
method?: RequestInit['method'];
errorCodes?: Response['status'][];
getTokens: (tokens?: unknown) => { accessToken: string; refreshToken: string };
setTokens: (tokens?: unknown) => void;
Expand Down

0 comments on commit 4a06d67

Please sign in to comment.