import { redirect } from "@/i18n/routing"; import { Response } from "@/types"; import { cookies } from "next/headers"; import { ServerOptions } from "./type"; const requestInterceptor = (options: ServerOptions) => { // εˆ€ζ–­token if (options.checkToken) { const token = cookies().has("Token"); if (!token) { redirect({ href: "/login", locale: "en" }); } } return options; }; const responseInterceptor = ( response: Response & R, options: ServerOptions, url: string ): Promise & R> => { return new Promise((resolve, reject) => { const { code, msg } = response; switch (code) { case 200: resolve(response); break; case 401: console.log(`πŸš€πŸš€πŸš€πŸš€πŸš€->server-code: 401`, options.url); redirect({ href: "/login", locale: "en" }); break; case 500: reject(response); break; default: console.log({ ...response, ...options, message: `please check api ${url}${options.url}`, }); resolve(response); } }); }; class Server { private static instance: Server; private BASE_URL: string; constructor() { this.BASE_URL = process.env.NEXT_PUBLIC_BASE_URL as string; } async request(options: ServerOptions): Promise & R> { options = requestInterceptor(options); const { method = "GET", url, headers = {}, data = {}, body, ...other } = options; const params = JSON.stringify(data); try { const response = await fetch(`${this.BASE_URL}${url}`, { method: method, headers: { Token: cookies().get("Token")?.value || "", "Content-Type": "application/json", language: cookies().get("language")?.value || cookies().get("NEXT_LOCALE")?.value, ...headers, }, body: params, ...other, }) .then((res) => res.json()) .catch((error) => { console.log(`πŸš€πŸš€πŸš€πŸš€πŸš€-> in index.ts on 68`, error); return {}; }); return responseInterceptor(response, options, this.BASE_URL); } catch (error) { console.log( `πŸš€πŸš€πŸš€πŸš€πŸš€-> in index.ts on 67`, error, `${this.BASE_URL}${options.url}`, JSON.stringify(options) ); return Promise.reject(error); } } } export const server = new Server();