]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/models/pods.js
Server: reorganize express validators
[github/Chocobozzz/PeerTube.git] / server / models / pods.js
1 'use strict'
2
3 const mongoose = require('mongoose')
4 const map = require('lodash/map')
5 const validator = require('express-validator').validator
6
7 const constants = require('../initializers/constants')
8
9 // ---------------------------------------------------------------------------
10
11 const PodSchema = mongoose.Schema({
12 url: String,
13 publicKey: String,
14 score: { type: Number, max: constants.FRIEND_SCORE.MAX }
15 })
16
17 // TODO: set options (TLD...)
18 PodSchema.path('url').validate(validator.isURL)
19 PodSchema.path('publicKey').required(true)
20 PodSchema.path('score').validate(function (value) { return !isNaN(value) })
21
22 PodSchema.statics = {
23 countAll: countAll,
24 incrementScores: incrementScores,
25 list: list,
26 listAllIds: listAllIds,
27 listOnlyUrls: listOnlyUrls,
28 listBadPods: listBadPods,
29 load: load,
30 loadByUrl: loadByUrl,
31 removeAll: removeAll
32 }
33
34 PodSchema.pre('save', function (next) {
35 const self = this
36
37 Pod.loadByUrl(this.url, function (err, pod) {
38 if (err) return next(err)
39
40 if (pod) return next(new Error('Pod already exists.'))
41
42 self.score = constants.FRIEND_SCORE.BASE
43 return next()
44 })
45 })
46
47 const Pod = mongoose.model('Pod', PodSchema)
48
49 // ------------------------------ Statics ------------------------------
50
51 function countAll (callback) {
52 return this.count(callback)
53 }
54
55 function incrementScores (ids, value, callback) {
56 if (!callback) callback = function () {}
57 return this.update({ _id: { $in: ids } }, { $inc: { score: value } }, { multi: true }, callback)
58 }
59
60 function list (callback) {
61 return this.find(callback)
62 }
63
64 function listAllIds (callback) {
65 return this.find({}, { _id: 1 }, function (err, pods) {
66 if (err) return callback(err)
67
68 return callback(null, map(pods, '_id'))
69 })
70 }
71
72 function listOnlyUrls (callback) {
73 return this.find({}, { _id: 0, url: 1 }, callback)
74 }
75
76 function listBadPods (callback) {
77 return this.find({ score: 0 }, callback)
78 }
79
80 function load (id, callback) {
81 return this.findById(id, callback)
82 }
83
84 function loadByUrl (url, callback) {
85 return this.findOne({ url: url }, callback)
86 }
87
88 function removeAll (callback) {
89 return this.remove({}, callback)
90 }