-
Notifications
You must be signed in to change notification settings - Fork 10
/
mappings.ts
90 lines (80 loc) · 2.46 KB
/
mappings.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
// On first sight, you might think that the typings in this module could be improved.
// However, we don't have typings for the snake_case models which is why we don't
// gain much more confidence by removing 'any' here
import mapObject from "map-obj";
export const queryParamMapping: Record<string, string> = {
filterUsersId: "filter[users_id]",
filterCustomersId: "filter[customers_id]",
filterProjectsId: "filter[projects_id]",
filterServicesId: "filter[services_id]",
filterLumpsumServicesId: "filter[lumpsum_services_id]",
/** @deprecated Please don't use this anymore, it will be removed someday */
filterLumpsumsServicesId: "filter[lumpsum_services_id]",
filterBillable: "filter[billable]",
filterText: "filter[text]",
filterTextsId: "filter[texts_id]",
filterBudgetType: "filter[budget_type]",
filterLumpsumsId: "filter[lumpsums_id]",
filterTimeSince: "filter[time_since]",
filterTimeUntil: "filter[time_until]",
filterActive: "filter[active]",
filterFulltext: "filter[fulltext]",
// excludeIds needs to stay in camelCase.
// This seems to be an inconsistency in the API.
excludeIds: "excludeIds",
};
export const mapQueryParams = <Result = Record<string, unknown>>(
queryParams: Record<string, any>
) => {
return mapObject(
queryParams,
(key, value) => {
const mappedKey =
key in queryParamMapping
? queryParamMapping[key]
: camelCaseToSnakeCase(key);
return [mappedKey, value];
},
{
deep: true,
}
) as unknown as Result;
};
export const mapRequestBody = <Result = Record<string, unknown>>(
requestBody: Record<string, any>
) => {
return mapObject(
requestBody,
(key, value) => {
const mappedKey = camelCaseToSnakeCase(key);
return [mappedKey, value];
},
{
deep: true,
}
) as unknown as Result;
};
export const mapResponseBody = <Result = Record<string, unknown>>(
responseBody: Record<string, any>
) => {
return mapObject(
responseBody,
(key, value) => {
const mappedKey = snakeCaseToCamelCase(key);
return [mappedKey, value];
},
{
deep: true,
}
) as unknown as Result;
};
export const snakeCaseToCamelCase = (key: string) => {
return key.replace(/_+(\d*)([a-z])/gi, (_, $1, $2) => {
return ($1 + $2.toUpperCase()) as string;
});
};
export const camelCaseToSnakeCase = (key: string) => {
return key.replace(/(\d*)([A-Z])/g, (_, $1, $2) => {
return "_" + $1 + $2.toLowerCase();
});
};