This repository was archived by the owner on Oct 21, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathschema.js
More file actions
107 lines (77 loc) · 2.53 KB
/
schema.js
File metadata and controls
107 lines (77 loc) · 2.53 KB
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
"use strict";
var mongoose = require('mongoose-q')(require('mongoose')),
waigo = require('waigo');
/** @type {Object} Base schema class. */
exports.Schema = mongoose.Schema;
/**
* Create a Mongoose schema.
*
* This will ensure all Mongoose models created from this schema implement the
* `HasViewObject` mixin. The mixin will also be applied to collections of
* model instances so that query results can be rendered directly to the client.
*
* @param {Object} schemaDescription Gets passed to mongoose.Schema constructor
* @param {Object} options Gets passed to mongoose.Schema constructor
* @param {Object} [options.addTimestampFields] If set then `created_at` and `updated_at` timestamp fields will be added and automatically managed.
* @return {Object} The created `mongoose.Schema`.
*/
exports.create = function(schemaDescription, options) {
options = options || {};
// add timestamp fields
if (options.addTimestampFields) {
schemaDescription.created_at = schemaDescription.updated_at = Date;
}
var schema = new mongoose.Schema(schemaDescription, options);
// auto-set timestamp fields during 'save'
if (options.addTimestampFields) {
schema.pre('save', function(next){
var now = new Date();
this.updated_at = now;
if ( !this.created_at ) {
this.created_at = now;
}
next();
});
}
/**
* Get which keys to include when generating a view object representation.
*
* @param {Object} ctx Request context.
* @return {Array}
*/
schema.method('viewObjectKeys', function(ctx) {
return ['_id'].concat(Object.keys(schemaDescription));
});
/**
* Format a value for inclusion in a view object.
*
* @param {Object} ctx Request context.
* @param {String} key Key to which value belongs.
* @param {*} val The value.
* @return {*}
*/
schema.method('formatForViewObject', function*(ctx, key, val) {
return val;
});
/**
* Get view object representation of this model.
* @param {Object} ctx Request context.
* @return {Object}
*/
schema.method('toViewObject', function*(ctx) {
var self = this;
var ret = {};
var keys = self.viewObjectKeys(ctx);
for (let idx in keys) {
let key = keys[idx];
ret[key] = self[key];
if (ret[key] instanceof mongoose.Model) {
ret[key] = yield ret[key].toViewObject(ctx);
} else {
ret[key] = yield self.formatForViewObject(ctx, key, ret[key]);
}
}
return ret;
});
return schema;
};