|
1
|
type QueryGraphConfig = { |
|
2
|
entity: string |
|
3
|
fields?: string[] |
|
4
|
filters?: Record<string, any> |
|
5
|
pagination?: { |
|
6
|
order?: Record<string, string> |
|
7
|
take?: number |
|
8
|
} |
|
9
|
withDeleted?: boolean |
|
10
|
} |
|
11
|
|
|
12
|
/** |
|
13
|
* In-memory stand-in for the application query graph the index module |
|
14
|
* consumes data from. Tests seed it with records per entity alias and the |
|
15
|
* fake honors the filter/pagination shapes the module relies on: |
|
16
|
* |
|
17
|
* - `filters.id` as an array or single value (event consumption) |
|
18
|
* - `filters.id.$gt` + order/take (data synchronizer cursor pagination) |
|
19
|
* |
|
20
|
* Every call is recorded in `calls` for tests that want to assert how the |
|
21
|
* module queried the data source. |
|
22
|
*/ |
|
23
|
export class FakeQuery { |
|
24
|
protected data: Map<string, Record<string, any>[]> = new Map() |
|
25
|
|
|
26
|
calls: QueryGraphConfig[] = [] |
|
27
|
|
|
28
|
seed(entity: string, records: Record<string, any>[]) { |
|
29
|
this.data.set(entity, records) |
|
30
|
return this |
|
31
|
} |
|
32
|
|
|
33
|
reset() { |
|
34
|
this.data.clear() |
|
35
|
this.calls = [] |
|
36
|
} |
|
37
|
|
|
38
|
graph = async (config: QueryGraphConfig): Promise<{ data: any[] }> => { |
|
39
|
this.calls.push(JSON.parse(JSON.stringify(config))) |
|
40
|
|
|
41
|
let records = [...(this.data.get(config.entity) ?? [])] |
|
42
|
|
|
43
|
const idFilter = config.filters?.id |
|
44
|
|
|
45
|
if (Array.isArray(idFilter)) { |
|
46
|
records = records.filter((record) => idFilter.includes(record.id)) |
|
47
|
} else if (typeof idFilter === "string") { |
|
48
|
records = records.filter((record) => record.id === idFilter) |
|
49
|
} else if (idFilter && typeof idFilter === "object" && "$gt" in idFilter) { |
|
50
|
records = records.filter((record) => record.id > idFilter.$gt) |
|
51
|
} |
|
52
|
|
|
53
|
const updatedAtFilter = config.filters?.updated_at |
|
54
|
if (updatedAtFilter?.$gt) { |
|
55
|
records = records.filter( |
|
56
|
(record) => |
|
57
|
new Date(record.updated_at as string) > |
|
58
|
new Date(updatedAtFilter.$gt as string) |
|
59
|
) |
|
60
|
} |
|
61
|
|
|
62
|
const idOrder = config.pagination?.order?.id |
|
63
|
if (idOrder) { |
|
64
|
const direction = idOrder.toLowerCase() === "desc" ? -1 : 1 |
|
65
|
records.sort((a, b) => |
|
66
|
a.id === b.id ? 0 : a.id > b.id ? direction : -direction |
|
67
|
) |
|
68
|
} |
|
69
|
|
|
70
|
if (typeof config.pagination?.take === "number") { |
|
71
|
records = records.slice(0, config.pagination.take) |
|
72
|
} |
|
73
|
|
|
74
|
return { data: JSON.parse(JSON.stringify(records)) } |
|
75
|
} |
|
76
|
} |