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