【问题标题】:Sailsjs model static methodSailsjs模型静态方法
【发布时间】:2015-03-20 22:17:23
【问题描述】:

我正在尝试为sails.js 的模型接口创建类型定义。 sails.js 允许您定义一个简单的文件,该文件导出具有嵌套“属性”对象的对象。每个属性对应于数据库中的一个列名,以及列类型。

//MyModel.js
module.exports = {

  attributes:{
     name:"string"
  }

}; 

要在您的代码中使用此模型,您可以编写如下代码:

MyModel.create({name:"alex"}).then(function(result){
   //the model was inserted into the DB, result is the created record.
});

我写的代码是这样的:

declare module Sails{

  export interface Model{
    create(params:Object):Promise<Sails.Model>;
  }
}

class Model implements Sails.Model{

  create(params:Object):Promise<Sails.Model> {
    return undefined;
  }

  attributes:Object;

  constructor(attributes:Object){
    this.attributes = attributes;
  }


}

class MyModel extends Model{
    constructor(attributes:Object){
        super(attributes);
     }
}

var _export = new MyModel({name:string});

export = _export;

这是我遇到的问题。为了让sailsjs 正确地与我的打字稿代码交互,module.exports 必须在其上具有该属性对象以及数据库类型定义。这不会是一个问题,除非当我尝试使用这个类时,它需要像 create 这样的静态方法,而这些方法并不存在。

我希望能够使用这样的模型编写我的打字稿代码:

MyModel.create({name:"bob"}).then((result:MyModel) => {
   //do stuff with result
});

【问题讨论】:

    标签: typescript sails.js definitelytyped


    【解决方案1】:

    我已经解决了,但它并不漂亮:

    //api/models/MyModel.ts
    import Model = require('./Model');
    
    var MyModel = new Model({
      name:"string"
    });
    
    export = MyModel;
    
    
    //api/model/Model.ts
    class Model {
    
      attributes:Object;
      constructor(attributes:Object){
        this.attributes = attributes;
      }
    
    }
    export = Model;
    
    
    //api/types/MyModelQuery.ts
    //this file maps to the attributes of a query result
    
    declare class ScreenQuery {
      name:string;
    }
    export = ScreenQuery;
    
    
    //sails.d.ts
    
    declare module Sails{
    
      export interface Model{
        create(params:Object):Promise<Sails.QueryResult>;
        attributes:Object;
      }
    
      export interface QueryResult{
    
      }
    
      export interface Controller{
    
      }
    
    }
    

    我仍在努力,一旦我完成了完整的实施,我会更新它。

    编辑:我创建了一篇博客文章,全面描述了我所采用的方法。 Using typescript with sails.js

    【讨论】:

      猜你喜欢
      • 2014-06-21
      • 1970-01-01
      • 2017-02-16
      • 1970-01-01
      • 2013-11-14
      • 1970-01-01
      • 2018-09-30
      相关资源
      最近更新 更多