Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/474.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何访问环回模型属性类型?(模型.定义.属性.类型)_Javascript_Types_Loopbackjs - Fatal编程技术网

Javascript 如何访问环回模型属性类型?(模型.定义.属性.类型)

Javascript 如何访问环回模型属性类型?(模型.定义.属性.类型),javascript,types,loopbackjs,Javascript,Types,Loopbackjs,如何从模型扩展文件model.js中访问模型属性类型 如果尝试访问MODEL.definition.properties,则可以看到给定属性的以下内容: { type: [Function: String], [1] required: false, [1] description: 'deal stage' } 为什么类型被列为[Function:String],而不仅仅是String或类似的类型 如果我运行typeofproperty.type,它将返回函数,但如果我运行prope

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

如果尝试访问MODEL.definition.properties,则可以看到给定属性的以下内容:

{ type: [Function: String],
[1]   required: false,
[1]   description: 'deal stage' }
为什么类型被列为[Function:String],而不仅仅是String或类似的类型

如果我运行typeofproperty.type,它将返回函数,但如果我运行property.type,它将返回一个空字符串。

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

var type=typeofproperty.type

变量类型将是字符串、数字等

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

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

TL;博士

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

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

环回允许以多种方式定义属性类型:

作为字符串名称,例如{type:'string',description:'deal stage'}。您也可以使用模型名称作为类型,例如{type:'Customer'}。 作为类型构造函数,例如{type:String,description:'deal stage'}。您也可以使用模型构造函数作为类型,例如{type:Customer}。 作为匿名模型的定义,例如{type:{street:String,city:String,country:String} 作为数组类型。可以使用上述三种方式中的任意一种指定数组项的类型,如字符串名称、类型构造函数或匿名模型定义。 请阅读我们文档中的更多内容:

为了更好地理解如何处理不同类型的属性定义,您可以检查loopback swagger中的代码,该代码正在将环回模型模式转换为类似于JSON模式的swagger模式:

函数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';
};

米罗斯拉夫,谢谢你的详细回答!我要试试这个。