Move auth token logic to useApi hook.
This commit is contained in:
@@ -3,7 +3,7 @@ import { getSession } from './session';
|
||||
import { getAuthToken } from './auth';
|
||||
import { unauthorized, badRequest, serverError } from './response';
|
||||
|
||||
export function use(middleware) {
|
||||
export function createMiddleware(middleware) {
|
||||
return (req, res) =>
|
||||
new Promise((resolve, reject) => {
|
||||
middleware(req, res, result => {
|
||||
@@ -15,9 +15,9 @@ export function use(middleware) {
|
||||
});
|
||||
}
|
||||
|
||||
export const useCors = use(cors());
|
||||
export const useCors = createMiddleware(cors());
|
||||
|
||||
export const useSession = use(async (req, res, next) => {
|
||||
export const useSession = createMiddleware(async (req, res, next) => {
|
||||
let session;
|
||||
|
||||
try {
|
||||
@@ -35,7 +35,7 @@ export const useSession = use(async (req, res, next) => {
|
||||
next();
|
||||
});
|
||||
|
||||
export const useAuth = use(async (req, res, next) => {
|
||||
export const useAuth = createMiddleware(async (req, res, next) => {
|
||||
const token = await getAuthToken(req);
|
||||
|
||||
if (!token) {
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
import { makeUrl } from './url';
|
||||
import { AUTH_TOKEN } from './constants';
|
||||
|
||||
export const apiRequest = (method, url, body, headers) => {
|
||||
const authToken = getItem(AUTH_TOKEN);
|
||||
|
||||
return fetch(url, {
|
||||
method,
|
||||
cache: 'no-cache',
|
||||
@@ -11,7 +8,6 @@ export const apiRequest = (method, url, body, headers) => {
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
...(authToken ? { Authorization: `Bearer ${authToken}` } : {}),
|
||||
...headers,
|
||||
},
|
||||
body,
|
||||
|
||||
Reference in New Issue
Block a user