]>
Commit | Line | Data |
---|---|---|
1 | 'use strict' | |
2 | ||
3 | const each = require('async/each') | |
4 | ||
5 | // --------------------------------------------------------------------------- | |
6 | ||
7 | module.exports = function (sequelize, DataTypes) { | |
8 | const Tag = sequelize.define('Tag', | |
9 | { | |
10 | name: { | |
11 | type: DataTypes.STRING, | |
12 | allowNull: false | |
13 | } | |
14 | }, | |
15 | { | |
16 | timestamps: false, | |
17 | indexes: [ | |
18 | { | |
19 | fields: [ 'name' ], | |
20 | unique: true | |
21 | } | |
22 | ], | |
23 | classMethods: { | |
24 | associate, | |
25 | ||
26 | findOrCreateTags | |
27 | } | |
28 | } | |
29 | ) | |
30 | ||
31 | return Tag | |
32 | } | |
33 | ||
34 | // --------------------------------------------------------------------------- | |
35 | ||
36 | function associate (models) { | |
37 | this.belongsToMany(models.Video, { | |
38 | foreignKey: 'tagId', | |
39 | through: models.VideoTag, | |
40 | onDelete: 'cascade' | |
41 | }) | |
42 | } | |
43 | ||
44 | function findOrCreateTags (tags, transaction, callback) { | |
45 | if (!callback) { | |
46 | callback = transaction | |
47 | transaction = null | |
48 | } | |
49 | ||
50 | const self = this | |
51 | const tagInstances = [] | |
52 | ||
53 | each(tags, function (tag, callbackEach) { | |
54 | const query = { | |
55 | where: { | |
56 | name: tag | |
57 | }, | |
58 | defaults: { | |
59 | name: tag | |
60 | } | |
61 | } | |
62 | ||
63 | if (transaction) query.transaction = transaction | |
64 | ||
65 | self.findOrCreate(query).asCallback(function (err, res) { | |
66 | if (err) return callbackEach(err) | |
67 | ||
68 | // res = [ tag, isCreated ] | |
69 | const tag = res[0] | |
70 | tagInstances.push(tag) | |
71 | return callbackEach() | |
72 | }) | |
73 | }, function (err) { | |
74 | return callback(err, tagInstances) | |
75 | }) | |
76 | } |