]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/models/author.js
Server: make a basic "quick and dirty update" for videos
[github/Chocobozzz/PeerTube.git] / server / models / author.js
1 'use strict'
2
3 const customUsersValidators = require('../helpers/custom-validators').users
4
5 module.exports = function (sequelize, DataTypes) {
6 const Author = sequelize.define('Author',
7 {
8 name: {
9 type: DataTypes.STRING,
10 allowNull: false,
11 validate: {
12 usernameValid: function (value) {
13 const res = customUsersValidators.isUserUsernameValid(value)
14 if (res === false) throw new Error('Username is not valid.')
15 }
16 }
17 }
18 },
19 {
20 indexes: [
21 {
22 fields: [ 'name' ]
23 },
24 {
25 fields: [ 'podId' ]
26 },
27 {
28 fields: [ 'userId' ],
29 unique: true
30 },
31 {
32 fields: [ 'name', 'podId' ],
33 unique: true
34 }
35 ],
36 classMethods: {
37 associate,
38
39 findOrCreateAuthor
40 }
41 }
42 )
43
44 return Author
45 }
46
47 // ---------------------------------------------------------------------------
48
49 function associate (models) {
50 this.belongsTo(models.Pod, {
51 foreignKey: {
52 name: 'podId',
53 allowNull: true
54 },
55 onDelete: 'cascade'
56 })
57
58 this.belongsTo(models.User, {
59 foreignKey: {
60 name: 'userId',
61 allowNull: true
62 },
63 onDelete: 'cascade'
64 })
65 }
66
67 function findOrCreateAuthor (name, podId, userId, transaction, callback) {
68 if (!callback) {
69 callback = transaction
70 transaction = null
71 }
72
73 const author = {
74 name,
75 podId,
76 userId
77 }
78
79 const query = {
80 where: author,
81 defaults: author
82 }
83
84 if (transaction) query.transaction = transaction
85
86 this.findOrCreate(query).asCallback(function (err, result) {
87 if (err) return callback(err)
88
89 // [ instance, wasCreated ]
90 return callback(null, result[0])
91 })
92 }