UNPKG

1.61 kBJavaScriptView Raw
1// Copyright IBM Corp. 2013,2019. All Rights Reserved.
2// Node module: loopback-datasource-juggler
3// This file is licensed under the MIT License.
4// License text available at https://opensource.org/licenses/MIT
5
6'use strict';
7
8module.exports = function getIntrospector(ModelBuilder) {
9 function introspectType(value) {
10 // Unknown type, using Any
11 if (value === null || value === undefined) {
12 return ModelBuilder.Any;
13 }
14
15 // Check registered schemaTypes
16 for (const t in ModelBuilder.schemaTypes) {
17 const st = ModelBuilder.schemaTypes[t];
18 if (st !== Object && st !== Array && (value instanceof st)) {
19 return t;
20 }
21 }
22
23 const type = typeof value;
24 if (type === 'string' || type === 'number' || type === 'boolean') {
25 return type;
26 }
27
28 if (value instanceof Date) {
29 return 'date';
30 }
31
32 let itemType;
33 if (Array.isArray(value)) {
34 for (let i = 0; i < value.length; i++) {
35 if (value[i] === null || value[i] === undefined) {
36 continue;
37 }
38 itemType = introspectType(value[i]);
39 if (itemType) {
40 return [itemType];
41 }
42 }
43 return 'array';
44 }
45
46 if (type === 'function') {
47 return value.constructor.name;
48 }
49
50 const properties = {};
51 for (const p in value) {
52 itemType = introspectType(value[p]);
53 if (itemType) {
54 properties[p] = itemType;
55 }
56 }
57 if (Object.keys(properties).length === 0) {
58 return 'object';
59 }
60 return properties;
61 }
62
63 ModelBuilder.introspect = introspectType;
64 return introspectType;
65};