From f96e6174fe90f3d2b1e3016861017cfcc25a6ddc Mon Sep 17 00:00:00 2001 From: eug-vs Date: Sat, 14 Nov 2020 23:11:06 +0300 Subject: feat: add APIClient --- src/hooks/APIClient.ts | 17 +++++++++++++++++ src/requests.ts | 27 +++++++++++++++++++++++++++ src/types.ts | 12 ++++++++++++ 3 files changed, 56 insertions(+) create mode 100644 src/hooks/APIClient.ts create mode 100644 src/requests.ts create mode 100644 src/types.ts (limited to 'src') diff --git a/src/hooks/APIClient.ts b/src/hooks/APIClient.ts new file mode 100644 index 0000000..d3c4542 --- /dev/null +++ b/src/hooks/APIClient.ts @@ -0,0 +1,17 @@ +import useSWR, { responseInterface } from 'swr'; +import { get } from '../requests'; +import { User, Event } from '../types'; + +type Response = responseInterface; + +const fetcher = (endpoint: string) => get(endpoint).then(response => response.data); + + +export const useUser = (id: string): Response => { + return useSWR(id && `/users/${id}`, fetcher); +}; + +export const useEvents = (): Response => { + return useSWR(`/events`, fetcher); +}; + diff --git a/src/requests.ts b/src/requests.ts new file mode 100644 index 0000000..368ae40 --- /dev/null +++ b/src/requests.ts @@ -0,0 +1,27 @@ +import axios from 'axios'; +import _ from 'lodash'; + +const baseURL = process.env.NODE_ENV === 'production' + ? 'https://bsu-fantom.herokuapp.com' + : 'http://localhost:3030'; + +const requests = axios.create({ baseURL }); + +requests.interceptors.request.use(config => { + const token = localStorage.getItem('token'); + return _.set(config, 'headers.Authorization', token); +}); + +requests.interceptors.response.use(response => response, error => { + if (error.message === 'Request failed with status code 401' && localStorage.getItem('token')) { + localStorage.removeItem('remember'); + window.location.reload(); + } + return Promise.reject(error); +}); + +export const { + get, post, put, patch +} = requests; +export default requests; + diff --git a/src/types.ts b/src/types.ts new file mode 100644 index 0000000..dc429a4 --- /dev/null +++ b/src/types.ts @@ -0,0 +1,12 @@ +interface Base { + _id: string; + createdAt: string; + updatedAt: string; +} + +export interface User extends Base { + username: string; +} + +export interface Event extends Base {} + -- cgit v1.2.3