UNPKG

1.47 kBJavaScriptView Raw
1const _ = require('lodash');
2const Promise = require('bluebird');
3const inspector = require('./inspector');
4
5const SANITIZATION_SCHEMA = {
6 properties: {
7 namespace: {
8 def: 'global',
9 optional: false
10 },
11 id: {
12 optional: false
13 }
14 }
15};
16
17const VALIDATION_SCHEMA = {
18 type: 'object',
19 strict: true,
20 properties: {
21 namespace: {
22 type: 'string',
23 def: 'global',
24 optional: false
25 },
26 id: {
27 type: 'string',
28 optional: false
29 }
30 }
31};
32
33const ObjectId = function (params) {
34 const self = this;
35 const validateId = (id) => _.isString(id) && ObjectId.ID_REGEX.test(id);
36
37 inspector.sanitize(SANITIZATION_SCHEMA, params);
38 const result = inspector.validate(VALIDATION_SCHEMA, params);
39
40 if (!result.valid) {
41 throw new Error(result.format());
42 }
43 _.merge(self, params);
44
45 self.validate = (name) => new Promise((resolve, reject) => {
46 name = name || 'Id';
47
48 if (!validateId(self.namespace)) {
49 reject(new Error(`Namespace must be string of 1-40 alphanumeric characters, given '${self.namespace}'`));
50 }
51 if (!validateId(self.id)) {
52 reject(new Error(`${name} must be string of 1-40 alphanumeric characters, given '${self.id}'`));
53 }
54 resolve(self);
55 });
56 return self;
57};
58ObjectId.ID_REGEX = /^[a-zA-Z][a-zA-Z0-9]{1,40}$/;
59ObjectId.coerce = (id) => id instanceof ObjectId ? id : new ObjectId(id);
60
61module.exports = ObjectId;