aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/models/author.ts
diff options
context:
space:
mode:
authorChocobozzz <florian.bigard@gmail.com>2017-05-15 22:22:03 +0200
committerChocobozzz <florian.bigard@gmail.com>2017-05-20 09:57:40 +0200
commit65fcc3119c334b75dd13bcfdebf186afdc580a8f (patch)
tree4f2158c61a9b7c3f47cfa233d01413b946ee53c0 /server/models/author.ts
parentd5f345ed4cfac4e1fa84dcb4fce1cda4d32f9c73 (diff)
downloadPeerTube-65fcc3119c334b75dd13bcfdebf186afdc580a8f.tar.gz
PeerTube-65fcc3119c334b75dd13bcfdebf186afdc580a8f.tar.zst
PeerTube-65fcc3119c334b75dd13bcfdebf186afdc580a8f.zip
First typescript iteration
Diffstat (limited to 'server/models/author.ts')
-rw-r--r--server/models/author.ts90
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 @@
1import { isUserUsernameValid } from '../helpers'
2
3module.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
47function 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
65function 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}