1 import { values } from 'lodash'
2 import * as Sequelize from 'sequelize'
4 import { database as db } from '../../initializers/database'
5 import { REQUEST_ENDPOINTS } from '../../initializers'
6 import { addMethodsToModel } from '../utils'
13 } from './request-interface'
15 let Request: Sequelize.Model<RequestInstance, RequestAttributes>
16 let countTotalRequests: RequestMethods.CountTotalRequests
17 let listWithLimitAndRandom: RequestMethods.ListWithLimitAndRandom
18 let removeWithEmptyTo: RequestMethods.RemoveWithEmptyTo
19 let removeAll: RequestMethods.RemoveAll
21 export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.DataTypes) {
22 Request = sequelize.define<RequestInstance, RequestAttributes>('Request',
29 type: DataTypes.ENUM(values(REQUEST_ENDPOINTS)),
35 const classMethods = [
38 listWithLimitAndRandom,
44 addMethodsToModel(Request, classMethods)
49 // ------------------------------ STATICS ------------------------------
51 function associate (models) {
52 Request.belongsToMany(models.Pod, {
57 through: models.RequestToPod,
62 countTotalRequests = function () {
63 // We need to include Pod because there are no cascade delete when a pod is removed
64 // So we could count requests that do not have existing pod anymore
66 include: [ Request['sequelize'].models.Pod ]
69 return Request.count(query)
72 listWithLimitAndRandom = function (limitPods: number, limitRequestsPerPod: number) {
76 return Pod.listRandomPodIdsWithRequest(limitPods, 'RequestToPods', tableJoin).then(podIds => {
77 // We don't have friends that have requests
78 if (podIds.length === 0) return []
80 // The first x requests of these pods
81 // It is very important to sort by id ASC to keep the requests order!
88 model: Request['sequelize'].models.Pod,
98 return Request.findAll(query).then(requests => {
100 const requestsGrouped = groupAndTruncateRequests(requests, limitRequestsPerPod)
101 return requestsGrouped
106 removeAll = function () {
107 // Delete all requests
108 return Request.truncate({ cascade: true })
111 removeWithEmptyTo = function () {
116 Sequelize.literal('SELECT "requestId" FROM "RequestToPods"')
122 return Request.destroy(query)
125 // ---------------------------------------------------------------------------
127 function groupAndTruncateRequests (requests: RequestInstance[], limitRequestsPerPod: number) {
128 const requestsGrouped: RequestsGrouped = {}
130 requests.forEach(request => {
131 request.Pods.forEach(pod => {
132 if (!requestsGrouped[pod.id]) requestsGrouped[pod.id] = []
134 if (requestsGrouped[pod.id].length < limitRequestsPerPod) {
135 requestsGrouped[pod.id].push({
143 return requestsGrouped