/
mapping.ts
551 lines (442 loc) · 16.6 KB
/
mapping.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
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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
import {Binary, ObjectID} from "mongodb";
import {
classToPlain,
ClassType,
deleteExcludedPropertiesFor,
getClassName,
getClassPropertyName,
getDecorator, getEnumKeys,
getParentReferenceClass,
getRegisteredProperties, getResolvedReflection,
getValidEnumValue,
isArray,
isEnumAllowLabelsAsValue,
isObject, isOptional, isPlainObject,
isUndefined,
isValidEnumValue,
toClass,
ToClassState
} from "@marcj/marshal";
import * as clone from "clone";
import * as mongoUuid from "mongo-uuid";
export function uuid4Binary(u?: string): Binary {
return mongoUuid(Binary, u);
}
export function uuid4Stringify(u: Binary | string): string {
return 'string' === typeof u ? u : mongoUuid.stringify(u);
}
export function partialClassToMongo<T, K extends keyof T>(
classType: ClassType<T>,
target?: { [path: string]: any },
): { [path: string]: any } {
if (!target) return {};
const result = {};
for (const i in target) {
if (!target.hasOwnProperty(i)) continue;
if (target[i] as any instanceof RegExp) {
continue;
}
result[i] = propertyClassToMongo(classType, i, target[i]);
}
return result;
}
export function partialPlainToMongo<T, K extends keyof T>(
classType: ClassType<T>,
target?: { [path: string]: any },
): { [path: string]: any } {
if (!target) return {};
const result = {};
for (const i in target) {
if (!target.hasOwnProperty(i)) continue;
result[i] = propertyPlainToMongo(classType, i, target[i]);
}
return result;
}
export function partialMongoToPlain<T, K extends keyof T>(
classType: ClassType<T>,
target?: { [path: string]: any },
): { [path: string]: any } {
if (!target) return {};
const result = {};
for (const i in target) {
if (!target.hasOwnProperty(i)) continue;
result[i] = propertyMongoToPlain(classType, i, target[i]);
}
return result;
}
export function propertyMongoToPlain<T>(
classType: ClassType<T>,
propertyName: string,
propertyValue: any
) {
const reflection = getResolvedReflection(classType, propertyName);
if (!reflection) return propertyValue;
const {type} = reflection;
if (isUndefined(propertyValue)) {
return undefined;
}
if (null === propertyValue) {
return null;
}
function convert(value: any) {
if (value && 'uuid' === type && 'string' !== typeof value) {
return uuid4Stringify(value);
}
if ('objectId' === type && 'string' !== typeof value && value.toHexString()) {
return (<ObjectID>value).toHexString();
}
if ('date' === type && value instanceof Date) {
return value.toJSON();
}
return value;
}
return convert(propertyValue);
}
export function propertyClassToMongo<T>(
classType: ClassType<T>,
propertyName: string,
propertyValue: any
) {
const reflection = getResolvedReflection(classType, propertyName);
if (!reflection) return propertyValue;
const {resolvedClassType, resolvedPropertyName, type, typeValue, array, map} = reflection;
if (isUndefined(propertyValue)) {
return undefined;
}
if (null === propertyValue) {
return null;
}
function convert(value: any) {
if (value && 'objectId' === type && 'string' === typeof value) {
try {
return new ObjectID(value);
} catch (e) {
throw new Error(`Invalid ObjectID given in property ${getClassPropertyName(resolvedClassType, resolvedPropertyName)}: '${value}'`);
}
}
if (value && 'uuid' === type && 'string' === typeof value) {
try {
return uuid4Binary(value);
} catch (e) {
throw new Error(`Invalid UUID given in property ${getClassPropertyName(resolvedClassType, resolvedPropertyName)}: '${value}'`);
}
}
if ('string' === type) {
return String(value);
}
if ('number' === type) {
return Number(value);
}
if ('enum' === type) {
//the class instance itself can only have the actual value which can be used in plain as well
return value;
}
if ('binary' === type) {
return new Binary(value);
}
if (type === 'class') {
return classToMongo(typeValue, value);
}
return value;
}
if (array) {
if (isArray(propertyValue)) {
return propertyValue.map(v => convert(v));
}
return [];
}
if (map) {
const result: { [name: string]: any } = {};
if (isObject(propertyValue)) {
for (const i in propertyValue) {
if (!propertyValue.hasOwnProperty(i)) continue;
result[i] = convert((<any>propertyValue)[i]);
}
}
return result;
}
return convert(propertyValue);
}
export function propertyPlainToMongo<T>(
classType: ClassType<T>,
propertyName: string,
propertyValue: any
) {
const reflection = getResolvedReflection(classType, propertyName);
if (!reflection) return propertyValue;
const {resolvedClassType, resolvedPropertyName, type, typeValue, array, map} = reflection;
if (isUndefined(propertyValue)) {
return undefined;
}
if (null === propertyValue) {
return null;
}
function convert(value: any) {
if (value && 'objectId' === type && 'string' === typeof value) {
try {
return new ObjectID(value);
} catch (e) {
throw new Error(`Invalid ObjectID given in property ${getClassPropertyName(resolvedClassType, resolvedPropertyName)}: '${value}'`);
}
}
if (value && 'uuid' === type && 'string' === typeof value) {
try {
return uuid4Binary(value);
} catch (e) {
throw new Error(`Invalid UUID given in property ${getClassPropertyName(resolvedClassType, resolvedPropertyName)}: '${value}'`);
}
}
if ('date' === type && ('string' === typeof value || 'number' === typeof value)) {
return new Date(value);
}
if ('string' === type && 'string' !== typeof value) {
return String(value);
}
if ('number' === type && 'number' !== typeof value) {
return +value;
}
if ('binary' === type && 'string' === typeof value) {
return new Buffer(value, 'base64');
}
if ('boolean' === type && 'boolean' !== typeof value) {
if ('true' === value || '1' === value || 1 === value) return true;
if ('false' === value || '0' === value || 0 === value) return false;
return true === value;
}
if ('any' === type) {
return clone(value, false);
}
if ('binary' === type && 'string' === typeof value) {
return new Binary(new Buffer(value, 'base64'));
}
if (type === 'class') {
//we need to check if value has all properties set, if one not-optional is missing, we throw an error
for (const property of getRegisteredProperties(typeValue)) {
if (value[property] === undefined) {
if (isOptional(typeValue, propertyName)) {
continue;
}
throw new Error(`Missing value for ${getClassPropertyName(typeValue, propertyName)}. Can not convert to mongo.`);
}
value[property] = propertyPlainToMongo(typeValue, property, value[property]);
}
}
return value;
}
if (array) {
if (isArray(propertyValue)) {
return propertyValue.map(v => convert(v));
}
return [];
}
if (map) {
const result: { [name: string]: any } = {};
if (isObject(propertyValue)) {
for (const i in propertyValue) {
if (!propertyValue.hasOwnProperty(i)) continue;
result[i] = convert((<any>propertyValue)[i]);
}
}
return result;
}
return convert(propertyValue);
}
export function propertyMongoToClass<T>(
classType: ClassType<T>,
propertyName: string,
propertyValue: any,
parents: any[],
incomingLevel: number,
state: ToClassState
) {
if (isUndefined(propertyValue)) {
return undefined;
}
if (null === propertyValue) {
return null;
}
const reflection = getResolvedReflection(classType, propertyName);
if (!reflection) return propertyValue;
const {resolvedClassType, resolvedPropertyName, type, typeValue, array, map} = reflection;
function convert(value: any) {
if (value && 'uuid' === type && 'string' !== typeof value) {
return uuid4Stringify(value);
}
if ('objectId' === type && 'string' !== typeof value && value.toHexString()) {
return (<ObjectID>value).toHexString();
}
if ('date' === type && !(value instanceof Date)) {
return new Date(value);
}
if ('binary' === type && value instanceof Binary) {
return value.buffer;
}
if ('any' === type) {
return clone(value, false);
}
if ('string' === type && 'string' !== typeof value) {
return String(value);
}
if ('number' === type && 'number' !== typeof value) {
return +value;
}
if ('boolean' === type && 'boolean' !== typeof value) {
if ('true' === value || '1' === value || 1 === value) return true;
if ('false' === value || '0' === value || 0 === value) return false;
return true === value;
}
if ('enum' === type) {
const allowLabelsAsValue = isEnumAllowLabelsAsValue(resolvedClassType, resolvedPropertyName);
if (undefined !== value && !isValidEnumValue(typeValue, value, allowLabelsAsValue)) {
throw new Error(`Invalid ENUM given in property ${resolvedPropertyName}: ${value}, valid: ${getEnumKeys(typeValue).join(',')}`);
}
return getValidEnumValue(typeValue, value, allowLabelsAsValue);
}
if (type === 'class') {
if (value instanceof typeValue) {
//already the target type, this is an error
throw new Error(`${getClassPropertyName(resolvedClassType, resolvedPropertyName)} is already in target format. Are you calling plainToClass() with an class instance?`);
}
return toClass(typeValue, clone(value, false, 1), propertyMongoToClass, parents, incomingLevel, state);
}
return value;
}
if (array) {
if (isArray(propertyValue)) {
return propertyValue.map(v => convert(v));
}
return [];
}
if (map) {
const result: any = {};
if (isObject(propertyValue)) {
for (const i in propertyValue) {
if (!propertyValue.hasOwnProperty(i)) continue;
result[i] = convert((propertyValue as any)[i]);
}
}
return result;
}
return convert(propertyValue);
}
export function mongoToClass<T>(classType: ClassType<T>, target: any, parents?: any[]): T {
const state = new ToClassState();
const item = toClass(classType, clone(target, false, 1), propertyMongoToClass, parents || [], 1, state);
for (const callback of state.onFullLoadCallbacks) {
callback();
}
return item;
}
export function mongoToPlain<T>(classType: ClassType<T>, target: any) {
return classToPlain(classType, mongoToClass(classType, target));
}
export function plainToMongo<T>(classType: ClassType<T>, target: {[k: string]: any}): any {
const result: any = {};
if (target instanceof classType) {
throw new Error(`Could not plainToMongo since target is a class instance of ${getClassName(classType)}`);
}
for (const propertyName of getRegisteredProperties(classType)) {
if (undefined === (target as any)[propertyName]) {
continue;
}
if (getParentReferenceClass(classType, propertyName)) {
//we do not export parent references, as this would lead to an circular reference
continue;
}
result[propertyName] = propertyPlainToMongo(classType, propertyName, (target as any)[propertyName]);
}
deleteExcludedPropertiesFor(classType, result, 'mongo');
return result;
}
export function classToMongo<T>(classType: ClassType<T>, target: T): any {
const result: any = {};
if (!(target instanceof classType)) {
throw new Error(`Could not classToMongo since target is not a class instance of ${getClassName(classType)}`);
}
const decoratorName = getDecorator(classType);
if (decoratorName) {
return propertyClassToMongo(classType, decoratorName, (target as any)[decoratorName]);
}
for (const propertyName of getRegisteredProperties(classType)) {
if (undefined === (target as any)[propertyName]) {
continue;
}
if (getParentReferenceClass(classType, propertyName)) {
//we do not export parent references, as this would lead to an circular reference
continue;
}
result[propertyName] = propertyClassToMongo(classType, propertyName, (target as any)[propertyName]);
}
deleteExcludedPropertiesFor(classType, result, 'mongo');
return result;
}
/**
* Takes a mongo filter query and converts its class values to classType's mongo types, so you
* can use it to send it to mongo.
*/
export function convertClassQueryToMongo<T, K extends keyof T>(
classType: ClassType<T>,
target: { [path: string]: any },
fieldNamesMap: {[name: string]: boolean} = {},
): { [path: string]: any } {
return convertQueryToMongo(classType, target, (convertClassType: ClassType<any>, path: string, value: any) => {
return propertyClassToMongo(convertClassType, path, value);
}, fieldNamesMap);
}
/**
* Takes a mongo filter query and converts its plain values to classType's mongo types, so you
* can use it to send it to mongo.
*/
export function convertPlainQueryToMongo<T, K extends keyof T>(
classType: ClassType<T>,
target: { [path: string]: any },
fieldNamesMap: {[name: string]: boolean} = {}
): { [path: string]: any } {
return convertQueryToMongo(classType, target, (convertClassType: ClassType<any>, path: string, value: any) => {
return propertyPlainToMongo(convertClassType, path, value);
}, fieldNamesMap);
}
export function convertQueryToMongo<T, K extends keyof T>(
classType: ClassType<T>,
target: { [path: string]: any },
converter: (convertClassType: ClassType<any>, path: string, value: any) => any,
fieldNamesMap: {[name: string]: boolean} = {}
): { [path: string]: any } {
const result: { [i: string]: any } = {};
for (const i in target) {
if (!target.hasOwnProperty(i)) continue;
const fieldValue: any = target[i];
if (i[0] === '$') {
result[i] = (fieldValue as any[]).map(v => convertQueryToMongo(classType, v, converter, fieldNamesMap));
continue;
}
if (isPlainObject(fieldValue)) {
for (const j in fieldValue) {
if (!fieldValue.hasOwnProperty(j)) continue;
const queryValue: any = (fieldValue as any)[j];
if (j[0] !== '$') {
result[i] = converter(classType, i, fieldValue);
break;
} else {
if (j === '$and' || j === '$or' || j === '$nor' || j === '$not') {
(fieldValue as any)[j] = (queryValue as any[]).map(v => convertQueryToMongo(classType, v, converter, fieldNamesMap));
} else if (j === '$in' || j === '$nin' || j === '$all') {
fieldNamesMap[i] = true;
(fieldValue as any)[j] = (queryValue as any[]).map(v => converter(classType, i, v));
} else if (j === '$text' || j === '$exists' || j === '$mod' || j === '$size' || j === '$type' || j === '$regex' || j === '$where') {
//don't transform
fieldNamesMap[i] = true;
} else {
fieldNamesMap[i] = true;
(fieldValue as any)[j] = converter(classType, i, queryValue);
}
}
}
result[i] = fieldValue;
} else {
fieldNamesMap[i] = true;
result[i] = converter(classType, i, fieldValue);
}
}
return result;
}