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