PeerTube/server/models/author.js

91 lines
1.7 KiB
JavaScript
Raw Normal View History

2016-12-28 15:49:23 +01:00
'use strict'
const customUsersValidators = require('../helpers/custom-validators').users
2016-12-11 21:50:51 +01:00
module.exports = function (sequelize, DataTypes) {
const Author = sequelize.define('Author',
{
name: {
2016-12-28 15:49:23 +01: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 21:50:51 +01:00
}
},
{
2016-12-29 09:33:28 +01:00
indexes: [
{
fields: [ 'name' ]
},
{
fields: [ 'podId' ]
},
{
2017-02-16 19:24:34 +01:00
fields: [ 'userId' ],
unique: true
},
{
fields: [ 'name', 'podId' ],
unique: true
2016-12-29 09:33:28 +01:00
}
],
2016-12-11 21:50:51 +01:00
classMethods: {
2016-12-29 18:02:03 +01:00
associate,
findOrCreateAuthor
2016-12-11 21:50:51 +01: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 21:50:51 +01:00
}
2016-12-29 18:02:03 +01: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])
})
}