generated from 47ng/typescript-library-starter
-
-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathvisitor.ts
85 lines (79 loc) · 2.17 KB
/
visitor.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
import { DMMFModels } from './dmmf'
import { Item, traverseTree } from './traverseTree'
import type { FieldConfiguration, MiddlewareParams } from './types'
interface VisitorState {
currentModel: string
}
export interface TargetField {
path: string
value: string
model: string
field: string
fieldConfig: FieldConfiguration
}
export type TargetFieldVisitorFn = (targetField: TargetField) => void
export const makeVisitor = (
models: DMMFModels,
visitor: TargetFieldVisitorFn
) =>
function visitNode(state: VisitorState, { key, type, node, path }: Item) {
const model = models[state.currentModel]
if (!model || !key) {
return state
}
if (type === 'string' && key in model.fields) {
const targetField: TargetField = {
field: key,
model: state.currentModel,
fieldConfig: model.fields[key],
path: path.join('.'),
value: node as string
}
visitor(targetField)
return state
}
// Special case: {field}.set for updates
if (
type === 'object' &&
key in model.fields &&
typeof (node as any)?.set === 'string'
) {
const value: string = (node as any).set
const targetField: TargetField = {
field: key,
model: state.currentModel,
fieldConfig: model.fields[key],
path: path.join('.') + '.set',
value
}
visitor(targetField)
return state
}
if (['object', 'array'].includes(type) && key in model.connections) {
// Follow the connection: from there on downwards, we're changing models.
// Return a new object to break from existing references.
return {
currentModel: model.connections[key].modelName
}
}
return state
}
export function visitInputTargetFields(
params: MiddlewareParams,
models: DMMFModels,
visitor: TargetFieldVisitorFn
) {
traverseTree(params.args, makeVisitor(models, visitor), {
currentModel: params.model!
})
}
export function visitOutputTargetFields(
params: MiddlewareParams,
result: any,
models: DMMFModels,
visitor: TargetFieldVisitorFn
) {
traverseTree(result, makeVisitor(models, visitor), {
currentModel: params.model!
})
}