import { redirect } from "@/i18n"; import { Response } from "@/types"; import { cookies } from "next/headers"; import { ServerOptions } from "./type"; import { locales } from "@/i18n"; const requestInterceptor = (options: ServerOptions) => { // εˆ€ζ–­token if (options.checkToken) { const token = cookies().has("Token"); if (!token) { redirect("/login"); } } 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("/login"); break; default: console.log({ ...response, ...options, message: `please check api ${url}${options.url}`, }); reject(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 === "br" ? "pt" : cookies().get("language")?.value || locales.at(2)!, ...headers, }, body: params, ...other, }).then((res) => res.json()); return responseInterceptor(response, options, this.BASE_URL); } catch (error) { return Promise.reject(error); } } } export const server = new Server();