-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.ts
61 lines (51 loc) · 1.58 KB
/
client.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
import { config } from "./config.ts";
import type { ListParams, FetchRequest, FireResponse } from "./types.ts";
const extractParams = ({
pageSize,
pageToken,
orderBy,
mask,
showMissing,
}: Partial<FetchRequest>): ListParams => {
const size = pageSize ? `?pageSize=${Number(pageSize)}` : "";
const page = pageToken ? `${size ? "&" : "?"}pageToken=${pageToken}` : "";
const order = orderBy ? `${size || page ? "&" : "?"}orderBy=${orderBy}` : "";
const missing = showMissing
? `${size || page || order ? "&" : "?"}showMissing=${showMissing}`
: "";
const fields = mask
? `${size || page || order || missing ? "&" : "?"}mask=${JSON.stringify(
mask
)}`
: "";
return {
size,
page,
order,
missing,
fields,
};
};
const client = {
request: async (params: FetchRequest): Promise<FireResponse> => {
const requestHeaders: HeadersInit = new Headers();
requestHeaders.set("Content-Type", "application/json");
const token = params?.authorization ?? config.token;
if (token) {
requestHeaders.set("Authorization", `Bearer ${token}`);
}
const { size, page, order, missing, fields } = extractParams(params);
const req = await fetch(
`${config.host(params?.project)}/databases/${
params?.database ?? config.firebaseDb
}/${params.url}${size}${page}${order}${missing}${fields}`,
{
method: params.method ?? "POST",
body: params?.reqBody && JSON.stringify(params.reqBody),
headers: requestHeaders,
}
);
return await req.json();
},
};
export { client };