UNPKG

hd-utils

Version:

A handy utils for modern JS developers

24 lines (23 loc) 1.48 kB
/** * @description Converts a JSON object into a specified multipart or URL-encoded formatted string. * * This function takes a JSON object and constructs a string that follows the specified * multipart format or URL-encoded format. It allows for arrays, objects, and simple data types, * supporting `form-data`, `related`, `mixed`, and `application/x-www-form-urlencoded`. * * @param {Record<string, unknown>} jsonData - The JSON object where keys are form field names * and values can be strings, numbers, arrays, or nested objects. * @param {string} [boundary] - The boundary string used to separate parts of the form data (required for multipart). * @param {'form-data' | 'related' | 'mixed' | 'urlencoded'} [type='form-data'] - The type of format to use. * @returns {string} - A string representing the specified formatted data. * * @example * const json = { username: 'john_doe', age: 30, files: ['file1.png', 'file2.jpg'] }; * const boundary = '----WebKitFormBoundary123456'; * const formDataText = jsonToFormDataText(json, boundary, 'form-data'); * console.log(formDataText); // Outputs multipart/form-data formatted string * * const urlEncodedText = jsonToFormDataText(json, undefined, 'urlencoded'); * console.log(urlEncodedText); // Outputs application/x-www-form-urlencoded string */ export default function jsonToFormDataText(jsonData: Record<string, unknown>, type?: 'form-data' | 'related' | 'mixed' | 'urlencoded', boundary?: string): string;