-
-
Notifications
You must be signed in to change notification settings - Fork 25
/
document.ts
111 lines (98 loc) · 2.57 KB
/
document.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
import rfdc from 'rfdc';
import type Model from './model';
import type Schema from './schema';
import type BluebirdPromise from 'bluebird';
import type { NodeJSLikeCallback } from './types';
const cloneDeep = rfdc();
abstract class Document<T> {
abstract _model: Model<T>;
_id!: string | number | undefined;
abstract _schema: Schema<T>;
[key : string]: any;
/**
* Document constructor.
*
* @param {object} data
*/
constructor(data?: T) {
if (data) {
Object.assign(this, data);
}
}
/**
* Saves the document.
*
* @param {function} [callback]
* @return {BluebirdPromise}
*/
save(callback?: NodeJSLikeCallback<any>): BluebirdPromise<any> {
return this._model.save(this, callback);
}
/**
* Updates the document.
*
* @param {object} data
* @param {function} [callback]
* @return {BluebirdPromise}
*/
update(data: object, callback?: NodeJSLikeCallback<any>): BluebirdPromise<any> {
return this._model.updateById(this._id, data, callback);
}
/**
* Replaces the document.
*
* @param {object} data
* @param {function} [callback]
* @return {BluebirdPromise}
*/
replace(data: T | Document<T>, callback?: NodeJSLikeCallback<any>): BluebirdPromise<any> {
return this._model.replaceById(this._id, data, callback);
}
/**
* Removes the document.
*
* @param {function} [callback]
* @return {BluebirdPromise}
*/
remove(callback?: NodeJSLikeCallback<any>): BluebirdPromise<any> {
return this._model.removeById(this._id, callback);
}
/**
* Returns a plain JavaScript object.
*
* @return {object}
*/
toObject(): T {
const keys = Object.keys(this);
const obj: Partial<T> = {};
for (let i = 0, len = keys.length; i < len; i++) {
const key = keys[i];
// Don't deep clone getters in order to avoid "Maximum call stack size
// exceeded" error
obj[key] = isGetter(this, key) ? this[key] : cloneDeep(this[key]);
}
return obj as T;
}
/**
* Returns a string representing the document.
*
* @return {String}
*/
toString(): string {
return JSON.stringify(this);
}
/**
* Populates document references.
*
* @param {String|Object} expr
* @return {Document}
*/
populate(expr: string | any[] | { path?: string; model?: any; [key: PropertyKey]: any }): Document<T> {
const stack = this._schema._parsePopulate(expr);
return this._model._populate(this, stack);
}
}
function isGetter(obj: any, key: PropertyKey): any {
return Object.getOwnPropertyDescriptor(obj, key).get;
}
export default Document;