-
Notifications
You must be signed in to change notification settings - Fork 13
/
index.js
376 lines (295 loc) · 9.49 KB
/
index.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
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
'use strict';
const _ = require('./vendor/lodash');
const Sequelize = require('sequelize');
const PLAIN_TYPES = ['string', 'number', 'boolean'];
const ARRAY_TYPES = [
'Array',
'Int8Array',
'Uint8Array',
'Uint8ClampedArray',
'Int16Array',
'Uint16Array',
'Int32Array',
'Uint32Array',
'Float32Array',
'Float64Array'
];
const DOC_DB_TYPES = ['JSON', 'JSONB', 'HSTORE'];
function _padWith0(v) {
v = '' + v;
return v.length == 1 ? '0' + v : v;
}
function encodeToJSON(value, options) {
let className = (value && typeof(value.constructor) === 'function') ? value.constructor.name : null;
if(PLAIN_TYPES.indexOf(typeof(value)) > -1 || value === null) {
return value;
} else if(ARRAY_TYPES.indexOf(className) > -1) {
let result = [];
for(let e of value) {
result.push(encodeToJSON(e, options));
}
return result;
} else if(value instanceof Date) {
return value.toISOString();
} else if(value instanceof Buffer) {
return value.toString(options.blobEncoding);
} else if(typeof(value) === 'object') {
let result = {};
for(let key in value) {
if(value.hasOwnProperty(key)) {
result[key] = encodeToJSON(value[key], options);
}
}
return result;
} else {
throw new Error('Can\'t encode ' + typeof(value) + ' to JSON');
}
}
const _policies = { FAIL: 1, SKIP: 2, SET_NULL: 3 };
let _defaultOptions = {
encoder: encodeToJSON,
undefinedPolicy: _policies.SKIP,
copyJSONFields: true,
simpleDates: true,
encoderOptions: {
blobEncoding: 'base64'
}
};
function _getSchemeFromModel(model, scheme) {
if(model.serializer && model.serializer.schemes) {
return model.serializer.schemes[scheme] || null;
}
return null;
}
function _isModel(obj, sequelize, seqVer) {
if(seqVer >= 5) {
return obj.prototype instanceof Sequelize.Model;
} else if (seqVer >= 4) {
return obj.prototype instanceof sequelize.Model;
} else {
return obj instanceof sequelize.Model;
}
}
function _isModelInstance(obj, sequelize, seqVer) {
if(seqVer >= 5) {
return obj instanceof Sequelize.Model;
} else if (seqVer >= 4) {
return obj instanceof sequelize.Model;
} else {
return obj instanceof sequelize.Instance;
}
}
function _getModelFromInstance(inst, seqVer) {
if(seqVer >= 4) {
return inst.constructor;
} else {
return inst.Model;
}
}
function _isSpecificModelInstance(obj, model, seqVer) {
if(seqVer >= 4) {
return obj instanceof model;
} else {
return obj instanceof model.Instance;
}
}
class Serializer {
constructor(model, scheme, options) {
const sequelize = model.sequelize || {};
let seqVer = 1 * (sequelize.constructor.version || '-').split('.', 2)[0]; // major version as number
let schemeName = null;
if(!(sequelize.Model || Sequelize.Model) || isNaN(seqVer) || !_isModel(model, sequelize, seqVer)) {
throw new Error('' + model + ' is not a valid Sequelize model');
}
if(typeof(scheme) === 'string') {
schemeName = scheme;
scheme = _getSchemeFromModel(model, scheme);
} else if(!scheme) {
if(model.serializer) {
let schemes = model.serializer.schemes || {};
if(model.serializer.defaultScheme) {
schemeName = model.serializer.defaultScheme;
scheme = schemes[model.serializer.defaultScheme];
} else {
if(schemes.default) {
schemeName = 'default';
scheme = schemes.default;
} else {
scheme = {};
}
}
} else {
scheme = {};
}
}
if(!scheme || typeof(scheme) !== 'object') {
throw new Error('Invalid serialization scheme for ' + model.name + ': ' + scheme);
}
this._origOptions = options;
this._options = _.defaultsDeep(
{},
options,
scheme.options,
model.serializer ? model.serializer.options : null,
_defaultOptions
);
this._seq = sequelize;
this._seqVer = seqVer;
this._model = model;
this._scheme = scheme;
this._schemeName = schemeName;
this._attr = {
all: [],
virtual: [],
pk: [],
fk: [],
assoc: [],
blob: [],
doc: [],
auto: []
};
this._collectAttrs();
this._attrList = this._compileAttributesList(scheme);
}
_collectAttrs() {
let attr = this._attr;
let a, typeName;
const rawAttributes = this._model.attributes || this._model.rawAttributes;
for(let name in rawAttributes) {
if(!rawAttributes.hasOwnProperty(name)) continue;
a = rawAttributes[name];
if(this._options.attrFilter && this._options.attrFilter(a, this._model) === false) {
continue;
}
typeName = a.type.key;
attr.all.push(a.fieldName);
if(a.primaryKey) attr.pk.push(a.fieldName);
if(a.references) attr.fk.push(a.fieldName);
if(a._autoGenerated) attr.auto.push(a.fieldName);
if(typeName == 'VIRTUAL') attr.virtual.push(a.fieldName);
else if(typeName == 'BLOB') attr.blob.push(a.fieldName);
else if(DOC_DB_TYPES.indexOf(typeName) > -1) attr.doc.push(a.fieldName);
}
for(let name in this._model.associations) {
//if(!this._model.attributes.hasOwnProperty(name)) continue;
a = this._model.associations[name];
attr.assoc.push(a.as);
}
}
_expandAttributes(list) {
let attr = this._attr;
let result = [];
for(let a of list) {
if(a[0] == '@') {
result = result.concat(result, this._attr[a.substr(1)]);
} else {
result.push(a);
}
}
return _.uniq(result);
}
_compileAttributesList(scheme) {
let
include = scheme.include ? this._expandAttributes(scheme.include) : this._attr.all,
exclude = scheme.exclude ? this._expandAttributes(scheme.exclude) : [],
result = [];
for(let a of include) {
if(exclude.indexOf(a) < 0) {
result.push(a[0] != '.' && this._attr.all.indexOf(a) < 0 && this._attr.assoc.indexOf(a) < 0 ? '.' + a : a);
}
}
return result;
}
_serializeValue(attr, value, cache) {
const attributes = this._model.attributes || this._model.rawAttributes;
const a = attributes[attr];
let returnJSON = false;
if(a && this._options.copyJSONFields) {
returnJSON = (a.type instanceof this._seq.Sequelize.JSON || a.type instanceof this._seq.Sequelize.JSONB);
}
if(returnJSON) {
return value;
} else if(value instanceof Array) {
let result = [];
for(let e of value) {
result.push(this._serializeValue(attr, e, cache));
}
return result;
} else if(_isModelInstance(value, this._seq, this._seqVer)) {
return this._serializeAssoc(attr, value, cache);
} else {
if(this._options.simpleDates && a && a.type instanceof this._seq.Sequelize.DATEONLY && value instanceof Date) {
value = value.getFullYear() + '-' + _padWith0(value.getMonth() + 1) + '-' + _padWith0(value.getDate());
}
return this._options.encoder(value, this._options.encoderOptions);
}
}
_serializeAssoc(attr, inst, cache) {
let attrPath = (this._attrPath ? this._attrPath + '.' : '') + attr;
let serializer;
if(cache && cache[attrPath]) {
serializer = cache[attrPath];
} else {
let scheme = this._scheme.assoc ? this._scheme.assoc[attr] : null;
serializer = new Serializer(_getModelFromInstance(inst, this._seqVer), scheme, this._origOptions);
serializer._attrPath = attrPath;
if(cache) cache[attrPath] = serializer;
}
return serializer.serialize(inst, cache);
}
serialize(inst, cache) {
if(!_isSpecificModelInstance(inst, this._model, this._seqVer)) {
throw new Error('Not an instance of ' + this._model.name);
}
let output = {}, value, name;
for(let a of this._attrList) {
// if the attribute name is dot-prefixed, always treat it as a regular attribute of the model instance
if(a[0] !== '.' && this._attr.all.indexOf(a) > -1) {
value = inst.get(a);
} else {
if(a[0] === '.') a = a.substr(1);
value = inst[a];
if(typeof(value) === 'function') {
value = value.call(inst);
}
}
name = (this._scheme.as ? this._scheme.as[a] : null) || a;
if(typeof(value) !== 'undefined') {
output[name] = this._serializeValue(a, value, cache);
} else {
switch(this._options.undefinedPolicy) {
case _policies.SKIP:
break;
case _policies.SET_NULL:
output[name] = null;
break;
case _policies.FAIL:
throw new Error('Undefined attribute on ' + this._model.name + ' instance: ' + a);
default:
throw new Error('Invalid undefinedPolicy setting');
}
}
}
if(this._model.serializer && this._model.serializer.postSerialize) {
output = this._model.serializer.postSerialize.call(this._scheme, output, inst, this._schemeName);
}
if(this._scheme.postSerialize) {
output = this._scheme.postSerialize(output, inst);
}
return output;
}
static serializeMany(data, model, scheme, options) {
let serializer = new Serializer(model, scheme, options);
let cache = {}, result = [];
for(let inst of data) {
result.push(serializer.serialize(inst, cache));
}
return result;
}
}
for(let p in _policies) {
Serializer[p] = _policies[p];
}
Serializer.encodeToJSON = encodeToJSON;
Serializer.defaultOptions = _defaultOptions;
module.exports = Serializer;