var _ = require('lodash');
var Promise = require('bluebird');
var Sequelize = require('sequelize');
var ResourceNotFound = require('./errors').ResourceNotFound;
var ResourceAccessDenied = require('./errors').ResourceAccessDenied;
var ResourceExpired = require('./errors').ResourceExpired;
var ConferenceState = {
NEW: 'new',
...
};
module.exports.define = function define(options) {
var sequelize = options.sequelize;
return sequelize.define('conference', {
id: {
type: Sequelize.UUID,
defaultValue: Sequelize.UUIDV4,
primaryKey: true
},
startDate: {
type: Sequelize.DATE,
},
endDate: {
type: Sequelize.DATE,
},
state: {
type: Sequelize.ENUM(
ConferenceState.NEW,
...
),
defaultValue: ConferenceState.NEW,
required: true,
allowNull: false
}
}, {
classMethods: {
getOrCreateConference: function createConference(data) {
return new Promise(function (resolve, reject) {
var Conference = sequelize.models.conference;
Conference.findOne({
where: data
}).then(function(conference){
if(_.isObject(conference)) {
resolve(conference);
} else {
return Conference.create(data);
}
}).then(function(conference){
resolve(conference);
}).catch(function(err){
reject(err);
});
});
},
scheduleConference: function scheduleConference(start, end) {
// TODO
},
}
});
};
我的问题现在是关于如何处理以下任务的理论问题:
所以会议有一个修复开始和结束日期。它必须包含具有值的字段,并且在尚未启动或已结束时也无法加入。否则会引发错误。
所以我需要一个mehtode说,我想安排一个会议并传递开始/结束值。
这可以在一种方法中完成,还是应该拆分?我需要哪些方法以及他们在程序中基本上会做什么?
答案 0 :(得分:1)
根据您的评论,您的scheduleConference
方法必须只更新指定的实例(会议)。你确实把它放在classMethods
中,但我建议你把它放在instanceMethods
中,它的简单实现可能如下:
classMethods: {
},
instanceMethods: {
scheduleConference: function(start, end){
return this.update({ startDate: start, endDate: end }).then((conference) => {
// here you get updated instance of conference
return reference;
});
}
}
以上方法可以这样使用
// assuming that conference is a sequelize model instance
conference.scheduleConference(start, end).then((self) => {
// updated conference as self
});
<小时/> 的修改
我看到你已经实现了getOrCreateConference
方法,但是sequelize本身提供了这种方法,它被称为findOrCreate
。您可以在models.Model.findOrCreate()