PeerTube/server/models/pods.js

91 lines
2.1 KiB
JavaScript
Raw Normal View History

'use strict'
2016-03-16 22:29:27 +01:00
const mongoose = require('mongoose')
const map = require('lodash/map')
const validator = require('express-validator').validator
2016-03-16 22:29:27 +01:00
const constants = require('../initializers/constants')
// ---------------------------------------------------------------------------
const PodSchema = mongoose.Schema({
url: String,
publicKey: String,
score: { type: Number, max: constants.FRIEND_SCORE.MAX }
})
// TODO: set options (TLD...)
PodSchema.path('url').validate(validator.isURL)
PodSchema.path('publicKey').required(true)
PodSchema.path('score').validate(function (value) { return !isNaN(value) })
PodSchema.statics = {
countAll: countAll,
incrementScores: incrementScores,
list: list,
listAllIds: listAllIds,
listOnlyUrls: listOnlyUrls,
listBadPods: listBadPods,
load: load,
loadByUrl: loadByUrl,
removeAll: removeAll
}
PodSchema.pre('save', function (next) {
const self = this
2015-06-09 17:41:40 +02:00
Pod.loadByUrl(this.url, function (err, pod) {
if (err) return next(err)
if (pod) return next(new Error('Pod already exists.'))
2015-06-09 17:41:40 +02:00
self.score = constants.FRIEND_SCORE.BASE
return next()
})
})
const Pod = mongoose.model('Pod', PodSchema)
// ------------------------------ Statics ------------------------------
function countAll (callback) {
return this.count(callback)
}
function incrementScores (ids, value, callback) {
if (!callback) callback = function () {}
return this.update({ _id: { $in: ids } }, { $inc: { score: value } }, { multi: true }, callback)
}
function list (callback) {
return this.find(callback)
}
2015-06-09 17:41:40 +02:00
function listAllIds (callback) {
return this.find({}, { _id: 1 }, function (err, pods) {
if (err) return callback(err)
return callback(null, map(pods, '_id'))
})
}
function listOnlyUrls (callback) {
return this.find({}, { _id: 0, url: 1 }, callback)
}
function listBadPods (callback) {
return this.find({ score: 0 }, callback)
}
2015-06-09 17:41:40 +02:00
function load (id, callback) {
return this.findById(id, callback)
}
2016-01-31 11:23:52 +01:00
function loadByUrl (url, callback) {
return this.findOne({ url: url }, callback)
}
2016-01-31 11:23:52 +01:00
function removeAll (callback) {
return this.remove({}, callback)
}