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