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