aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/models/author.js
diff options
context:
space:
mode:
Diffstat (limited to 'server/models/author.js')
-rw-r--r--server/models/author.js85
1 files changed, 85 insertions, 0 deletions
diff --git a/server/models/author.js b/server/models/author.js
new file mode 100644
index 000000000..7d15fb6ec
--- /dev/null
+++ b/server/models/author.js
@@ -0,0 +1,85 @@
1'use strict'
2
3const customUsersValidators = require('../helpers/custom-validators').users
4
5module.exports = function (sequelize, DataTypes) {
6 const Author = sequelize.define('Author',
7 {
8 name: {
9 type: DataTypes.STRING,
10 allowNull: false,
11 validate: {
12 usernameValid: function (value) {
13 const res = customUsersValidators.isUserUsernameValid(value)
14 if (res === false) throw new Error('Username is not valid.')
15 }
16 }
17 }
18 },
19 {
20 indexes: [
21 {
22 fields: [ 'name' ]
23 },
24 {
25 fields: [ 'podId' ]
26 },
27 {
28 fields: [ 'userId' ]
29 }
30 ],
31 classMethods: {
32 associate,
33
34 findOrCreateAuthor
35 }
36 }
37 )
38
39 return Author
40}
41
42// ---------------------------------------------------------------------------
43
44function associate (models) {
45 this.belongsTo(models.Pod, {
46 foreignKey: {
47 name: 'podId',
48 allowNull: true
49 },
50 onDelete: 'cascade'
51 })
52
53 this.belongsTo(models.User, {
54 foreignKey: {
55 name: 'userId',
56 allowNull: true
57 },
58 onDelete: 'cascade'
59 })
60}
61
62function findOrCreateAuthor (name, podId, userId, transaction, callback) {
63 if (!callback) {
64 callback = transaction
65 transaction = null
66 }
67
68 const author = {
69 name,
70 podId,
71 userId
72 }
73
74 const query = {
75 where: author,
76 defaults: author
77 }
78
79 if (transaction) query.transaction = transaction
80
81 this.findOrCreate(query).asCallback(function (err, result) {
82 // [ instance, wasCreated ]
83 return callback(err, result[0])
84 })
85}