]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/models/video/author.ts
Handle blacklist (#84)
[github/Chocobozzz/PeerTube.git] / server / models / video / author.ts
CommitLineData
e02643f3
C
1import * as Sequelize from 'sequelize'
2
74889a71 3import { isUserUsernameValid } from '../../helpers'
67bf9b96 4
74889a71 5import { addMethodsToModel } from '../utils'
e02643f3 6import {
e02643f3
C
7 AuthorInstance,
8 AuthorAttributes,
9
10 AuthorMethods
11} from './author-interface'
12
13let Author: Sequelize.Model<AuthorInstance, AuthorAttributes>
14let findOrCreateAuthor: AuthorMethods.FindOrCreateAuthor
15
127944aa 16export default function defineAuthor (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.DataTypes) {
e02643f3 17 Author = sequelize.define<AuthorInstance, AuthorAttributes>('Author',
feb4bdfd
C
18 {
19 name: {
67bf9b96
C
20 type: DataTypes.STRING,
21 allowNull: false,
22 validate: {
075f16ca 23 usernameValid: value => {
65fcc311 24 const res = isUserUsernameValid(value)
67bf9b96
C
25 if (res === false) throw new Error('Username is not valid.')
26 }
27 }
feb4bdfd
C
28 }
29 },
30 {
319d072e
C
31 indexes: [
32 {
33 fields: [ 'name' ]
34 },
35 {
36 fields: [ 'podId' ]
4712081f
C
37 },
38 {
5d67f289
C
39 fields: [ 'userId' ],
40 unique: true
41 },
42 {
43 fields: [ 'name', 'podId' ],
44 unique: true
319d072e 45 }
e02643f3 46 ]
feb4bdfd
C
47 }
48 )
49
e02643f3
C
50 const classMethods = [ associate, findOrCreateAuthor ]
51 addMethodsToModel(Author, classMethods)
52
feb4bdfd
C
53 return Author
54}
55
56// ---------------------------------------------------------------------------
57
58function associate (models) {
e02643f3 59 Author.belongsTo(models.Pod, {
feb4bdfd
C
60 foreignKey: {
61 name: 'podId',
62 allowNull: true
63 },
64 onDelete: 'cascade'
65 })
4712081f 66
e02643f3 67 Author.belongsTo(models.User, {
4712081f
C
68 foreignKey: {
69 name: 'userId',
70 allowNull: true
71 },
72 onDelete: 'cascade'
73 })
5c98d3bf
C
74
75 Author.hasMany(models.Video, {
76 foreignKey: {
77 name: 'authorId',
78 allowNull: false
79 },
80 onDelete: 'cascade'
81 })
feb4bdfd 82}
4ff0d862 83
6fcd19ba 84findOrCreateAuthor = function (name: string, podId: number, userId: number, transaction: Sequelize.Transaction) {
4ff0d862
C
85 const author = {
86 name,
87 podId,
88 userId
89 }
90
6fcd19ba 91 const query: Sequelize.FindOrInitializeOptions<AuthorAttributes> = {
4ff0d862 92 where: author,
6fcd19ba
C
93 defaults: author,
94 transaction
4ff0d862
C
95 }
96
6fcd19ba 97 return Author.findOrCreate(query).then(([ authorInstance ]) => authorInstance)
4ff0d862 98}