Blame view

node_modules/loopback-datasource-juggler/lib/introspection.js 1.56 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
  // Copyright IBM Corp. 2013,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';
  
  module.exports = function getIntrospector(ModelBuilder) {
    function introspectType(value) {
      // Unknown type, using Any
      if (value === null || value === undefined) {
        return ModelBuilder.Any;
      }
  
      // Check registered schemaTypes
      for (var t in ModelBuilder.schemaTypes) {
        var st = ModelBuilder.schemaTypes[t];
        if (st !== Object && st !== Array && (value instanceof st)) {
          return t;
        }
      }
  
      var type = typeof value;
      if (type === 'string' || type === 'number' || type === 'boolean') {
        return type;
      }
  
      if (value instanceof Date) {
        return 'date';
      }
  
      var itemType;
      if (Array.isArray(value)) {
        for (var i = 0; i < value.length; i++) {
          if (value[i] === null || value[i] === undefined) {
            continue;
          }
          itemType = introspectType(value[i]);
          if (itemType) {
            return [itemType];
          }
        }
        return 'array';
      }
  
      if (type === 'function') {
        return value.constructor.name;
      }
  
      var properties = {};
      for (var p in value) {
        itemType = introspectType(value[p]);
        if (itemType) {
          properties[p] = itemType;
        }
      }
      if (Object.keys(properties).length === 0) {
        return 'object';
      }
      return properties;
    }
  
    ModelBuilder.introspect = introspectType;
    return introspectType;
  };