PeerTube/server/models/author.js

86 lines
1.6 KiB
JavaScript
Raw Normal View History

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' ]
},
{
fields: [ 'userId' ]
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'
})
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) {
// [ instance, wasCreated ]
return callback(err, result[0])
})
}