2020-10-13 11:55:24 +00:00
|
|
|
const findIndex = require('lodash/findIndex');
|
|
|
|
const Joi = require('joi');
|
|
|
|
Joi.objectId = require('joi-objectid')(Joi);
|
|
|
|
|
|
|
|
const schema = Joi.objectId();
|
2018-01-19 19:03:17 +00:00
|
|
|
|
|
|
|
class MongoIds {
|
|
|
|
constructor() {
|
|
|
|
this.knownIds = [];
|
|
|
|
}
|
|
|
|
check(id, title) {
|
2020-10-13 11:55:24 +00:00
|
|
|
try {
|
|
|
|
Joi.validate(id, schema);
|
|
|
|
} catch {
|
2018-01-19 19:03:17 +00:00
|
|
|
throw new Error(`Expected a valid ObjectId for ${title}, but got ${id}`);
|
|
|
|
}
|
2020-10-13 11:55:24 +00:00
|
|
|
|
|
|
|
const idIndex = findIndex(this.knownIds, existing => id === existing);
|
2018-01-19 19:03:17 +00: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 19:03:17 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-10-23 13:21:53 +00:00
|
|
|
module.exports = MongoIds;
|