]>
Commit | Line | Data |
---|---|---|
e02643f3 C |
1 | import * as Sequelize from 'sequelize' |
2 | ||
74889a71 | 3 | import { isUserUsernameValid } from '../../helpers' |
67bf9b96 | 4 | |
74889a71 | 5 | import { addMethodsToModel } from '../utils' |
e02643f3 | 6 | import { |
e02643f3 C |
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 | ||
127944aa | 16 | export 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 | ||
58 | function 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 | }) | |
feb4bdfd | 74 | } |
4ff0d862 | 75 | |
6fcd19ba | 76 | findOrCreateAuthor = function (name: string, podId: number, userId: number, transaction: Sequelize.Transaction) { |
4ff0d862 C |
77 | const author = { |
78 | name, | |
79 | podId, | |
80 | userId | |
81 | } | |
82 | ||
6fcd19ba | 83 | const query: Sequelize.FindOrInitializeOptions<AuthorAttributes> = { |
4ff0d862 | 84 | where: author, |
6fcd19ba C |
85 | defaults: author, |
86 | transaction | |
4ff0d862 C |
87 | } |
88 | ||
6fcd19ba | 89 | return Author.findOrCreate(query).then(([ authorInstance ]) => authorInstance) |
4ff0d862 | 90 | } |