@duongtrungnguyen/next-helper
Version:
Helper library for Next.js 15
90 lines • 3.51 kB
JavaScript
import { cookies } from "next/headers";
import { getQueryString, parseToken } from "../utils";
import { libConfig } from "../configs";
class HttpClient {
/**
* Creates an instance of HttpClient.
* @param baseUrl - The base URL for the HTTP requests.
*/
constructor(baseUrl) {
this.baseUrl = baseUrl;
}
/**
* Makes an HTTP request.
* @template T - The expected response type.
* @param endpoint - The endpoint to send the request to.
* @param method - The HTTP method to use.
* @param body - The request body.
* @param config - Additional request configurations.
* @returns A promise that resolves to the response data or the raw response.
* @throws An error if the response is not ok.
*/
async request(endpoint, method, body, config = {}) {
var _a;
const { query, rawResponse, ...restConfig } = config;
const url = `${this.baseUrl}${endpoint}${query ? getQueryString(query) : ""}`;
const cookieStore = await cookies();
const accessToken = (_a = cookieStore.get(libConfig.auth.cookies.accessToken)) == null ? void 0 : _a.value;
const { body: serializedBody, headers: bodyHeaders } = this.serialize(body);
const response = await fetch(url, {
...restConfig,
method,
headers: {
Authorization: parseToken(accessToken),
...bodyHeaders,
...restConfig.headers
},
body: serializedBody
});
if (rawResponse) return response;
const contentType = response.headers.get("content-type");
let responseData;
if (contentType == null ? void 0 : contentType.includes("application/json")) {
responseData = await response.json();
} else {
responseData = await response.text();
}
if (!response.ok) {
throw new Error((responseData == null ? void 0 : responseData.message) || `${response.statusText}`);
}
return responseData;
}
/**
* Serializes the request body into a format suitable for HTTP requests.
*
* @param body - The request body to be serialized. It can be of type `FormData`, `Blob`, `ArrayBuffer`, `URLSearchParams`, or a plain object.
* @returns An object containing the serialized body and appropriate headers. If the body is `FormData`, `Blob`, or `ArrayBuffer`, it returns the body as is.
* If the body is `URLSearchParams`, it returns the body with `Content-Type` set to `application/x-www-form-urlencoded`.
* If the body is a plain object, it returns the JSON stringified body with `Content-Type` set to `application/json`.
*/
serialize(body) {
if (body instanceof FormData || body instanceof Blob || body instanceof ArrayBuffer) {
return { body };
}
if (body instanceof URLSearchParams) {
return { body, headers: { "Content-Type": "application/x-www-form-urlencoded" } };
}
if (body && typeof body === "object") {
return { body: JSON.stringify(body), headers: { "Content-Type": "application/json" } };
}
return {};
}
async get(endpoint, config) {
return this.request(endpoint, "GET", void 0, config);
}
async post(endpoint, body, config) {
return this.request(endpoint, "POST", body, config);
}
async put(endpoint, body, config) {
return this.request(endpoint, "PUT", body, config);
}
async delete(endpoint, config) {
return this.request(endpoint, "DELETE", void 0, config);
}
}
const httpClient = new HttpClient(libConfig.baseUrl);
export {
HttpClient,
httpClient
};
//# sourceMappingURL=http.js.map