2020-10-13 13:55:24 +02:00
|
|
|
const findIndex = require('lodash/findIndex');
|
|
|
|
const Joi = require('joi');
|
|
|
|
Joi.objectId = require('joi-objectid')(Joi);
|
|
|
|
|
|
|
|
const schema = Joi.objectId();
|
2018-01-19 14:03:17 -05:00
|
|
|
|
|
|
|
class MongoIds {
|
|
|
|
constructor() {
|
|
|
|
this.knownIds = [];
|
|
|
|
}
|
|
|
|
check(id, title) {
|
2020-10-13 13:55:24 +02:00
|
|
|
try {
|
|
|
|
Joi.validate(id, schema);
|
|
|
|
} catch {
|
2018-01-19 14:03:17 -05:00
|
|
|
throw new Error(`Expected a valid ObjectId for ${title}, but got ${id}`);
|
|
|
|
}
|
2020-10-13 13:55:24 +02:00
|
|
|
|
|
|
|
const idIndex = findIndex(this.knownIds, existing => id === existing);
|
2018-01-19 14:03:17 -05:00
|
|
|
if (idIndex !== -1) {
|
|
|
|
throw new Error(`
|
|
|
|
All challenges must have a unique id.
|
|
|
|
|
|
|
|
The id for ${title} is already assigned
|
|
|
|
`);
|
|
|
|
}
|
2019-02-18 19:32:49 +00:00
|
|
|
this.knownIds = [...this.knownIds, id];
|
2018-01-19 14:03:17 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-10-23 16:21:53 +03:00
|
|
|
module.exports = MongoIds;
|