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