UNPKG

wretch

Version:

A tiny wrapper built around fetch with an intuitive syntax.

1 lines 2.47 kB
{"version":3,"file":"formUrl.min.cjs","sources":["../../../src/addons/formUrl.ts"],"sourcesContent":["import type { Wretch, WretchAddon } from \"../types.js\"\n\nfunction encodeQueryValue(key: string, value: unknown) {\n return encodeURIComponent(key) +\n \"=\" +\n encodeURIComponent(\n typeof value === \"object\" ?\n JSON.stringify(value) :\n \"\" + value\n )\n}\nfunction convertFormUrl(formObject: object) {\n return Object.keys(formObject)\n .map(key => {\n const value = formObject[key]\n if (value instanceof Array) {\n return value.map(v => encodeQueryValue(key, v)).join(\"&\")\n }\n return encodeQueryValue(key, value)\n })\n .join(\"&\")\n}\n\nexport interface FormUrlAddon {\n /**\n * Converts the input parameter to an url encoded string and sets the content-type\n * header and body. If the input argument is already a string, skips the conversion\n * part.\n *\n * ```js\n * const form = { a: 1, b: { c: 2 } };\n * const alreadyEncodedForm = \"a=1&b=%7B%22c%22%3A2%7D\";\n *\n * // Automatically sets the content-type header to \"application/x-www-form-urlencoded\"\n * wretch(\"...\").addon(FormUrlAddon).formUrl(form).post();\n * wretch(\"...\").addon(FormUrlAddon).formUrl(alreadyEncodedForm).post();\n * ```\n *\n * @param input - An object to convert into an url encoded string or an already encoded string\n */\n formUrl<T extends FormUrlAddon, C, R>(this: T & Wretch<T, C, R>, input: (object | string)): this\n}\n\n/**\n * Adds the ability to convert a an object to a FormUrl and use it as a request body.\n *\n * ```js\n * import FormUrlAddon from \"wretch/addons/formUrl\"\n *\n * wretch().addon(FormUrlAddon)\n * ```\n */\nconst formUrl: WretchAddon<FormUrlAddon> = {\n wretch: {\n formUrl(input) {\n return this\n .body(typeof input === \"string\" ? input : convertFormUrl(input))\n .content(\"application/x-www-form-urlencoded\")\n }\n }\n}\n\nexport default formUrl\n"],"names":["encodeURIComponent","value","JSON","stringify","wretch","input","this","body","formObject","Object","keys","map","key","Array","encodeQueryValue","v","join"],"mappings":"6CAEA,IACSA,mBAAuB,iBAAAC,EACzBC,KAAAC,UAAAF,GACe,GAAAA,EAEd,UA4CLG,OAAA,SACwCC,GACjC,OAAAC,KACEC,KAAK,iBAAAF,EAAAA,GA7CZG,EA6CYH,EA5ChBI,OAAAC,KAAAF,GACQG,KAAAC,UACMX,EAAKO,EAAWI,GAC1B,OAAGX,aAAOY,MACEZ,UAAca,EAAIF,EAAAG,KAAAC,KAAA,SAEWf,EAAA,wBAuC7B,yCA9CZO,CA+CI"}