-
-
Notifications
You must be signed in to change notification settings - Fork 52
/
defineRelationalProperties.ts
165 lines (146 loc) · 4.72 KB
/
defineRelationalProperties.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
import { debug } from 'debug'
import get from 'lodash/get'
import set from 'lodash/set'
import { invariant } from 'outvariant'
import { Database } from '../db/Database'
import {
Entity,
InternalEntity,
InternalEntityProperty,
ModelDictionary,
Value,
} from '../glossary'
import { executeQuery } from '../query/executeQuery'
import { first } from '../utils/first'
import { definePropertyAtPath } from '../utils/definePropertyAtPath'
import {
ProducedRelationsMap,
ProducedRelation,
RelationKind,
} from '../relations/Relation'
import { QuerySelectorWhere } from '../query/queryTypes'
const log = debug('defineRelationalProperties')
export function defineRelationalProperties(
entity: InternalEntity<any, any>,
initialValues: Partial<Value<any, ModelDictionary>>,
relations: ProducedRelationsMap,
db: Database<any>,
): void {
log('defining relational properties...', { entity, initialValues, relations })
for (const [propertyPath, relation] of Object.entries(relations)) {
log(
`setting relational property "${entity.__type}.${propertyPath}"`,
relation,
)
if (!get(initialValues, propertyPath)) {
log('relation has no initial value, skipping...')
continue
}
// Take the relational entity reference from the initial values.
const entityRefs: Entity<any, any>[] = [].concat(
get(initialValues, propertyPath),
)
log('entity references:', entityRefs)
if (relation.unique) {
log('"%s" is a unique relation, verifying..."', propertyPath)
// Trying to look up an entity of the same type
// that references the same relational entity.
const existingEntities = executeQuery(
entity[InternalEntityProperty.type],
entity[InternalEntityProperty.primaryKey],
{
where: set<QuerySelectorWhere<any>>({}, propertyPath, {
[relation.primaryKey]: {
in: entityRefs.map((entityRef) => {
return entityRef[relation.primaryKey]
}),
},
}),
},
db,
)
log(
`existing entities that reference the same "${propertyPath}"`,
existingEntities,
)
invariant(
existingEntities.length === 0,
'Failed to create a unique "%s" relation for "%s" (%s): the provided entity is already used.',
relation.modelName,
`${entity.__type}.${propertyPath}`,
entity[entity[InternalEntityProperty.primaryKey]],
)
}
addRelation(entity, propertyPath, relation, entityRefs, db)
log('relation "%s" successfuly set!', propertyPath)
}
}
export function addRelation(
entity: Entity<any, any>,
propertyPath: string,
relation: ProducedRelation,
references: Value<any, any> | Value<any, any>[],
db: Database<any>,
): void {
const entityType = entity[InternalEntityProperty.type]
const referencesList = ([] as Value<any, any>[]).concat(references)
const referencedModels = db.getModel(relation.modelName)
log(
'adding a "%s" relational property "%s" on "%s" (%j)',
relation.kind,
propertyPath,
entityType,
references,
)
log(
'database records for the referenced "%s" model:',
relation.modelName,
referencedModels,
)
// All referenced entities must exist.
// This also guards against providing compatible plain objects as next values,
// because they won't have the corresponding records in the database.
referencesList.forEach((reference) => {
const referenceId = reference[relation.primaryKey]
invariant(
referencedModels.has(referenceId),
'Failed to add relational property "%s" on "%s": referenced entity with the id "%s" does not exist.',
propertyPath,
entityType,
referenceId,
)
})
definePropertyAtPath(entity, propertyPath, {
enumerable: true,
// Mark the property as configurable so that it can be re-defined.
// Relational properties may be re-defined when updated during the
// entity update ("update"/"updateMany").
configurable: true,
get() {
log(`get "${propertyPath}"`, relation)
const queryResult = referencesList.reduce<InternalEntity<any, any>[]>(
(result, entityRef) => {
return result.concat(
executeQuery(
relation.modelName,
relation.primaryKey,
{
where: {
[relation.primaryKey]: {
equals: entityRef[relation.primaryKey],
},
},
},
db,
),
)
},
[],
)
log(`resolved "${relation.kind}" "${propertyPath}" to`, queryResult)
return relation.kind === RelationKind.OneOf
? first(queryResult)
: queryResult
},
})
}