-
Notifications
You must be signed in to change notification settings - Fork 92
/
Copy pathsettings.ts
66 lines (56 loc) · 2.11 KB
/
settings.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
import type { HttpRequests } from "./http-requests.js";
import type { HttpRequestsWithEnqueuedTaskPromise } from "./task.js";
import type {
EnqueuedTaskPromise,
IndividualUpdatableSettings,
RecordAny,
} from "./types/index.js";
/** Each setting property mapped to their REST method required for updates. */
type MakeSettingsRecord = {
[TKey in keyof IndividualUpdatableSettings]: "put" | "patch";
};
/** Each setting property mapped to its get, update and reset functions. */
export type SettingFns = {
[TKey in keyof IndividualUpdatableSettings as `get${Capitalize<TKey>}`]: () => Promise<
IndividualUpdatableSettings[TKey]
>;
} & {
[TKey in keyof IndividualUpdatableSettings as `update${Capitalize<TKey>}`]: (
body: IndividualUpdatableSettings[TKey],
) => EnqueuedTaskPromise;
} & {
[TKey in keyof IndividualUpdatableSettings as `reset${Capitalize<TKey>}`]: () => EnqueuedTaskPromise;
};
function capitalize(str: string): string {
return str.charAt(0).toUpperCase() + str.slice(1);
}
function camelToKebabCase(str: string): string {
return str.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);
}
/** Returns an object containing all the setting functions. */
export function makeSettingFns(
httpRequest: HttpRequests,
httpRequestsWithTask: HttpRequestsWithEnqueuedTaskPromise,
basePath: string,
opts: MakeSettingsRecord,
): SettingFns {
const settingFns = {} as RecordAny;
for (const [name, method] of Object.entries(opts)) {
const uppercaseName = capitalize(name);
const path = `${basePath}/${camelToKebabCase(name)}`;
settingFns[`get${uppercaseName}`] = async function (): Promise<
IndividualUpdatableSettings[keyof typeof opts]
> {
return await httpRequest.get({ path });
};
settingFns[`update${uppercaseName}`] = function (
body: IndividualUpdatableSettings[keyof typeof opts],
): EnqueuedTaskPromise {
return httpRequestsWithTask[method]({ path, body });
};
settingFns[`reset${uppercaseName}`] = function (): EnqueuedTaskPromise {
return httpRequestsWithTask.delete({ path });
};
}
return settingFns as SettingFns;
}