-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
sort.ts
93 lines (80 loc) · 2.3 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
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import {
PersistentModel,
SchemaModel,
SortPredicate,
ProducerSortPredicate,
SortDirection,
SortPredicatesGroup,
} from '../types';
export class ModelSortPredicateCreator {
private static sortPredicateGroupsMap = new WeakMap<
SortPredicate<any>,
SortPredicatesGroup<any>
>();
private static createPredicateBuilder<T extends PersistentModel>(
modelDefinition: SchemaModel
) {
const { name: modelName } = modelDefinition;
const fieldNames = new Set<keyof T>(Object.keys(modelDefinition.fields));
let handler: ProxyHandler<SortPredicate<T>>;
const predicate = new Proxy(
{} as SortPredicate<T>,
(handler = {
get(_target, propertyKey, receiver: SortPredicate<T>) {
const field = propertyKey as keyof T;
if (!fieldNames.has(field)) {
throw new Error(
`Invalid field for model. field: ${field}, model: ${modelName}`
);
}
const result = (sortDirection: SortDirection) => {
ModelSortPredicateCreator.sortPredicateGroupsMap
.get(receiver)
?.push({ field, sortDirection });
return receiver;
};
return result;
},
})
);
ModelSortPredicateCreator.sortPredicateGroupsMap.set(predicate, []);
return predicate;
}
static isValidPredicate<T extends PersistentModel>(
predicate: any
): predicate is SortPredicate<T> {
return ModelSortPredicateCreator.sortPredicateGroupsMap.has(predicate);
}
static getPredicates<T extends PersistentModel>(
predicate: SortPredicate<T>,
throwOnInvalid: boolean = true
): SortPredicatesGroup<T> {
if (
throwOnInvalid &&
!ModelSortPredicateCreator.isValidPredicate(predicate)
) {
throw new Error('The predicate is not valid');
}
const predicateGroup =
ModelSortPredicateCreator.sortPredicateGroupsMap.get(predicate);
if (predicateGroup) {
return predicateGroup;
} else {
throw new Error('Predicate group not found');
}
}
// transforms cb-style predicate into Proxy
static createFromExisting<T extends PersistentModel>(
modelDefinition: SchemaModel,
existing: ProducerSortPredicate<T>
) {
if (!existing || !modelDefinition) {
return undefined;
}
return existing(
ModelSortPredicateCreator.createPredicateBuilder(modelDefinition)
);
}
}