wretch
Version:
A tiny wrapper built around fetch with an intuitive syntax.
1 lines • 2.62 kB
Source Map (JSON)
{"version":3,"file":"formUrl.min.mjs","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":["encodeQueryValue","key","value","encodeURIComponent","JSON","stringify","formUrl","wretch","input","this","body","formObject","Object","keys","map","Array","v","join","content"],"mappings":"AAEA,SAASA,EAAiBC,EAAaC,GACrC,OAAOC,mBAAmBF,GACxB,IACAE,mBACmB,iBAAVD,EACLE,KAAKC,UAAUH,GACf,GAAKA,EAEb,CA0CA,MAAMI,EAAqC,CACzCC,OAAQ,CACND,QAAQE,GACN,OAAOC,KACJC,KAAsB,iBAAVF,EAAqBA,GA7ClBG,EA6CyCH,EA5CxDI,OAAOC,KAAKF,GAChBG,KAAIb,IACH,MAAMC,EAAQS,EAAWV,GACzB,OAAIC,aAAiBa,MACZb,EAAMY,KAAIE,GAAKhB,EAAiBC,EAAKe,KAAIC,KAAK,KAEhDjB,EAAiBC,EAAKC,EAAM,IAEpCe,KAAK,OAqCDC,QAAQ,qCA9CjB,IAAwBP,CA+CnB"}