wretch
Version:
A tiny wrapper built around fetch with an intuitive syntax.
1 lines • 2.49 kB
Source Map (JSON)
{"version":3,"file":"formUrl.min.cjs","names":[],"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, E>(this: T & Wretch<T, C, R, E>, 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"],"mappings":"AAEA,SAAS,EAAiB,EAAa,EAAgB,CACrD,OAAO,mBAAmB,EAAI,CAC5B,IACA,mBACE,OAAO,GAAU,SACf,KAAK,UAAU,EAAM,CACrB,GAAK,EACR,CAEL,SAAS,EAAe,EAAoB,CAC1C,OAAO,OAAO,KAAK,EAAW,CAC3B,IAAI,GAAO,CACV,IAAM,EAAQ,EAAW,GAIzB,OAHI,aAAiB,MACZ,EAAM,IAAI,GAAK,EAAiB,EAAK,EAAE,CAAC,CAAC,KAAK,IAAI,CAEpD,EAAiB,EAAK,EAAM,EACnC,CACD,KAAK,IAAI,CAgCd,MAAM,EAAqC,CACzC,OAAQ,CACN,QAAQ,EAAO,CACb,OAAO,KACJ,KAAK,OAAO,GAAU,SAAW,EAAQ,EAAe,EAAM,CAAC,CAC/D,QAAQ,oCAAoC,EAElD,CACF"}