-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.ts
68 lines (57 loc) · 2.17 KB
/
utils.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
type StrapiQuery = {
key: string,
value: string,
index: string|string[]|null,
}
export default class StrapiQueryGenerator {
private readonly base: string;
private params: StrapiQuery[];
constructor(base: string, params: StrapiQuery[] = []) {
this.base = base;
this.params = params;
}
private addParam(param: string, value: string, index: string|string[]|null) {
return new StrapiQueryGenerator(this.base, [...this.params, {key: param, index: index, value: value}]);
}
private getIndex(key: string) {
return this.params.filter((param) => param.key === key).length.toString();
}
public sortBy(sort: string, opt: "asc" | "desc" = "asc") {
let index = this.getIndex("sort");
return this.addParam("sort", sort+"%3A"+opt, index);
}
public paginate(currentPage: number, itemsPerPage: number) {
return this.addParam("pagination", currentPage.toString(), "page").addParam("pagination", itemsPerPage.toString(), "pageSize");
}
public filter_fields(fields: string[]) {
let n: StrapiQueryGenerator = this;
for (let i = 0; i < fields.length; i++) {
n = n.addParam("fields", fields[i], n.getIndex("fields"));
}
return n;
}
public populateAll() {
return this.addParam("populate", "*", null);
}
public populate(field: string, indexes: string[]) {
return this.addParam("populate", field, indexes);
}
public toString() {
let url = this.base;
for (let i = 0; i < this.params.length; i++) {
let param = this.params[i];
url += (i === 0 ? "?" : "&") + param.key + (param.index ? Array.isArray(param.index) ? param.index.map(v => "[" + v + "]").join("")+"=" : "[" + param.index + "]=" : "=") + param.value;
}
return url;
}
}
export function formatDate(date: Date): string {
// TODO split into files
// YYYY-MM-DD HH:MM
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();
const hour = date.getHours();
const minute = date.getMinutes();
return `${year}-${month}-${day} ${hour}:${minute}`
}