2020-01-21 18:12:14 +00:00
|
|
|
// Copyright IBM Corp. 2013,2019. All Rights Reserved.
|
2016-04-01 22:25:16 +00:00
|
|
|
// 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';
|
|
|
|
|
2013-08-07 21:51:32 +00:00
|
|
|
module.exports = function getIntrospector(ModelBuilder) {
|
2014-01-24 17:09:53 +00:00
|
|
|
function introspectType(value) {
|
|
|
|
// Unknown type, using Any
|
|
|
|
if (value === null || value === undefined) {
|
|
|
|
return ModelBuilder.Any;
|
|
|
|
}
|
2013-07-26 20:06:43 +00:00
|
|
|
|
2014-01-24 17:09:53 +00:00
|
|
|
// Check registered schemaTypes
|
2018-12-07 14:54:29 +00:00
|
|
|
for (const t in ModelBuilder.schemaTypes) {
|
|
|
|
const st = ModelBuilder.schemaTypes[t];
|
2014-01-24 17:09:53 +00:00
|
|
|
if (st !== Object && st !== Array && (value instanceof st)) {
|
|
|
|
return t;
|
|
|
|
}
|
|
|
|
}
|
2013-07-26 20:06:43 +00:00
|
|
|
|
2018-12-07 14:54:29 +00:00
|
|
|
const type = typeof value;
|
2014-01-24 17:09:53 +00:00
|
|
|
if (type === 'string' || type === 'number' || type === 'boolean') {
|
|
|
|
return type;
|
|
|
|
}
|
2013-07-26 20:06:43 +00:00
|
|
|
|
2014-01-24 17:09:53 +00:00
|
|
|
if (value instanceof Date) {
|
|
|
|
return 'date';
|
|
|
|
}
|
2013-07-26 20:06:43 +00:00
|
|
|
|
2018-12-07 14:54:29 +00:00
|
|
|
let itemType;
|
2014-01-24 17:09:53 +00:00
|
|
|
if (Array.isArray(value)) {
|
2018-12-07 14:54:29 +00:00
|
|
|
for (let i = 0; i < value.length; i++) {
|
2014-01-24 17:09:53 +00:00
|
|
|
if (value[i] === null || value[i] === undefined) {
|
|
|
|
continue;
|
2013-07-26 20:06:43 +00:00
|
|
|
}
|
2014-09-12 21:25:35 +00:00
|
|
|
itemType = introspectType(value[i]);
|
2014-01-24 17:09:53 +00:00
|
|
|
if (itemType) {
|
|
|
|
return [itemType];
|
2013-08-07 21:51:32 +00:00
|
|
|
}
|
2014-01-24 17:09:53 +00:00
|
|
|
}
|
|
|
|
return 'array';
|
|
|
|
}
|
2013-07-26 20:06:43 +00:00
|
|
|
|
2014-01-24 17:09:53 +00:00
|
|
|
if (type === 'function') {
|
|
|
|
return value.constructor.name;
|
|
|
|
}
|
|
|
|
|
2018-12-07 14:54:29 +00:00
|
|
|
const properties = {};
|
|
|
|
for (const p in value) {
|
2014-09-12 21:25:35 +00:00
|
|
|
itemType = introspectType(value[p]);
|
2014-01-24 17:09:53 +00:00
|
|
|
if (itemType) {
|
|
|
|
properties[p] = itemType;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if (Object.keys(properties).length === 0) {
|
|
|
|
return 'object';
|
2013-07-26 20:06:43 +00:00
|
|
|
}
|
2014-01-24 17:09:53 +00:00
|
|
|
return properties;
|
|
|
|
}
|
2013-07-26 20:06:43 +00:00
|
|
|
|
2014-09-12 21:25:35 +00:00
|
|
|
ModelBuilder.introspect = introspectType;
|
2014-01-24 17:09:53 +00:00
|
|
|
return introspectType;
|
2016-04-01 11:48:17 +00:00
|
|
|
};
|