| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112 |
- import assert from "assert";
- const API = process.env.NEXT_PUBLIC_API || "/api";
- export enum ApiMethods {
- GET = "GET",
- POST = "POST",
- PUT = "PUT",
- }
- export enum ApiResulState {
- SUCCESS,
- ERROR,
- }
- type SuccessApiResult = {
- state: ApiResulState.SUCCESS;
- message: string;
- user: User;
- };
- type FailureApiResult = { state: ApiResulState.ERROR; error: string };
- export type FetchApiResult = SuccessApiResult | FailureApiResult;
- type FetchApi = <T>(
- path: string,
- method: ApiMethods,
- body: T
- ) => Promise<FetchApiResult>;
- const fetchApi: FetchApi = async (path, method, body) => {
- try {
- const response = await fetch(`${API}${path}`, {
- method: method,
- body: JSON.stringify(body),
- headers: { "Content-Type": "application/json" },
- });
- const { message, ...result } = await response.json();
- if (response.ok) {
- return { state: ApiResulState.SUCCESS, message, user: result };
- } else {
- return {
- state: ApiResulState.ERROR,
- error: message.replace("Incorect", "Incorrect"),
- };
- }
- } catch (error) {
- return {
- state: ApiResulState.ERROR,
- error: `There was an error, please try again`,
- };
- }
- };
- export interface FetchApiInterface<T> {
- (body: T): Promise<FetchApiResult>;
- }
- export const login: FetchApiInterface<
- Pick<User, "email" | "password">
- > = async (body) => {
- const response = await fetchApi("/login", ApiMethods.POST, body);
- switch (response.state) {
- case ApiResulState.SUCCESS: {
- const user = await fetchUserData(body.email);
- return {
- ...response,
- user,
- };
- }
- default:
- return response;
- }
- };
- export const register: FetchApiInterface<
- Pick<User, "email" | "password">
- > = async (body) => {
- return fetchApi("/register", ApiMethods.POST, body);
- };
- export const updateUser: FetchApiInterface<
- Partial<User> & Pick<User, "id">
- > = async ({ id, ...body }) => {
- return fetchApi(`/user/${id}`, ApiMethods.PUT, body);
- };
- const fetchUsers = async (): Promise<Array<User>> => {
- const response = await fetch("/api/users");
- if (response.ok) {
- return response.json();
- } else {
- return Promise.resolve([]);
- }
- };
- const fetchUserData = async (email: string): Promise<User> => {
- const users = await fetchUsers();
- const user = users.find((user) => user.email === email);
- assert(user);
- return user;
- };
- const apiPaths = {
- login,
- register,
- updateUser,
- };
- export default apiPaths;
|