Added utils

This commit is contained in:
sianida26 2024-03-01 20:57:55 +07:00
parent 8f7b9e1788
commit fb20753c9d
2 changed files with 64 additions and 0 deletions

View File

@ -0,0 +1,33 @@
/**
* Converts a JSON object to FormData.
*
* @param json - The JSON object to be converted into FormData. The object can
* include nested objects and arrays. Nested objects are flattened according
* to the FormData encoding conventions, with keys indicating the path to each
* value and arrays being treated with indices.
* @returns A FormData object containing the keys and values from the input JSON.
* Each key in the JSON object is represented in the FormData, with its corresponding
* value. Nested objects and arrays are handled by appending square brackets to the key
* names to indicate the structure in the FormData.
*/
export default function jsonToFormData(json: Record<string, any>): FormData {
const formData = new FormData();
Object.keys(json).forEach((key) => {
const value = json[key];
if (Array.isArray(value)) {
// Handle array values by appending each item with an index
value.forEach((item, index) => {
formData.append(`${key}[${index}]`, item);
});
} else if (typeof value === "object" && value !== null) {
// Handle nested objects by appending each sub-key
Object.keys(value).forEach((subKey) => {
formData.append(`${key}[${subKey}]`, value[subKey]);
});
} else {
// Handle simple types (strings, numbers, etc.)
formData.append(key, value);
}
});
return formData;
}

View File

@ -0,0 +1,31 @@
import { headers } from "next/headers";
import BaseError from "../error/BaseError";
/**
* Ensures that the current request's content type is one of the allowed types.
* This function is intended to be used in Next.js API routes to validate request content types.
*
* @param contentTypes - A single content type string or an array of allowed content type strings.
* @throws {BaseError} Throws a BaseError if the current request's content type is not in the allowed content types.
*/
export default function onlyAllowFollowingContentType(
contentTypes: string | string[]
) {
// Retrieve the current request's content type.
const currentContentType = headers().get("Content-Type");
// Normalize the input parameter to an array to simplify the inclusion check.
const allowedContentTypes = Array.isArray(contentTypes)
? contentTypes
: [contentTypes];
// Check if the current content type is not among the allowed ones and throw an error if so.
if (!allowedContentTypes.includes(currentContentType ?? "")) {
throw new BaseError({
errorCode: "UNSUPPORTED_CONTENT_TYPE",
message:
"This content type is not supported. Please use one of the supported content types instead.",
statusCode: 400,
});
}
}