-
Notifications
You must be signed in to change notification settings - Fork 52
/
entity.ts
597 lines (501 loc) · 18.6 KB
/
entity.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
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
import is from 'is';
import hooks from 'promised-hooks';
import { Transaction } from '@google-cloud/datastore';
import DataLoader from 'dataloader';
import defaultValues from './helpers/defaultValues';
import helpers from './helpers';
import Gstore from './index';
import Schema, { SchemaPathDefinition } from './schema';
import Model from './model';
import { datastoreSerializer } from './serializers';
import { ERROR_CODES, ValidationError } from './errors';
import {
EntityKey,
EntityData,
IdType,
Ancestor,
GenericObject,
DatastoreSaveMethod,
PopulateRef,
PromiseWithPopulate,
CustomEntityFunction,
} from './types';
import { ValidateResponse } from './helpers/validation';
import { PopulateHandler } from './helpers/populateHelpers';
const { validation, populateHelpers } = helpers;
const { populateFactory } = populateHelpers;
export class GstoreEntity<T extends object = GenericObject> {
/* The entity Key */
public entityKey: EntityKey;
/* The entity data */
public entityData: { [P in keyof T]: T[P] } = {} as any;
/**
* If you provided a dataloader instance when saving the entity, it will
* be added as property. You will then have access to it in your "pre" save() hooks.
*/
public dataloader: DataLoader<EntityKey[], EntityData> | undefined;
public context: GenericObject;
private __gstore: Gstore | undefined; // Added when creating the Model
private __schema: Schema<T> | undefined; // Added when creating the Model
private __entityKind: string | undefined; // Added when creating the Model
public __hooksEnabled = true;
constructor(data?: EntityData<T>, id?: IdType, ancestors?: Ancestor, namespace?: string, key?: EntityKey) {
/**
* Object to store custom data for the entity.
* In some cases we might want to add custom data onto the entity
* and as Typescript won't allow random properties to be added, this
* is the place to add data based on the context.
*/
this.context = {};
if (key) {
if (!this.gstore.ds.isKey(key)) {
throw new Error('Entity Key must be a Datastore Key');
}
this.entityKey = key;
} else {
this.entityKey = this.__createKey(id, ancestors, namespace);
}
// create entityData from data provided
this.__buildEntityData(data || {});
this.__addAliasAndVirtualProperties();
this.__addCustomMethodsFromSchema();
// Wrap entity with hook "pre" and "post" methods
hooks.wrap(this);
// Add the middlewares defined on the Schena
this.__registerHooksFromSchema();
}
/**
* Save the entity in the Datastore
*
* @param {Transaction} transaction The optional transaction to save the entity into
* @param options Additional configuration
* @returns {Promise<GstoreEntity<T>>}
* @link https://sebloix.gitbook.io/gstore-node/entity/methods/save
*/
save(transaction?: Transaction, opts?: SaveOptions): Promise<Entity<T>> {
this.__hooksEnabled = true;
const options = {
method: 'upsert' as DatastoreSaveMethod,
sanitizeEntityData: true,
...opts,
} as SaveOptions;
// ------------------------ HANDLERS ---------------------------------
// -------------------------------------------------------------------
const validateEntityData = (): Partial<ValidateResponse> => {
if (this.schema.options.validateBeforeSave) {
return this.validate();
}
return { error: null };
};
const validateMethod = (method: DatastoreSaveMethod): { error: Error | null } => {
const allowed: { [key: string]: boolean } = {
update: true,
insert: true,
upsert: true,
};
return !allowed[method]
? { error: new Error('Method must be either "update", "insert" or "upsert"') }
: { error: null };
};
const validateDataAndMethod = (): { error: ValidationError | Error | null } => {
const { error: entityDataError } = validateEntityData();
let methodError: Error | null;
if (!entityDataError) {
({ error: methodError } = validateMethod(options.method!));
}
return { error: entityDataError || methodError! };
};
const onEntitySaved = (): Promise<Entity<T>> => {
/**
* Make sure to clear the cache for this Entity Kind
*/
if ((this.constructor as Model).__hasCache(options)) {
return (this.constructor as Model)
.clearCache()
.then(() => (this as unknown) as Entity<T>)
.catch((err: any) => {
let msg = 'Error while clearing the cache after saving the entity.';
msg += 'The entity has been saved successfully though. ';
msg += 'Both the cache error and the entity saved have been attached.';
const cacheError = new Error(msg);
(cacheError as any).__entity = this;
(cacheError as any).__cacheError = err;
throw cacheError;
});
}
return Promise.resolve((this as unknown) as Entity<T>);
};
/**
* If it is a transaction, we create a hooks.post array that will be executed
* when transaction succeeds by calling transaction.execPostHooks() (returns a Promises)
*/
const attachPostHooksToTransaction = (): void => {
// Disable the "post" hooks as we will only run them after the transaction succcees
this.__hooksEnabled = false;
(this.constructor as Model).__hooksTransaction.call(
this,
transaction!,
(this as any).__posts ? (this as any).__posts.save : undefined,
);
};
// ------------------------ END HANDLERS --------------------------------
if (options.sanitizeEntityData) {
// this.entityData = (this.constructor as Model<T>).sanitize.call(this.constructor, this.entityData, {
this.entityData = (this.constructor as Model<T>).sanitize.call(this.constructor, this.entityData, {
disabled: ['write'],
});
}
const { error } = validateDataAndMethod();
if (error) {
return Promise.reject(error);
}
this.serializeEntityData();
const datastoreEntity = datastoreSerializer.toDatastore(this);
datastoreEntity.method = options.method;
if (transaction) {
if (transaction.constructor.name !== 'Transaction') {
return Promise.reject(new Error('Transaction needs to be a gcloud Transaction'));
}
attachPostHooksToTransaction();
transaction.save(datastoreEntity);
return Promise.resolve((this as unknown) as Entity<T>);
}
return this.gstore.ds.save(datastoreEntity).then(onEntitySaved);
}
/**
* Validate the entity data. It returns an object with an `error` and a `value` property.
* If the error is `null`, the validation has passed.
* The `value` returned is the entityData sanitized (unknown properties removed).
*
* @link https://sebloix.gitbook.io/gstore-node/entity/methods/validate
*/
validate(): ValidateResponse {
const { entityData, schema, entityKind, gstore } = this;
return validation.validate(entityData, schema, entityKind, gstore.ds);
}
/**
* Returns a JSON object of the entity data along with the entity id/name.
* The properties on the Schema where "read" has been set to "false" won't be added
* unless `readAll: true` is passed in the options.
*
* @param options Additional configuration
* @link https://sebloix.gitbook.io/gstore-node/entity/methods/plain
*/
plain(options: PlainOptions | undefined = {}): Partial<EntityData<T>> & { [key: string]: any } {
if (!is.object(options)) {
throw new Error('Options must be an Object');
}
const readAll = !!options.readAll || false;
const virtuals = !!options.virtuals || false;
const showKey = !!options.showKey || false;
if (virtuals) {
// Add any possible virtual properties to the object
this.entityData = this.__getEntityDataWithVirtuals();
}
const data = datastoreSerializer.fromDatastore(this.entityData, this.constructor as Model, {
readAll,
showKey,
});
return data;
}
get<P extends keyof T>(path: P): any {
if ({}.hasOwnProperty.call(this.schema.__virtuals, path)) {
return this.schema.__virtuals[path as string].applyGetters(this.entityData);
}
return this.entityData[path];
}
set<P extends keyof T>(path: P, value: any): Entity<T> {
if ({}.hasOwnProperty.call(this.schema.__virtuals, path)) {
this.schema.__virtuals[path as string].applySetters(value, this.entityData);
return (this as unknown) as Entity<T>;
}
this.entityData[path] = value;
return (this as unknown) as Entity<T>;
}
/**
* Access any gstore Model from the entity instance.
*
* @param {string} entityKind The entity kind
* @returns {Model} The Model
* @example
```
const user = new User({ name: 'john', pictId: 123});
const ImageModel = user.model('Image');
ImageModel.get(user.pictId).then(...);
```
* @link https://sebloix.gitbook.io/gstore-node/entity/methods/model
*/
model(name: string): Model {
return this.gstore.model(name);
}
// TODO: Rename this function "fetch" (and create alias to this for backward compatibility)
/**
* Fetch entity from Datastore
*
* @link https://sebloix.gitbook.io/gstore-node/entity/methods/datastoreentity
*/
datastoreEntity(options = {}): Promise<Entity<T> | null> {
const onEntityFetched = (result: [EntityData<T> | null]): Entity<T> | null => {
const entityData = result ? result[0] : null;
if (!entityData) {
if (this.gstore.config.errorOnEntityNotFound) {
const error = new Error('Entity not found');
(error as any).code = ERROR_CODES.ERR_ENTITY_NOT_FOUND;
throw error;
}
return null;
}
this.entityData = entityData;
return (this as unknown) as Entity<T>;
};
if ((this.constructor as Model<T>).__hasCache(options)) {
return this.gstore.cache!.keys.read(this.entityKey, options).then(onEntityFetched);
}
return this.gstore.ds.get(this.entityKey).then(onEntityFetched);
}
/**
* Populate entity references (whose properties are an entity Key) and merge them in the entity data.
*
* @param refs The entity references to fetch from the Datastore. Can be one (string) or multiple (array of string)
* @param properties The properties to return from the reference entities. If not specified, all properties will be returned
* @link https://sebloix.gitbook.io/gstore-node/entity/methods/populate
*/
populate<U extends string | string[]>(
path?: U,
propsToSelect?: U extends Array<string> ? never : string | string[],
): PromiseWithPopulate<Entity<T>> {
const refsToPopulate: PopulateRef[][] = [];
const promise = Promise.resolve(this).then((this.constructor as Model<T>).__populate(refsToPopulate));
((promise as any).populate as PopulateHandler) = populateFactory(refsToPopulate, promise, this.schema);
((promise as any).populate as PopulateHandler)(path, propsToSelect);
return promise as any;
}
/**
* Process some basic formatting to the entity data before save
* - automatically set the modifiedOn property to current date (if the property exists on schema)
* - convert object with latitude/longitude to Datastore GeoPoint
* - convert string date to Date object
*/
serializeEntityData(): void {
/**
* If the schema has a "modifiedOn" property we automatically
* update its value to the current dateTime
*/
if ({}.hasOwnProperty.call(this.schema.paths, 'modifiedOn')) {
(this.entityData as any).modifiedOn = new Date();
}
/**
* If the entityData has 'geoPoint' property(ies)
* and its value is an object with "latitude" and "longitude"
* we convert it to a datastore GeoPoint.
*/
if ({}.hasOwnProperty.call(this.schema.__meta, 'geoPointsProps')) {
this.schema.__meta.geoPointsProps.forEach((property: string) => {
const propValue = (this.entityData as any)[property];
if (
{}.hasOwnProperty.call(this.entityData, property) &&
propValue !== null &&
propValue.constructor.name !== 'GeoPoint'
) {
(this.entityData as any)[property] = this.gstore.ds.geoPoint(propValue);
}
});
}
if ({}.hasOwnProperty.call(this.schema.__meta, 'dateProps')) {
this.schema.__meta.dateProps.forEach((property: string) => {
const propValue = (this.entityData as any)[property];
if (
{}.hasOwnProperty.call(this.entityData, property) &&
propValue !== null &&
propValue instanceof Date === false
) {
(this.entityData as any)[property] = new Date(propValue);
}
});
}
}
get id(): string | number {
return this.entityKey.id || this.entityKey.name!;
}
/**
* The gstore instance
*/
get gstore(): Gstore {
if (this.__gstore === undefined) {
throw new Error('No gstore instance attached to entity');
}
return this.__gstore;
}
/**
* The entity Model Schema
*/
get schema(): Schema<T> {
if (this.__schema === undefined) {
throw new Error('No schema instance attached to entity');
}
return this.__schema;
}
/**
* The Datastore entity kind
*/
get entityKind(): string {
if (this.__entityKind === undefined) {
throw new Error('No entity kind attached to entity');
}
return this.__entityKind;
}
private __buildEntityData(data: GenericObject): void {
const { schema } = this;
const isJoiSchema = schema.isJoi;
// If Joi schema, get its default values
if (isJoiSchema) {
const { error, value } = schema.validateJoi(data);
if (!error) {
this.entityData = { ...value };
}
}
this.entityData = { ...this.entityData, ...data };
Object.entries(schema.paths as { [k: string]: SchemaPathDefinition }).forEach(([key, prop]) => {
const hasValue = {}.hasOwnProperty.call(this.entityData, key);
const isOptional = {}.hasOwnProperty.call(prop, 'optional') && prop.optional !== false;
const isRequired = {}.hasOwnProperty.call(prop, 'required') && prop.required === true;
// Set Default Values
if (!isJoiSchema && !hasValue && !isOptional) {
let value = null;
if ({}.hasOwnProperty.call(prop, 'default')) {
if (typeof prop.default === 'function') {
value = prop.default();
} else {
value = prop.default;
}
}
if ({}.hasOwnProperty.call(defaultValues.__map__, value)) {
/**
* If default value is in the gstore.defaultValue hashTable
* then execute the handler for that shortcut
*/
value = defaultValues.__handler__(value);
} else if (value === null && {}.hasOwnProperty.call(prop, 'values') && !isRequired) {
// Default to first value of the allowed values if **not** required
[value] = prop.values as any[];
}
this.entityData[key as keyof T] = value;
}
});
// add Symbol Key to the entityData
(this.entityData as any)[this.gstore.ds.KEY] = this.entityKey;
}
private __createKey(id?: IdType, ancestors?: Ancestor, namespace?: string): EntityKey {
if (id && !is.number(id) && !is.string(id)) {
throw new Error('id must be a string or a number');
}
const hasAncestors = typeof ancestors !== 'undefined' && ancestors !== null && is.array(ancestors);
let path: (string | number)[] = hasAncestors ? [...ancestors!] : [];
if (id) {
path = [...path, this.entityKind, id];
} else {
path.push(this.entityKind);
}
return namespace ? this.gstore.ds.key({ namespace, path }) : this.gstore.ds.key(path);
}
private __addAliasAndVirtualProperties(): void {
const { schema } = this;
// Create virtual properties (getters and setters for entityData object)
Object.keys(schema.paths)
.filter(pathKey => ({}.hasOwnProperty.call(schema.paths, pathKey)))
.forEach(pathKey =>
Object.defineProperty(this, pathKey, {
get: function getProp() {
return this.entityData[pathKey];
},
set: function setProp(newValue) {
this.entityData[pathKey] = newValue;
},
}),
);
// Create virtual properties (getters and setters for "virtuals" defined on the Schema)
Object.keys(schema.__virtuals)
.filter(key => ({}.hasOwnProperty.call(schema.__virtuals, key)))
.forEach(key =>
Object.defineProperty(this, key, {
get: function getProp() {
return schema.__virtuals[key].applyGetters({ ...this.entityData });
},
set: function setProp(newValue) {
schema.__virtuals[key].applySetters(newValue, this.entityData);
},
}),
);
}
private __registerHooksFromSchema(): GstoreEntity<T> {
const callQueue = this.schema.__callQueue.entity;
if (!Object.keys(callQueue).length) {
return this;
}
Object.keys(callQueue).forEach(method => {
if (!(this as any)[method]) {
return;
}
// Add Pre hooks
callQueue[method].pres.forEach(fn => {
(this as any).pre(method, fn);
});
// Add Pre hooks
callQueue[method].post.forEach(fn => {
(this as any).post(method, fn);
});
});
return this;
}
private __addCustomMethodsFromSchema(): void {
Object.entries(this.schema.methods).forEach(([method, handler]) => {
(this as any)[method] = handler;
});
}
private __getEntityDataWithVirtuals(): EntityData<T> & GenericObject {
const { __virtuals } = this.schema;
const entityData: EntityData<T> & GenericObject = { ...this.entityData };
Object.keys(__virtuals).forEach(k => {
if ({}.hasOwnProperty.call(entityData, k)) {
__virtuals[k].applySetters(entityData[k], entityData);
} else {
__virtuals[k].applyGetters(entityData);
}
});
return entityData;
}
}
export default GstoreEntity;
export type Entity<
T extends object = GenericObject,
M extends object = { [key: string]: CustomEntityFunction<T> }
> = GstoreEntity<T> & T & M;
interface SaveOptions {
method?: DatastoreSaveMethod;
sanitizeEntityData?: boolean;
cache?: any;
}
interface PlainOptions {
/**
* Output all the entity data properties, regardless of the Schema `read` setting.
*
* @type {boolean}
* @default false
*/
readAll?: boolean;
/**
* Add the _virtual_ properties defined for the entity on the Schema.
*
* @type {boolean}
* @default false
* @link https://sebloix.gitbook.io/gstore-node/schema/methods/virtual
*/
virtuals?: boolean;
/**
* Add the full entity _Key_ object at the a "__key" property
*
* @type {boolean}
* @default false
*/
showKey?: boolean;
}