Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sailsjs model static method

I'm trying to create a type definition for sails.js's Model interface. sails.js allows you to define a simple file which exports an object with a nested "attributes" object. Each attribute corresponds to a column name in a database, and the column type.

//MyModel.js
module.exports = {

  attributes:{
     name:"string"
  }

}; 

To use this model in your code, you write some code like so:

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

The code I wrote looks like so:

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;

Here's the problem I'm having. In order for sailsjs to interface with my typescript code properly, module.exports has to have that attributes object on it with the database type definitions. This wouldn't be a problem, except when I try to use this class, it needs the static methods like create which aren't on there.

I would like to be able to write my typescript code using the model like so:

MyModel.create({name:"bob"}).then((result:MyModel) => {
   //do stuff with result
});
like image 952
aclave1 Avatar asked Dec 04 '25 12:12

aclave1


1 Answers

I've solved it but it isn't pretty:

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

  }

}

I'm still working on it, I'll update this once I've got the full implementation done.

Edit: I've created a blog post fully describing the approach i've taken. Using typescript with sails.js

like image 125
aclave1 Avatar answered Dec 06 '25 11:12

aclave1



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!