]>
Commit | Line | Data |
---|---|---|
d9a2a031 C |
1 | import { AllowNull, BelongsToMany, Column, CreatedAt, Model, Table, UpdatedAt } from 'sequelize-typescript' |
2 | import { Transaction } from 'sequelize/types' | |
3 | import { MTracker } from '@server/types/models/server/tracker' | |
4 | import { VideoModel } from '../video/video' | |
5 | import { VideoTrackerModel } from './video-tracker' | |
6 | ||
7 | @Table({ | |
8 | tableName: 'tracker', | |
9 | indexes: [ | |
10 | { | |
11 | fields: [ 'url' ], | |
12 | unique: true | |
13 | } | |
14 | ] | |
15 | }) | |
16 | export class TrackerModel extends Model { | |
17 | ||
18 | @AllowNull(false) | |
19 | @Column | |
20 | url: string | |
21 | ||
22 | @CreatedAt | |
23 | createdAt: Date | |
24 | ||
25 | @UpdatedAt | |
26 | updatedAt: Date | |
27 | ||
28 | @BelongsToMany(() => VideoModel, { | |
29 | foreignKey: 'trackerId', | |
30 | through: () => VideoTrackerModel, | |
31 | onDelete: 'CASCADE' | |
32 | }) | |
33 | Videos: VideoModel[] | |
34 | ||
35 | static listUrlsByVideoId (videoId: number) { | |
36 | const query = { | |
37 | include: [ | |
38 | { | |
b3d5cb92 | 39 | attributes: [ 'id' ], |
d9a2a031 C |
40 | model: VideoModel.unscoped(), |
41 | required: true, | |
42 | where: { id: videoId } | |
43 | } | |
44 | ] | |
45 | } | |
46 | ||
47 | return TrackerModel.findAll(query) | |
48 | .then(rows => rows.map(rows => rows.url)) | |
49 | } | |
50 | ||
51 | static findOrCreateTrackers (trackers: string[], transaction: Transaction): Promise<MTracker[]> { | |
52 | if (trackers === null) return Promise.resolve([]) | |
53 | ||
54 | const tasks: Promise<MTracker>[] = [] | |
55 | trackers.forEach(tracker => { | |
56 | const query = { | |
57 | where: { | |
58 | url: tracker | |
59 | }, | |
60 | defaults: { | |
61 | url: tracker | |
62 | }, | |
63 | transaction | |
64 | } | |
65 | ||
66 | const promise = TrackerModel.findOrCreate<MTracker>(query) | |
67 | .then(([ trackerInstance ]) => trackerInstance) | |
68 | tasks.push(promise) | |
69 | }) | |
70 | ||
71 | return Promise.all(tasks) | |
72 | } | |
73 | } |