-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathsort.ts
99 lines (83 loc) · 2.15 KB
/
sort.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
91
92
93
94
95
96
97
98
99
export default class GraphQLSort {
private errors: string[];
private order?: string;
private path?: string[];
private sortArgs: any[];
private source: any;
constructor(sortObj: any) {
this.source = sortObj;
this.sortArgs = [];
this.errors = []
}
toString() {
this.parse();
this.validate();
let args: any[] = [];
if (this.sortArgs.length > 0) {
args = [...args, this.sortArgs];
} else {
if (this.path) {
args = [...args, `path:${JSON.stringify(this.path)}`];
}
if (this.order) {
args = [...args, `order:${this.order}`];
}
}
if (this.sortArgs.length > 0) {
return `${args.join(",")}`;
}
return `{${args.join(",")}}`;
}
validate() {
if (this.sortArgs.length == 0) {
this.validatePath(this.path)
}
}
validatePath(path: any) {
if (!path) {
throw new Error("sort filter: path needs to be set");
}
if (path.length == 0) {
throw new Error("sort filter: path cannot be empty");
}
}
parse() {
for (let key in this.source) {
switch (key) {
case "path":
this.parsePath(this.source[key]);
break;
case "order":
this.parseOrder(this.source[key]);
break;
default:
try {
this.sortArgs = [...this.sortArgs, this.parseSortArgs(this.source[key])];
} catch(e: any) {
this.errors = [...this.errors, `sort argument at ${key}: ${e.message}`];
}
}
}
if (this.errors.length > 0) {
throw new Error(`sort filter: ${this.errors.join(", ")}`);
}
}
parseSortArgs(args: any) {
return new GraphQLSort(args).toString();
}
parsePath(path: string[]) {
if (!Array.isArray(path)) {
throw new Error("sort filter: path must be an array");
}
this.path = path;
}
parseOrder(order: string) {
if (typeof order !== "string") {
throw new Error("sort filter: order must be a string");
}
if (order !== "asc" && order !== "desc") {
throw new Error("sort filter: order parameter not valid, possible values are: asc, desc");
}
this.order = order;
}
}