2016-04-12 11:42:57 +00:00
|
|
|
// Copyright IBM Corp. 2016. All Rights Reserved.
|
|
|
|
// Node module: loopback-datasource-juggler
|
|
|
|
// This file is licensed under the MIT License.
|
|
|
|
// License text available at https://opensource.org/licenses/MIT
|
2016-08-22 19:55:22 +00:00
|
|
|
'use strict';
|
2016-04-12 11:42:57 +00:00
|
|
|
|
2018-12-07 14:54:29 +00:00
|
|
|
const traverse = require('traverse');
|
2016-04-12 11:42:57 +00:00
|
|
|
|
|
|
|
exports.ContextRecorder = ContextRecorder;
|
|
|
|
exports.deepCloneToObject = deepCloneToObject;
|
|
|
|
exports.aCtxForModel = aCtxForModel;
|
|
|
|
|
|
|
|
function ContextRecorder(initialValue) {
|
|
|
|
if (!(this instanceof ContextRecorder)) {
|
|
|
|
return new ContextRecorder(initialValue);
|
|
|
|
}
|
|
|
|
this.records = initialValue;
|
2018-12-07 14:43:40 +00:00
|
|
|
}
|
2016-04-12 11:42:57 +00:00
|
|
|
|
|
|
|
ContextRecorder.prototype.recordAndNext = function(transformFm) {
|
2018-12-07 14:54:29 +00:00
|
|
|
const self = this;
|
2016-04-12 11:42:57 +00:00
|
|
|
return function(context, next) {
|
|
|
|
if (typeof transformFm === 'function') {
|
|
|
|
transformFm(context);
|
|
|
|
}
|
|
|
|
|
|
|
|
context = deepCloneToObject(context);
|
|
|
|
context.hookState.test = true;
|
|
|
|
|
|
|
|
if (typeof self.records === 'string') {
|
|
|
|
self.records = context;
|
|
|
|
return next();
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!Array.isArray(self.records)) {
|
|
|
|
self.records = [self.records];
|
|
|
|
}
|
|
|
|
|
|
|
|
self.records.push(context);
|
|
|
|
next();
|
|
|
|
};
|
|
|
|
};
|
|
|
|
|
|
|
|
function deepCloneToObject(obj) {
|
|
|
|
return traverse(obj).map(function(x) {
|
|
|
|
if (x === undefined) {
|
|
|
|
// RDBMSs return null
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
if (x && x.toObject)
|
|
|
|
return x.toObject(true);
|
|
|
|
if (x && typeof x === 'function' && x.modelName)
|
|
|
|
return '[ModelCtor ' + x.modelName + ']';
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
function aCtxForModel(TestModel, ctx) {
|
|
|
|
ctx.Model = TestModel;
|
|
|
|
|
|
|
|
if (!ctx.hookState) {
|
|
|
|
ctx.hookState = {};
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!('test' in ctx.hookState)) {
|
|
|
|
ctx.hookState.test = true;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!ctx.options) {
|
|
|
|
ctx.options = {};
|
|
|
|
}
|
|
|
|
return deepCloneToObject(ctx);
|
|
|
|
}
|