1 import { values } from 'lodash'
3 import { REQUEST_ENDPOINTS } from '../initializers'
5 // ---------------------------------------------------------------------------
7 module.exports = function (sequelize, DataTypes) {
8 const Request = sequelize.define('Request',
15 type: DataTypes.ENUM(values(REQUEST_ENDPOINTS)),
23 listWithLimitAndRandom,
35 // ------------------------------ STATICS ------------------------------
37 function associate (models) {
38 this.belongsToMany(models.Pod, {
43 through: models.RequestToPod,
48 function countTotalRequests (callback) {
49 // We need to include Pod because there are no cascade delete when a pod is removed
50 // So we could count requests that do not have existing pod anymore
52 include: [ this.sequelize.models.Pod ]
55 return this.count(query).asCallback(callback)
58 function listWithLimitAndRandom (limitPods, limitRequestsPerPod, callback) {
60 const Pod = this.sequelize.models.Pod
62 Pod.listRandomPodIdsWithRequest(limitPods, 'RequestToPods', function (err, podIds) {
63 if (err) return callback(err)
65 // We don't have friends that have requests
66 if (podIds.length === 0) return callback(null, [])
68 // The first x requests of these pods
69 // It is very important to sort by id ASC to keep the requests order!
76 model: self.sequelize.models.Pod,
86 self.findAll(query).asCallback(function (err, requests) {
87 if (err) return callback(err)
89 const requestsGrouped = groupAndTruncateRequests(requests, limitRequestsPerPod)
90 return callback(err, requestsGrouped)
95 function removeAll (callback) {
96 // Delete all requests
97 this.truncate({ cascade: true }).asCallback(callback)
100 function removeWithEmptyTo (callback) {
101 if (!callback) callback = function () { /* empty */ }
107 this.sequelize.literal('SELECT "requestId" FROM "RequestToPods"')
113 this.destroy(query).asCallback(callback)
116 // ---------------------------------------------------------------------------
118 function groupAndTruncateRequests (requests, limitRequestsPerPod) {
119 const requestsGrouped = {}
121 requests.forEach(function (request) {
122 request.Pods.forEach(function (pod) {
123 if (!requestsGrouped[pod.id]) requestsGrouped[pod.id] = []
125 if (requestsGrouped[pod.id].length < limitRequestsPerPod) {
126 requestsGrouped[pod.id].push({
134 return requestsGrouped