fork of hey-api/openapi-ts because I need some additional things
1import type {
2 ArrayStyle,
3 ObjectStyle,
4 SerializerOptions,
5} from './pathSerializer';
6
7export type QuerySerializer = (query: Record<string, unknown>) => string;
8
9export type BodySerializer = (body: any) => any;
10
11type QuerySerializerOptionsObject = {
12 allowReserved?: boolean;
13 array?: Partial<SerializerOptions<ArrayStyle>>;
14 object?: Partial<SerializerOptions<ObjectStyle>>;
15};
16
17export type QuerySerializerOptions = QuerySerializerOptionsObject & {
18 /**
19 * Per-parameter serialization overrides. When provided, these settings
20 * override the global array/object settings for specific parameter names.
21 */
22 parameters?: Record<string, QuerySerializerOptionsObject>;
23};
24
25const serializeFormDataPair = (
26 data: FormData,
27 key: string,
28 value: unknown,
29): void => {
30 if (typeof value === 'string' || value instanceof Blob) {
31 data.append(key, value);
32 } else {
33 data.append(key, JSON.stringify(value));
34 }
35};
36
37const serializeUrlSearchParamsPair = (
38 data: URLSearchParams,
39 key: string,
40 value: unknown,
41): void => {
42 if (typeof value === 'string') {
43 data.append(key, value);
44 } else {
45 data.append(key, JSON.stringify(value));
46 }
47};
48
49export const formDataBodySerializer = {
50 bodySerializer: <T extends Record<string, any> | Array<Record<string, any>>>(
51 body: T,
52 ): FormData => {
53 const data = new FormData();
54
55 Object.entries(body).forEach(([key, value]) => {
56 if (value === undefined || value === null) {
57 return;
58 }
59 if (Array.isArray(value)) {
60 value.forEach((v) => serializeFormDataPair(data, key, v));
61 } else {
62 serializeFormDataPair(data, key, value);
63 }
64 });
65
66 return data;
67 },
68};
69
70export const jsonBodySerializer = {
71 bodySerializer: <T>(body: T): string =>
72 JSON.stringify(body, (_key, value) =>
73 typeof value === 'bigint' ? value.toString() : value,
74 ),
75};
76
77export const urlSearchParamsBodySerializer = {
78 bodySerializer: <T extends Record<string, any> | Array<Record<string, any>>>(
79 body: T,
80 ): string => {
81 const data = new URLSearchParams();
82
83 Object.entries(body).forEach(([key, value]) => {
84 if (value === undefined || value === null) {
85 return;
86 }
87 if (Array.isArray(value)) {
88 value.forEach((v) => serializeUrlSearchParamsPair(data, key, v));
89 } else {
90 serializeUrlSearchParamsPair(data, key, value);
91 }
92 });
93
94 return data.toString();
95 },
96};