-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
69 lines (60 loc) · 1.44 KB
/
index.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
const LANGUAGES = ["vi", "en"] as const;
export type ModelData<T extends string[]> = Record<
T[number],
boolean | string | number | Date
>;
/**
* @description query options
*/
export class Context {
host: string;
lang: (typeof LANGUAGES)[number] = "vi";
}
type GenericQueryOptions = {
offset?: number;
limit?: number;
search?: string;
locale?: Context["lang"];
slug?: string;
};
type ManualQueryOptions<T extends string[]> = {
fields?: (T[number] | `${T[number]}(${string})`)[];
};
type QueryOptions<K extends string[]> = GenericQueryOptions &
ManualQueryOptions<K>;
export class Model<K extends string[], T extends ModelData<K>> {
readonly ctx: Context;
readonly kind: string;
constructor(ctx: Context, kind: `${string}.${string}`) {
this.ctx = ctx;
this.kind = kind;
}
requestBuilder(options: QueryOptions<K>): URL {
const params = new URLSearchParams(
Object.assign(
{},
{
type: this.kind,
...Object.keys(options).reduce(
(p, k) =>
Object.assign({}, p, {
[k]:
k === "fields"
? options.fields.join(",")
: options[k].toString(),
}),
{},
),
},
),
);
const url = new URL(this.ctx.host);
url.pathname = "/api/v2/pages";
url.search = params.toString();
return url;
}
async query(options: QueryOptions<K>): Promise<T[]> {
return fetch(this.requestBuilder(options)).then((ok) => ok.json());
}
}
export abstract class Searchable {}