您如何访问回送模型属性类型? (model.definition.properties.type)

时间:2018-10-21 14:59:09

标签: javascript types loopbackjs

如何从模型扩展文件(model.js)中访问模型属性类型?

如果我尝试访问MODEL.definition.properties,对于给定的属性,我将看到以下内容:

{ type: [Function: String],
[1]   required: false,
[1]   description: 'deal stage' }

为什么将类型列出为[Function: String]而不是“ String”之类的?

如果我运行typeof(property.type),它将返回“ function”,但是如果我运行property.type(),它将返回一个空字符串。

2 个答案:

答案 0 :(得分:1)

免责声明:我是LoopBack的合著者和当前维护者。

TL; DR

使用以下表达式获取属性类型作为字符串名称。请注意,它仅适用于可能的属性定义的子集(请参阅下文),最值得注意的是,它不支持数组。

const type = typeof property.type === 'string' 
  ? property.type
  : property.type.modelName || property.type.name;

长版

LoopBack允许以几种方式定义属性类型:

  1. 作为字符串名称,例如{type: 'string', description: 'deal stage'}。您也可以使用型号名称作为类型,例如{type: 'Customer'}
  2. 作为类型构造函数,例如{type: String, description: 'deal stage'}。您也可以使用模型构造函数作为类型,例如{type: Customer}
  3. 作为匿名模型的定义,例如{type: {street: String, city: String, country: String}
  4. 作为数组类型。可以使用上述三种方式中的任何一种来指定数组项的类型(作为字符串名称,类型构造函数或匿名模型定义)。

在我们的文档中了解更多信息:LoopBack types

要更好地理解如何处理各种类型的属性定义,可以检查loopback-swagger中将LoopBack模型架构转换为Swagger架构(类似于JSON架构)的代码:

函数getLdlTypeName在输入中接受属性定义(由buildFromLoopBackType进行了规范化),并将属性类型作为字符串名称返回。

exports.getLdlTypeName = function(ldlType) {
  // Value "array" is a shortcut for `['any']`
  if (ldlType === 'array') {
    return ['any'];
  }

  if (typeof ldlType === 'string') {
    var arrayMatch = ldlType.match(/^\[(.*)\]$/);
    return arrayMatch ? [arrayMatch[1]] : ldlType;
  }

  if (typeof ldlType === 'function') {
    return ldlType.modelName || ldlType.name;
  }

  if (Array.isArray(ldlType)) {
    return ldlType;
  }

  if (typeof ldlType === 'object') {
    // Anonymous objects, they are allowed e.g. in accepts/returns definitions
    // TODO(bajtos) Build a named schema for this anonymous object
    return 'object';
  }

  if (ldlType === undefined) {
    return 'any';
  }

  var msg = g.f('Warning: unknown LDL type %j, using "{{any}}" instead', ldlType);
  console.error(msg);
  return 'any';
};

答案 1 :(得分:0)

在函数上运行typeof返回类型。

var type = typeof(property.type())

var type将是字符串,数字等。

不确定为什么环回不返回类型本身,而不是返回函数。

相关问题