How to make model methods in api plan

I use sails mainly to provide a robust backend rest api. My problem is that in my model I need to calculate some element because there is no need to store it in the database. When I write these methods using what's in doc : the results of calling the bluePrint API are not displayed

to resume having this model:

module.exports = {
    autoPK: true,
    attributes: {
        host: {
            type: 'string',
        },
        url: {
            type: 'string',
        },
        start: {
            type: 'date',
        },
        end: {
            type: 'date',
        },
        getDuration: function(){ // <---- I need to get this info using bluePrint 
            var diff  = this.end - this.start;
            return diff;
        }
    }
};

      

when calling GET / api / session

it returns:

{
    "host": "localhost:8081",
    "url": "http://localhost:8081/db/LogStats/session",
    "start": "2015-06-19T17:35:57.000Z",
    "end": "2015-06-19T17:36:07.000Z",
    "createdAt": "2015-06-19T17:35:57.737Z",
    "updatedAt": "2015-06-19T17:36:07.840Z",
    "id": "558452fde383b73a62ee07b8"
}

      

I would like to have the json above WITH additional field duration "

EDIT: Below are the answers to the following questions:

module.exports = {
    autoPK: true,
    attributes: {
        host: {
            type: 'string',
        },
        url: {
            type: 'string',
        },
        start: {
            type: 'date',
        },
        end: {
            type: 'date',
        },
        getDuration: function(){
            return (new Date(this.end).getTime() - new Date(this.start).getTime()) / 1000;
        },
        toJSON: function() {
            var session = this.toObject();
            session.duration = this.getDuration();
            return session;
        }
    }
};

      

+3


source to share


2 answers


It sounds like you want to override the function of toJSON

your model to make it larger. Take a look here: https://github.com/balderdashy/waterline#model .



In the function, toJSON

you can apply any attribute you want.

+3


source


I think your problem is that you are trying to compare two strings that will occur with NaN

.

So, you need to convert two dates to Date Objects

.

I would do it like this:



getDuration: function()
        return (new Date(this.end).getTime() - new Date(this.start).getTime()) / 1000;
    }

      

Then you get the difference in seconds. Also remember to "cancel" your application after changing models / controllers.

+2


source







All Articles