Sailsjs模型静态方法

Sailsjs model static method

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

//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 正确地与我的 typescript 代码交互,module.exports 必须在其上包含带有数据库类型定义的属性对象。这不是问题,除非我尝试使用这个 class,它需要像 create 这样的静态方法,但那里没有。

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

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

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

//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{

  }

}

我还在努力,一旦我完成了完整的实施,我会更新这个。

编辑:我创建了一个博客post,充分描述了我所采用的方法。 Using typescript with sails.js