@duongtrungnguyen/next-helper
Version:
Helper library for Next.js 15
115 lines • 4.63 kB
JavaScript
;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var http_exports = {};
__export(http_exports, {
HttpClient: () => HttpClient,
httpClient: () => httpClient
});
module.exports = __toCommonJS(http_exports);
var import_headers = require("next/headers");
var import_utils = require("../utils");
var import_configs = require("../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 ? (0, import_utils.getQueryString)(query) : ""}`;
const cookieStore = await (0, import_headers.cookies)();
const accessToken = (_a = cookieStore.get(import_configs.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: (0, import_utils.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(import_configs.libConfig.baseUrl);
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
HttpClient,
httpClient
});
//# sourceMappingURL=http.js.map