]>
git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/models/request.js
3 const values
= require('lodash/values')
5 const constants
= require('../initializers/constants')
7 // ---------------------------------------------------------------------------
9 module
.exports = function (sequelize
, DataTypes
) {
10 const Request
= sequelize
.define('Request',
17 type: DataTypes
.ENUM(values(constants
.REQUEST_ENDPOINTS
)),
25 listWithLimitAndRandom
,
37 // ------------------------------ STATICS ------------------------------
39 function associate (models
) {
40 this.belongsToMany(models
.Pod
, {
45 through: models
.RequestToPod
,
50 function countTotalRequests (callback
) {
51 // We need to include Pod because there are no cascade delete when a pod is removed
52 // So we could count requests that do not have existing pod anymore
54 include: [ this.sequelize
.models
.Pod
]
57 return this.count(query
).asCallback(callback
)
60 function listWithLimitAndRandom (limitPods
, limitRequestsPerPod
, callback
) {
62 const Pod
= this.sequelize
.models
.Pod
64 Pod
.listRandomPodIdsWithRequest(limitPods
, 'RequestToPods', function (err
, podIds
) {
65 if (err
) return callback(err
)
67 // We don't have friends that have requests
68 if (podIds
.length
=== 0) return callback(null, [])
70 // The first x requests of these pods
71 // It is very important to sort by id ASC to keep the requests order!
78 model: self
.sequelize
.models
.Pod
,
88 self
.findAll(query
).asCallback(function (err
, requests
) {
89 if (err
) return callback(err
)
91 const requestsGrouped
= groupAndTruncateRequests(requests
, limitRequestsPerPod
)
92 return callback(err
, requestsGrouped
)
97 function removeAll (callback
) {
98 // Delete all requests
99 this.truncate({ cascade: true }).asCallback(callback
)
102 function removeWithEmptyTo (callback
) {
103 if (!callback
) callback = function () {}
109 this.sequelize
.literal('SELECT "requestId" FROM "RequestToPods"')
115 this.destroy(query
).asCallback(callback
)
118 // ---------------------------------------------------------------------------
120 function groupAndTruncateRequests (requests
, limitRequestsPerPod
) {
121 const requestsGrouped
= {}
123 requests
.forEach(function (request
) {
124 request
.Pods
.forEach(function (pod
) {
125 if (!requestsGrouped
[pod
.id
]) requestsGrouped
[pod
.id
] = []
127 if (requestsGrouped
[pod
.id
].length
< limitRequestsPerPod
) {
128 requestsGrouped
[pod
.id
].push({
136 return requestsGrouped