2016-12-28 08:49:23 -06:00
|
|
|
'use strict'
|
|
|
|
|
|
|
|
const customUsersValidators = require('../helpers/custom-validators').users
|
|
|
|
|
2016-12-11 14:50:51 -06:00
|
|
|
module.exports = function (sequelize, DataTypes) {
|
|
|
|
const Author = sequelize.define('Author',
|
|
|
|
{
|
|
|
|
name: {
|
2016-12-28 08:49:23 -06:00
|
|
|
type: DataTypes.STRING,
|
|
|
|
allowNull: false,
|
|
|
|
validate: {
|
|
|
|
usernameValid: function (value) {
|
|
|
|
const res = customUsersValidators.isUserUsernameValid(value)
|
|
|
|
if (res === false) throw new Error('Username is not valid.')
|
|
|
|
}
|
|
|
|
}
|
2016-12-11 14:50:51 -06:00
|
|
|
}
|
|
|
|
},
|
|
|
|
{
|
2016-12-29 02:33:28 -06:00
|
|
|
indexes: [
|
|
|
|
{
|
|
|
|
fields: [ 'name' ]
|
|
|
|
},
|
|
|
|
{
|
|
|
|
fields: [ 'podId' ]
|
2016-12-29 03:33:36 -06:00
|
|
|
},
|
|
|
|
{
|
2017-02-16 12:24:34 -06:00
|
|
|
fields: [ 'userId' ],
|
|
|
|
unique: true
|
|
|
|
},
|
|
|
|
{
|
|
|
|
fields: [ 'name', 'podId' ],
|
|
|
|
unique: true
|
2016-12-29 02:33:28 -06:00
|
|
|
}
|
|
|
|
],
|
2016-12-11 14:50:51 -06:00
|
|
|
classMethods: {
|
2016-12-29 11:02:03 -06:00
|
|
|
associate,
|
|
|
|
|
|
|
|
findOrCreateAuthor
|
2016-12-11 14:50:51 -06:00
|
|
|
}
|
|
|
|
}
|
|
|
|
)
|
|
|
|
|
|
|
|
return Author
|
|
|
|
}
|
|
|
|
|
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
|
|
|
function associate (models) {
|
|
|
|
this.belongsTo(models.Pod, {
|
|
|
|
foreignKey: {
|
|
|
|
name: 'podId',
|
|
|
|
allowNull: true
|
|
|
|
},
|
|
|
|
onDelete: 'cascade'
|
|
|
|
})
|
2016-12-29 03:33:36 -06:00
|
|
|
|
|
|
|
this.belongsTo(models.User, {
|
|
|
|
foreignKey: {
|
|
|
|
name: 'userId',
|
|
|
|
allowNull: true
|
|
|
|
},
|
|
|
|
onDelete: 'cascade'
|
|
|
|
})
|
2016-12-11 14:50:51 -06:00
|
|
|
}
|
2016-12-29 11:02:03 -06:00
|
|
|
|
|
|
|
function findOrCreateAuthor (name, podId, userId, transaction, callback) {
|
|
|
|
if (!callback) {
|
|
|
|
callback = transaction
|
|
|
|
transaction = null
|
|
|
|
}
|
|
|
|
|
|
|
|
const author = {
|
|
|
|
name,
|
|
|
|
podId,
|
|
|
|
userId
|
|
|
|
}
|
|
|
|
|
|
|
|
const query = {
|
|
|
|
where: author,
|
|
|
|
defaults: author
|
|
|
|
}
|
|
|
|
|
|
|
|
if (transaction) query.transaction = transaction
|
|
|
|
|
|
|
|
this.findOrCreate(query).asCallback(function (err, result) {
|
2017-02-18 02:29:59 -06:00
|
|
|
if (err) return callback(err)
|
|
|
|
|
2016-12-29 11:02:03 -06:00
|
|
|
// [ instance, wasCreated ]
|
2017-02-18 02:29:59 -06:00
|
|
|
return callback(null, result[0])
|
2016-12-29 11:02:03 -06:00
|
|
|
})
|
|
|
|
}
|