Blame view

node_modules/loopback-datasource-juggler/test/helpers/context-test-helpers.js 1.63 KB
f7563de62   Palak Handa   first commit
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
  // 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
  'use strict';
  
  var traverse = require('traverse');
  
  exports.ContextRecorder = ContextRecorder;
  exports.deepCloneToObject = deepCloneToObject;
  exports.aCtxForModel = aCtxForModel;
  
  function ContextRecorder(initialValue) {
    if (!(this instanceof ContextRecorder)) {
      return new ContextRecorder(initialValue);
    }
    this.records = initialValue;
  };
  
  ContextRecorder.prototype.recordAndNext = function(transformFm) {
    var self = this;
    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);
  }