]>
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 |
4e50b6a1 | 8 | let load: VideoShareMethods.Load |
d8465018 C |
9 | |
10 | export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.DataTypes) { | |
11 | VideoShare = sequelize.define<VideoShareInstance, VideoShareAttributes>('VideoShare', | |
12 | { }, | |
13 | { | |
14 | indexes: [ | |
15 | { | |
16 | fields: [ 'accountId' ] | |
17 | }, | |
18 | { | |
19 | fields: [ 'videoId' ] | |
20 | } | |
21 | ] | |
22 | } | |
23 | ) | |
24 | ||
25 | const classMethods = [ | |
d7d5611c | 26 | associate, |
4e50b6a1 C |
27 | loadAccountsByShare, |
28 | load | |
d8465018 C |
29 | ] |
30 | addMethodsToModel(VideoShare, classMethods) | |
31 | ||
32 | return VideoShare | |
33 | } | |
34 | ||
35 | // ------------------------------ METHODS ------------------------------ | |
36 | ||
37 | function associate (models) { | |
38 | VideoShare.belongsTo(models.Account, { | |
39 | foreignKey: { | |
40 | name: 'accountId', | |
41 | allowNull: false | |
42 | }, | |
43 | onDelete: 'cascade' | |
44 | }) | |
45 | ||
46 | VideoShare.belongsTo(models.Video, { | |
47 | foreignKey: { | |
48 | name: 'videoId', | |
49 | allowNull: true | |
50 | }, | |
51 | onDelete: 'cascade' | |
52 | }) | |
53 | } | |
d7d5611c | 54 | |
4e50b6a1 C |
55 | load = function (accountId: number, videoId: number) { |
56 | return VideoShare.findOne({ | |
57 | where: { | |
58 | accountId, | |
59 | videoId | |
60 | }, | |
61 | include: [ | |
62 | VideoShare['sequelize'].models.Account | |
63 | ] | |
64 | }) | |
65 | } | |
66 | ||
d7d5611c C |
67 | loadAccountsByShare = function (videoId: number) { |
68 | const query = { | |
69 | where: { | |
70 | videoId | |
71 | }, | |
72 | include: [ | |
73 | { | |
74 | model: VideoShare['sequelize'].models.Account, | |
75 | required: true | |
76 | } | |
77 | ] | |
78 | } | |
79 | ||
80 | return VideoShare.findAll(query) | |
81 | .then(res => res.map(r => r.Account)) | |
82 | } |