]>
Commit | Line | Data |
---|---|---|
d8465018 C |
1 | import * as Sequelize from 'sequelize' |
2 | ||
3 | import { addMethodsToModel } from '../utils' | |
d7d5611c | 4 | import { VideoShareAttributes, VideoShareInstance, VideoShareMethods } from './video-share-interface' |
d8465018 C |
5 | |
6 | let VideoShare: Sequelize.Model<VideoShareInstance, VideoShareAttributes> | |
d7d5611c | 7 | let loadAccountsByShare: VideoShareMethods.LoadAccountsByShare |
d8465018 C |
8 | |
9 | export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.DataTypes) { | |
10 | VideoShare = sequelize.define<VideoShareInstance, VideoShareAttributes>('VideoShare', | |
11 | { }, | |
12 | { | |
13 | indexes: [ | |
14 | { | |
15 | fields: [ 'accountId' ] | |
16 | }, | |
17 | { | |
18 | fields: [ 'videoId' ] | |
19 | } | |
20 | ] | |
21 | } | |
22 | ) | |
23 | ||
24 | const classMethods = [ | |
d7d5611c C |
25 | associate, |
26 | loadAccountsByShare | |
d8465018 C |
27 | ] |
28 | addMethodsToModel(VideoShare, classMethods) | |
29 | ||
30 | return VideoShare | |
31 | } | |
32 | ||
33 | // ------------------------------ METHODS ------------------------------ | |
34 | ||
35 | function associate (models) { | |
36 | VideoShare.belongsTo(models.Account, { | |
37 | foreignKey: { | |
38 | name: 'accountId', | |
39 | allowNull: false | |
40 | }, | |
41 | onDelete: 'cascade' | |
42 | }) | |
43 | ||
44 | VideoShare.belongsTo(models.Video, { | |
45 | foreignKey: { | |
46 | name: 'videoId', | |
47 | allowNull: true | |
48 | }, | |
49 | onDelete: 'cascade' | |
50 | }) | |
51 | } | |
d7d5611c C |
52 | |
53 | loadAccountsByShare = function (videoId: number) { | |
54 | const query = { | |
55 | where: { | |
56 | videoId | |
57 | }, | |
58 | include: [ | |
59 | { | |
60 | model: VideoShare['sequelize'].models.Account, | |
61 | required: true | |
62 | } | |
63 | ] | |
64 | } | |
65 | ||
66 | return VideoShare.findAll(query) | |
67 | .then(res => res.map(r => r.Account)) | |
68 | } |