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