]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/models/author.ts
require -> import
[github/Chocobozzz/PeerTube.git] / server / models / author.ts
1 import * as Sequelize from 'sequelize'
2
3 import { isUserUsernameValid } from '../helpers'
4
5 import { addMethodsToModel } from './utils'
6 import {
7 AuthorClass,
8 AuthorInstance,
9 AuthorAttributes,
10
11 AuthorMethods
12 } from './author-interface'
13
14 let Author: Sequelize.Model<AuthorInstance, AuthorAttributes>
15 let findOrCreateAuthor: AuthorMethods.FindOrCreateAuthor
16
17 export default function defineAuthor (sequelize: Sequelize.Sequelize, DataTypes) {
18 Author = sequelize.define<AuthorInstance, AuthorAttributes>('Author',
19 {
20 name: {
21 type: DataTypes.STRING,
22 allowNull: false,
23 validate: {
24 usernameValid: function (value) {
25 const res = isUserUsernameValid(value)
26 if (res === false) throw new Error('Username is not valid.')
27 }
28 }
29 }
30 },
31 {
32 indexes: [
33 {
34 fields: [ 'name' ]
35 },
36 {
37 fields: [ 'podId' ]
38 },
39 {
40 fields: [ 'userId' ],
41 unique: true
42 },
43 {
44 fields: [ 'name', 'podId' ],
45 unique: true
46 }
47 ]
48 }
49 )
50
51 const classMethods = [ associate, findOrCreateAuthor ]
52 addMethodsToModel(Author, classMethods)
53
54 return Author
55 }
56
57 // ---------------------------------------------------------------------------
58
59 function associate (models) {
60 Author.belongsTo(models.Pod, {
61 foreignKey: {
62 name: 'podId',
63 allowNull: true
64 },
65 onDelete: 'cascade'
66 })
67
68 Author.belongsTo(models.User, {
69 foreignKey: {
70 name: 'userId',
71 allowNull: true
72 },
73 onDelete: 'cascade'
74 })
75 }
76
77 findOrCreateAuthor = function (name, podId, userId, transaction, callback) {
78 if (!callback) {
79 callback = transaction
80 transaction = null
81 }
82
83 const author = {
84 name,
85 podId,
86 userId
87 }
88
89 const query: any = {
90 where: author,
91 defaults: author
92 }
93
94 if (transaction) query.transaction = transaction
95
96 Author.findOrCreate(query).asCallback(function (err, result) {
97 if (err) return callback(err)
98
99 // [ instance, wasCreated ]
100 return callback(null, result[0])
101 })
102 }