31 lines
		
	
	
		
			679 B
		
	
	
	
		
			JavaScript
		
	
	
	
	
	
			
		
		
	
	
			31 lines
		
	
	
		
			679 B
		
	
	
	
		
			JavaScript
		
	
	
	
	
	
const findIndex = require('lodash/findIndex');
 | 
						|
const Joi = require('joi');
 | 
						|
Joi.objectId = require('joi-objectid')(Joi);
 | 
						|
 | 
						|
const schema = Joi.objectId();
 | 
						|
 | 
						|
class MongoIds {
 | 
						|
  constructor() {
 | 
						|
    this.knownIds = [];
 | 
						|
  }
 | 
						|
  check(id, title) {
 | 
						|
    try {
 | 
						|
      schema.validate(id);
 | 
						|
    } catch {
 | 
						|
      throw new Error(`Expected a valid ObjectId for ${title}, but got ${id}`);
 | 
						|
    }
 | 
						|
 | 
						|
    const idIndex = findIndex(this.knownIds, existing => id === existing);
 | 
						|
    if (idIndex !== -1) {
 | 
						|
      throw new Error(`
 | 
						|
    All challenges must have a unique id.
 | 
						|
 | 
						|
    The id for ${title} is already assigned
 | 
						|
    `);
 | 
						|
    }
 | 
						|
    this.knownIds = [...this.knownIds, id];
 | 
						|
  }
 | 
						|
}
 | 
						|
 | 
						|
module.exports = MongoIds;
 |