Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: handle nested values in formDataBodySerializer #1609

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/great-taxis-do.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@hey-api/client-core': patch
---

fix: handle nested values in formDataBodySerializer
54 changes: 54 additions & 0 deletions packages/client-core/src/__tests__/bodySerializer.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { describe, expect, it } from 'vitest';

import { formDataBodySerializer } from '../bodySerializer';

describe('formDataBodySerializer', () => {
const { bodySerializer } = formDataBodySerializer;

it('object with primitive values', async () => {
const data = bodySerializer({
bar: 1,
baz: true,
foo: 'bar',
});
expect(data.get('foo')).toBe('bar');
expect(data.get('bar')).toBe('1');
expect(data.get('baz')).toBe('true');
});

it('array with primitive values', async () => {
const data = bodySerializer([1, true, 'bar']);
expect(data.get('array[0]')).toBe('1');
expect(data.get('array[1]')).toBe('true');
expect(data.get('array[2]')).toBe('bar');
});

it('primitive value', async () => {
const data = bodySerializer(1);
expect(data.get('key')).toBe('1');
});

it('nested array with primitive values', async () => {
const data = bodySerializer({
foo: [[1, true, 'bar']],
});
expect(data.get('foo[0][0]')).toBe('1');
expect(data.get('foo[0][1]')).toBe('true');
expect(data.get('foo[0][2]')).toBe('bar');
});

it('nested object with primitive values', async () => {
const data = bodySerializer({
foo: {
bar: {
bar: 1,
baz: true,
foo: 'bar',
},
},
});
expect(data.get('foo[bar][foo]')).toBe('bar');
expect(data.get('foo[bar][bar]')).toBe('1');
expect(data.get('foo[bar][baz]')).toBe('true');
});
});
56 changes: 32 additions & 24 deletions packages/client-core/src/bodySerializer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,24 +4,16 @@ import type {
SerializerOptions,
} from './pathSerializer';

export type QuerySerializer = (query: Record<string, unknown>) => string;

export type BodySerializer = (body: any) => any;

export type QuerySerializer = (query: Record<string, unknown>) => string;

export interface QuerySerializerOptions {
allowReserved?: boolean;
array?: SerializerOptions<ArrayStyle>;
object?: SerializerOptions<ObjectStyle>;
}

const serializeFormDataPair = (data: FormData, key: string, value: unknown) => {
if (typeof value === 'string' || value instanceof Blob) {
data.append(key, value);
} else {
data.append(key, JSON.stringify(value));
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It might be nice to warn when stringifying a non-JSON type. I ran into issues initially when passing a FileList to a form, expecting it to be serialized as a blob array. Instead, it came out as {}.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Honestly I think that's more on us to handle properly

}
};

const serializeUrlSearchParamsPair = (
data: URLSearchParams,
key: string,
Expand All @@ -34,23 +26,39 @@ const serializeUrlSearchParamsPair = (
}
};

export const formDataBodySerializer = {
bodySerializer: <T extends Record<string, any> | Array<Record<string, any>>>(
body: T,
) => {
const data = new FormData();
const serializeFormBody = <T>(data: FormData, value: T, key?: string) => {
if (value === null || value === undefined) {
return;
}

Object.entries(body).forEach(([key, value]) => {
if (value === undefined || value === null) {
return;
}
if (Array.isArray(value)) {
value.forEach((v) => serializeFormDataPair(data, key, v));
} else {
serializeFormDataPair(data, key, value);
}
if (typeof value === 'string' || value instanceof Blob) {
return data.append(key ?? 'key', value);
}

if (typeof value !== 'object') {
return data.append(key ?? 'key', JSON.stringify(value));
}

if (Array.isArray(value)) {
value.forEach((item, index) => {
serializeFormBody(
data,
item,
key ? `${key}[${index}]` : `array[${index}]`,
);
});
return;
}

for (const [k, v] of Object.entries(value)) {
serializeFormBody(data, v, key ? `${key}[${k}]` : k);
}
};

export const formDataBodySerializer = {
bodySerializer: <T>(body: T) => {
const data = new FormData();
serializeFormBody(data, body);
return data;
},
};
Expand Down
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
'use strict';var D=require('axios');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var D__default=/*#__PURE__*/_interopDefault(D);var R=async(t,e)=>{let r=typeof e=="function"?await e(t):e;if(r)return t.scheme==="bearer"?`Bearer ${r}`:t.scheme==="basic"?`Basic ${btoa(r)}`:r},w=(t,e,r)=>{typeof r=="string"||r instanceof Blob?t.append(e,r):t.append(e,JSON.stringify(r));},C=(t,e,r)=>{typeof r=="string"?t.append(e,r):t.append(e,JSON.stringify(r));},O={bodySerializer:t=>{let e=new FormData;return Object.entries(t).forEach(([r,i])=>{i!=null&&(Array.isArray(i)?i.forEach(a=>w(e,r,a)):w(e,r,i));}),e}},q={bodySerializer:t=>JSON.stringify(t)},v={bodySerializer:t=>{let e=new URLSearchParams;return Object.entries(t).forEach(([r,i])=>{i!=null&&(Array.isArray(i)?i.forEach(a=>C(e,r,a)):C(e,r,i));}),e}},$=t=>{switch(t){case "label":return ".";case "matrix":return ";";case "simple":return ",";default:return "&"}},P=t=>{switch(t){case "form":return ",";case "pipeDelimited":return "|";case "spaceDelimited":return "%20";default:return ","}},k=t=>{switch(t){case "label":return ".";case "matrix":return ";";case "simple":return ",";default:return "&"}},h=({allowReserved:t,explode:e,name:r,style:i,value:a})=>{if(!e){let n=(t?a:a.map(o=>encodeURIComponent(o))).join(P(i));switch(i){case "label":return `.${n}`;case "matrix":return `;${r}=${n}`;case "simple":return n;default:return `${r}=${n}`}}let s=$(i),l=a.map(n=>i==="label"||i==="simple"?t?n:encodeURIComponent(n):d({allowReserved:t,name:r,value:n})).join(s);return i==="label"||i==="matrix"?s+l:l},d=({allowReserved:t,name:e,value:r})=>{if(r==null)return "";if(typeof r=="object")throw new Error("Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these.");return `${e}=${t?r:encodeURIComponent(r)}`},g=({allowReserved:t,explode:e,name:r,style:i,value:a})=>{if(a instanceof Date)return `${r}=${a.toISOString()}`;if(i!=="deepObject"&&!e){let n=[];Object.entries(a).forEach(([u,f])=>{n=[...n,u,t?f:encodeURIComponent(f)];});let o=n.join(",");switch(i){case "form":return `${r}=${o}`;case "label":return `.${o}`;case "matrix":return `;${r}=${o}`;default:return o}}let s=k(i),l=Object.entries(a).map(([n,o])=>d({allowReserved:t,name:i==="deepObject"?`${r}[${n}]`:n,value:o})).join(s);return i==="label"||i==="matrix"?s+l:l};var E=/\{[^{}]+\}/g,U=({path:t,url:e})=>{let r=e,i=e.match(E);if(i)for(let a of i){let s=false,l=a.substring(1,a.length-1),n="simple";l.endsWith("*")&&(s=true,l=l.substring(0,l.length-1)),l.startsWith(".")?(l=l.substring(1),n="label"):l.startsWith(";")&&(l=l.substring(1),n="matrix");let o=t[l];if(o==null)continue;if(Array.isArray(o)){r=r.replace(a,h({explode:s,name:l,style:n,value:o}));continue}if(typeof o=="object"){r=r.replace(a,g({explode:s,name:l,style:n,value:o}));continue}if(n==="matrix"){r=r.replace(a,`;${d({name:l,value:o})}`);continue}let u=encodeURIComponent(n==="label"?`.${o}`:o);r=r.replace(a,u);}return r},B=({allowReserved:t,array:e,object:r}={})=>a=>{let s=[];if(a&&typeof a=="object")for(let l in a){let n=a[l];if(n!=null){if(Array.isArray(n)){s=[...s,h({allowReserved:t,explode:true,name:l,style:"form",value:n,...e})];continue}if(typeof n=="object"){s=[...s,g({allowReserved:t,explode:true,name:l,style:"deepObject",value:n,...r})];continue}s=[...s,d({allowReserved:t,name:l,value:n})];}}return s.join("&")},A=async({security:t,...e})=>{for(let r of t){let i=await R(r,e.auth);if(!i)continue;let a=r.name??"Authorization";switch(r.in){case "query":e.query||(e.query={}),e.query[a]=i;break;case "header":default:e.headers[a]=i;break}return}},b=t=>H({path:t.path,query:t.paramsSerializer?undefined:t.query,querySerializer:typeof t.querySerializer=="function"?t.querySerializer:B(t.querySerializer),url:t.url}),H=({path:t,query:e,querySerializer:r,url:i})=>{let s=i.startsWith("/")?i:`/${i}`;t&&(s=U({path:t,url:s}));let l=e?r(e):"";return l.startsWith("?")&&(l=l.substring(1)),l&&(s+=`?${l}`),s},x=(t,e)=>{let r={...t,...e};return r.headers=y(t.headers,e.headers),r},T=["common","delete","get","head","patch","post","put"],y=(...t)=>{let e={};for(let r of t){if(!r||typeof r!="object")continue;let i=Object.entries(r);for(let[a,s]of i)if(T.includes(a)&&typeof s=="object")e[a]={...e[a],...s};else if(s===null)delete e[a];else if(Array.isArray(s))for(let l of s)e[a]=[...e[a]??[],l];else s!==undefined&&(e[a]=typeof s=="object"?JSON.stringify(s):s);}return e},S=(t={})=>({baseURL:"",...t});var L=t=>{let e=x(S(),t),{auth:r,...i}=e,a=D__default.default.create(i),s=()=>({...e}),l=o=>(e=x(e,o),a.defaults={...a.defaults,...e,headers:y(a.defaults.headers,e.headers)},s()),n=async o=>{let u={...e,...o,axios:o.axios??e.axios??a,headers:y(e.headers,o.headers)};u.security&&await A({...u,security:u.security}),u.body&&u.bodySerializer&&(u.body=u.bodySerializer(u.body));let f=b(u);try{let m=u.axios,{auth:c,...j}=u,z=await m({...j,data:u.body,headers:u.headers,params:u.paramsSerializer?u.query:void 0,url:f}),{data:p}=z;return u.responseType==="json"&&(u.responseValidator&&await u.responseValidator(p),u.responseTransformer&&(p=await u.responseTransformer(p))),{...z,data:p??{}}}catch(m){let c=m;if(u.throwOnError)throw c;return c.error=c.response?.data??{},c}};return {buildUrl:b,delete:o=>n({...o,method:"delete"}),get:o=>n({...o,method:"get"}),getConfig:s,head:o=>n({...o,method:"head"}),instance:a,options:o=>n({...o,method:"options"}),patch:o=>n({...o,method:"patch"}),post:o=>n({...o,method:"post"}),put:o=>n({...o,method:"put"}),request:n,setConfig:l}};exports.createClient=L;exports.createConfig=S;exports.formDataBodySerializer=O;exports.jsonBodySerializer=q;exports.urlSearchParamsBodySerializer=v;//# sourceMappingURL=index.cjs.map
'use strict';var D=require('axios');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var D__default=/*#__PURE__*/_interopDefault(D);var R=async(r,e)=>{let t=typeof e=="function"?await e(r):e;if(t)return r.scheme==="bearer"?`Bearer ${t}`:r.scheme==="basic"?`Basic ${btoa(t)}`:t},C=(r,e,t)=>{typeof t=="string"?r.append(e,t):r.append(e,JSON.stringify(t));},h=(r,e,t)=>{if(e!=null){if(typeof e=="string"||e instanceof Blob)return r.append(t??"key",e);if(typeof e!="object")return r.append(t??"key",JSON.stringify(e));if(Array.isArray(e)){e.forEach((n,a)=>{h(r,n,t?`${t}[${a}]`:`array[${a}]`);});return}for(let[n,a]of Object.entries(e))h(r,a,t?`${t}[${n}]`:n);}},O={bodySerializer:r=>{let e=new FormData;return h(e,r),e}},$={bodySerializer:r=>JSON.stringify(r)},q={bodySerializer:r=>{let e=new URLSearchParams;return Object.entries(r).forEach(([t,n])=>{n!=null&&(Array.isArray(n)?n.forEach(a=>C(e,t,a)):C(e,t,n));}),e}},v=r=>{switch(r){case "label":return ".";case "matrix":return ";";case "simple":return ",";default:return "&"}},k=r=>{switch(r){case "form":return ",";case "pipeDelimited":return "|";case "spaceDelimited":return "%20";default:return ","}},P=r=>{switch(r){case "label":return ".";case "matrix":return ";";case "simple":return ",";default:return "&"}},g=({allowReserved:r,explode:e,name:t,style:n,value:a})=>{if(!e){let o=(r?a:a.map(i=>encodeURIComponent(i))).join(k(n));switch(n){case "label":return `.${o}`;case "matrix":return `;${t}=${o}`;case "simple":return o;default:return `${t}=${o}`}}let s=v(n),l=a.map(o=>n==="label"||n==="simple"?r?o:encodeURIComponent(o):f({allowReserved:r,name:t,value:o})).join(s);return n==="label"||n==="matrix"?s+l:l},f=({allowReserved:r,name:e,value:t})=>{if(t==null)return "";if(typeof t=="object")throw new Error("Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these.");return `${e}=${r?t:encodeURIComponent(t)}`},b=({allowReserved:r,explode:e,name:t,style:n,value:a})=>{if(a instanceof Date)return `${t}=${a.toISOString()}`;if(n!=="deepObject"&&!e){let o=[];Object.entries(a).forEach(([u,d])=>{o=[...o,u,r?d:encodeURIComponent(d)];});let i=o.join(",");switch(n){case "form":return `${t}=${i}`;case "label":return `.${i}`;case "matrix":return `;${t}=${i}`;default:return i}}let s=P(n),l=Object.entries(a).map(([o,i])=>f({allowReserved:r,name:n==="deepObject"?`${t}[${o}]`:o,value:i})).join(s);return n==="label"||n==="matrix"?s+l:l};var U=/\{[^{}]+\}/g,E=({path:r,url:e})=>{let t=e,n=e.match(U);if(n)for(let a of n){let s=false,l=a.substring(1,a.length-1),o="simple";l.endsWith("*")&&(s=true,l=l.substring(0,l.length-1)),l.startsWith(".")?(l=l.substring(1),o="label"):l.startsWith(";")&&(l=l.substring(1),o="matrix");let i=r[l];if(i==null)continue;if(Array.isArray(i)){t=t.replace(a,g({explode:s,name:l,style:o,value:i}));continue}if(typeof i=="object"){t=t.replace(a,b({explode:s,name:l,style:o,value:i}));continue}if(o==="matrix"){t=t.replace(a,`;${f({name:l,value:i})}`);continue}let u=encodeURIComponent(o==="label"?`.${i}`:i);t=t.replace(a,u);}return t},B=({allowReserved:r,array:e,object:t}={})=>a=>{let s=[];if(a&&typeof a=="object")for(let l in a){let o=a[l];if(o!=null){if(Array.isArray(o)){s=[...s,g({allowReserved:r,explode:true,name:l,style:"form",value:o,...e})];continue}if(typeof o=="object"){s=[...s,b({allowReserved:r,explode:true,name:l,style:"deepObject",value:o,...t})];continue}s=[...s,f({allowReserved:r,name:l,value:o})];}}return s.join("&")},A=async({security:r,...e})=>{for(let t of r){let n=await R(t,e.auth);if(!n)continue;let a=t.name??"Authorization";switch(t.in){case "query":e.query||(e.query={}),e.query[a]=n;break;case "header":default:e.headers[a]=n;break}return}},x=r=>H({path:r.path,query:r.paramsSerializer?undefined:r.query,querySerializer:typeof r.querySerializer=="function"?r.querySerializer:B(r.querySerializer),url:r.url}),H=({path:r,query:e,querySerializer:t,url:n})=>{let s=n.startsWith("/")?n:`/${n}`;r&&(s=E({path:r,url:s}));let l=e?t(e):"";return l.startsWith("?")&&(l=l.substring(1)),l&&(s+=`?${l}`),s},S=(r,e)=>{let t={...r,...e};return t.headers=y(r.headers,e.headers),t},T=["common","delete","get","head","patch","post","put"],y=(...r)=>{let e={};for(let t of r){if(!t||typeof t!="object")continue;let n=Object.entries(t);for(let[a,s]of n)if(T.includes(a)&&typeof s=="object")e[a]={...e[a],...s};else if(s===null)delete e[a];else if(Array.isArray(s))for(let l of s)e[a]=[...e[a]??[],l];else s!==undefined&&(e[a]=typeof s=="object"?JSON.stringify(s):s);}return e},z=(r={})=>({baseURL:"",...r});var L=r=>{let e=S(z(),r),{auth:t,...n}=e,a=D__default.default.create(n),s=()=>({...e}),l=i=>(e=S(e,i),a.defaults={...a.defaults,...e,headers:y(a.defaults.headers,e.headers)},s()),o=async i=>{let u={...e,...i,axios:i.axios??e.axios??a,headers:y(e.headers,i.headers)};u.security&&await A({...u,security:u.security}),u.body&&u.bodySerializer&&(u.body=u.bodySerializer(u.body));let d=x(u);try{let m=u.axios,{auth:c,...j}=u,w=await m({...j,data:u.body,headers:u.headers,params:u.paramsSerializer?u.query:void 0,url:d}),{data:p}=w;return u.responseType==="json"&&(u.responseValidator&&await u.responseValidator(p),u.responseTransformer&&(p=await u.responseTransformer(p))),{...w,data:p??{}}}catch(m){let c=m;if(u.throwOnError)throw c;return c.error=c.response?.data??{},c}};return {buildUrl:x,delete:i=>o({...i,method:"delete"}),get:i=>o({...i,method:"get"}),getConfig:s,head:i=>o({...i,method:"head"}),instance:a,options:i=>o({...i,method:"options"}),patch:i=>o({...i,method:"patch"}),post:i=>o({...i,method:"post"}),put:i=>o({...i,method:"put"}),request:o,setConfig:l}};exports.createClient=L;exports.createConfig=z;exports.formDataBodySerializer=O;exports.jsonBodySerializer=$;exports.urlSearchParamsBodySerializer=q;//# sourceMappingURL=index.cjs.map
//# sourceMappingURL=index.cjs.map
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,15 @@ interface SerializerOptions<T> {
type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited';
type ObjectStyle = 'form' | 'deepObject';

type QuerySerializer = (query: Record<string, unknown>) => string;
type BodySerializer = (body: any) => any;
type QuerySerializer = (query: Record<string, unknown>) => string;
interface QuerySerializerOptions {
allowReserved?: boolean;
array?: SerializerOptions<ArrayStyle>;
object?: SerializerOptions<ObjectStyle>;
}
declare const formDataBodySerializer: {
bodySerializer: <T extends Record<string, any> | Array<Record<string, any>>>(body: T) => FormData;
bodySerializer: <T>(body: T) => FormData;
};
declare const jsonBodySerializer: {
bodySerializer: <T>(body: T) => string;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,15 @@ interface SerializerOptions<T> {
type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited';
type ObjectStyle = 'form' | 'deepObject';

type QuerySerializer = (query: Record<string, unknown>) => string;
type BodySerializer = (body: any) => any;
type QuerySerializer = (query: Record<string, unknown>) => string;
interface QuerySerializerOptions {
allowReserved?: boolean;
array?: SerializerOptions<ArrayStyle>;
object?: SerializerOptions<ObjectStyle>;
}
declare const formDataBodySerializer: {
bodySerializer: <T extends Record<string, any> | Array<Record<string, any>>>(body: T) => FormData;
bodySerializer: <T>(body: T) => FormData;
};
declare const jsonBodySerializer: {
bodySerializer: <T>(body: T) => string;
Expand Down
Loading
Loading