如何使模型方法显示在蓝图api中

时间:2015-06-24 13:03:46

标签: javascript sails.js

我主要使用帆来提供稳固的后端休息api。我的问题是在我的模型中我需要计算一些元素,因为不需要存储在数据库中。当我使用doc中的内容编写这些方法时:bluePrint API调用的结果未显示

所以要恢复,有这个模型:

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;
        }
    }
};

调用 GET / api / session

它返回:

{
    "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"
}

我想让json高于 WITH 额外字段“持续时间

修改 感谢下面的答案,如何实现它:

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;
        }
    }
};

2 个答案:

答案 0 :(得分:3)

听起来您想要覆盖模型的toJSON功能来增强它。看看这里:https://github.com/balderdashy/waterline#model

toJSON函数中,您可以使用任何所需的属性。

答案 1 :(得分:2)

我认为您的问题是您尝试比较两个字符串,这些字符串会与NaN进行比较。

因此,您必须先将两个日期转换为Date Objects

我会这样做:

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

然后你会在几秒钟内得到差异。 在更换模型/控制器后,也不要忘记“重新移动”你的应用程序。