-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.js
350 lines (288 loc) · 8.15 KB
/
utils.js
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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
const debug = require('debug')(require('./package').name)
const _ = require('lodash')
const {
GraphQLNonNull,
} = require('graphql/type')
const { TYPE } = require('@tradle/constants')
const {
isInlinedProperty,
parseId,
setVirtual,
isInstantiable
} = require('@tradle/validate-resource').utils
const {
getNestedProperties,
getProperty
} = require('@tradle/validate-model').utils
// const { ResourceStubType } = require('./types')
const BaseObjectModel = require('./object-model')
const BASE_REQUIRED_INLINED = [TYPE]
// const ObjectPropNames = Object.keys(BaseObjectModel.properties)
const { NESTED_PROP_SEPARATOR } = require('./constants')
const OPERATORS = require('./operators')
const AUTHOR_TITLE_PROP = {
type: 'string'
}
const memoizeByModel = fn => _.memoize(fn, opts => opts.model.id)
const memoizeByModelAndBacklink = fn => _.memoize(fn, ({ model, backlink }) => {
return `${model.id}:${backlink ? 'b' : ''}`
})
// function memoizeByModelAndOperatorType (fn) {
// return _.memoize(fn, opts => {
// return `${getOperatorType(opts.operator) || ''}~${opts.model.id}`
// })
// }
const memoizeByModelAndOperator = fn =>
_.memoize(fn, opts => `${opts.model.id}~${opts.operator}`)
const memoizeByModelAndInput = fn => _.memoize(fn, opts => {
// i for input, o for output
return `${opts.operator ? 'i' : 'o'}~${opts.model.id}`
})
// function toNonNull (types) {
// return mapObject(types, wrapper => {
// return _.extend({}, wrapper, {
// type: new GraphQLNonNull(wrapper.type)
// })
// })
// }
// const isResourceStub = props => {
// const keys = Object.keys(props)
// return keys.length === ResourceStubType.propertyNames &&
// _.isEqual(keys.sort(), ResourceStubType.propertyNames)
// }
function isComplexProperty ({ type, range }) {
return type === 'object' ||
type === 'array' ||
type === 'enum' ||
range === 'json'
}
function isBadEnumModel (model) {
return model.subClassOf === 'tradle.Enum' && !Array.isArray(model.enum)
}
function isGoodEnumModel (model) {
return model.subClassOf === 'tradle.Enum' && Array.isArray(model.enum)
}
function isNullableProperty (property) {
return !isComplexProperty(property.type)
}
function isScalarProperty (property) {
return !isComplexProperty(property)
}
// function filterObject (obj, filter) {
// const filtered = {}
// for (let key in obj) {
// let val = obj[key]
// if (filter(val)) {
// filtered[key] = val
// }
// }
// return filtered
// }
function addProtocolProps (model) {
let required = model.required || []
while (true) {
let expanded = expandGroupProps(model, required)
if (expanded.length === required.length) {
break
}
required = expanded
}
if (model.inlined) {
model.properties[TYPE] = _.cloneDeep(BaseObjectModel.properties[TYPE])
} else {
_.extend(model.properties, _.cloneDeep(BaseObjectModel.properties))
}
model.required = getRequiredProperties({ model, inlined: model.inlined })
}
function expandGroupProps (model, arr) {
const props = []
for (const propertyName of arr) {
const { group } = getProperty({ model, propertyName })
// nested group props should be caught in @tradle/validate-model
props.push(group || propertyName)
}
return props
}
// faster than lodash
function unique (strings) {
const obj = {}
for (let str of strings) {
if (!(str in obj)) {
obj[str] = true
}
}
return Object.keys(obj)
}
// function hasNonProtocolProps (model) {
// return !!Object.keys(_.omit(model.properties, PROTOCOL_PROP_NAMES)).length
// }
// function toInlinedModel (model) {
// return _.extend({}, model, {
// inlined: true,
// required: getRequiredProperties({ model, inlined })
// })
// }
function normalizeModels (models, base={}) {
// models = filterObject(models, model => {
// return !isInstantiable(model) || hasNonProtocolProps(model)
// })
models = _.cloneDeep(models)
const all = _.extend({}, models, base)
forEachPropIn(models, addProtocolProps, all)
forEachPropIn(models, addCustomProps, all)
forEachPropIn(models, addNestedProps, all)
// return fixEnums(addedProtocol)
return models
}
function addCustomProps (model) {
if (model.inlined) return
model.properties._authorTitle = AUTHOR_TITLE_PROP
}
function addNestedProps (model, models) {
return _.extend(model.properties, getNestedProperties({ models, model }))
}
const getRequiredProperties = _.memoize(({ model, inlined }) => {
let required = model.required || []
if (inlined) {
required = required.concat(BASE_REQUIRED_INLINED)
} else {
required = required.concat(BaseObjectModel.required)
}
required = unique(required)
// special case
if (model.id === 'tradle.Identity') {
const idx = required.indexOf('_author')
if (idx !== -1) required.splice(idx, 1)
}
return required
}, ({ model, inlined }) => inlined ? 'i_' + model.id : 'o_' + model.id)
function getRef (property) {
return property.ref || (property.items && property.items.ref)
}
const getProperties = _.memoize(model => {
if (model.properties.id) {
throw new Error(`"id" is a reserved property, model ${model.id} needs to learn its place`)
}
return Object.keys(model.properties)
}, model => model.id)
function getInstantiableModels (models) {
return Object.keys(models).filter(id => isInstantiable(models[id]))
}
function getOnCreateProperties ({ model, models }) {
return Object.keys(model.properties).filter(propertyName => {
return isSetOnCreate({ model, propertyName })
})
}
function isSetOnCreate ({ model, propertyName }) {
const property = model.properties[propertyName]
return !property.backlink
// const { type } = property
// if (type !== 'object' && type !== 'array') {
// return true
// }
// if (isInlinedProperty({ property, models })) {
// return true
// }
// if (!property.backlink) return true
}
// function mapObject (obj, mapper, ...args) {
// const mapped = {}
// for (let key in obj) {
// mapped[key] = mapper(obj[key], ...args)
// }
// return mapped
// }
function forEachPropIn (obj, mapper, ...args) {
for (let key in obj) {
mapper(obj[key], ...args)
}
}
// function lazy (fn) {
// let val
// let called
// return function (...args) {
// if (called) return val
// val = fn.apply(this, args)
// called = true
// return val
// }
// }
function getTypeName ({ model, type, operator, operatorType, inlined }) {
if (!type) {
type = model.id
}
let name = type.replace(/[^_a-zA-Z0-9]/g, '_')
// graphql constraint
if (!/^[_a-zA-Z][_a-zA-Z0-9]*$/.test(name)) {
throw new Error('unable to sanitize type name: ' + type)
}
if (operator || operatorType) {
name = `${operator || operatorType}_${name}`
}
if (inlined) name = `${name}_i`
return name
}
/**
* Convert NESTED_PROP_SEPARATOR to '.' in filter,
* e.g. document__id to document.id
*/
function normalizeNestedProps ({ args, model, models }) {
const { properties } = model
const { filter, orderBy } = args
for (let comparator in filter) {
let vals = filter[comparator]
Object.keys(vals).forEach(propertyName => {
const val = vals[propertyName]
const path = propertyName.split(NESTED_PROP_SEPARATOR)
if (path.length >= 2) {
vals[path.join('.')] = val
delete vals[propertyName]
}
})
}
if (orderBy) {
orderBy.property = orderBy.property
.split(NESTED_PROP_SEPARATOR)
.join('.')
}
}
function defineGetter (obj, prop, getter, cache) {
let cached
Object.defineProperty(obj, prop, {
get: () => {
if (cache && cached) return cached
return cached = getter()
}
})
}
function getOperatorType (operator) {
if (operator) {
if (OPERATORS[operator].scalar) {
return 'scalar_compare'
}
return 'compare'
}
}
module.exports = {
debug,
// lazy,
// isResourceStub,
isBadEnumModel,
isGoodEnumModel,
isNullableProperty,
isScalarProperty,
normalizeModels,
normalizeNestedProps,
memoizeByModel,
memoizeByModelAndInput,
memoizeByModelAndBacklink,
memoizeByModelAndOperator,
// toNonNull,
getProperties,
getRequiredProperties,
getInstantiableModels,
getRef,
getTypeName,
defineGetter,
getOperatorType
}