]>
Commit | Line | Data |
---|---|---|
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 | Author.hasMany(models.Video, { | |
76 | foreignKey: { | |
77 | name: 'authorId', | |
78 | allowNull: false | |
79 | }, | |
80 | onDelete: 'cascade' | |
81 | }) | |
82 | } | |
83 | ||
84 | findOrCreateAuthor = function (name: string, podId: number, userId: number, transaction: Sequelize.Transaction) { | |
85 | const author = { | |
86 | name, | |
87 | podId, | |
88 | userId | |
89 | } | |
90 | ||
91 | const query: Sequelize.FindOrInitializeOptions<AuthorAttributes> = { | |
92 | where: author, | |
93 | defaults: author, | |
94 | transaction | |
95 | } | |
96 | ||
97 | return Author.findOrCreate(query).then(([ authorInstance ]) => authorInstance) | |
98 | } |