1 | const _ = require('lodash');
|
2 | const Promise = require('bluebird');
|
3 | const inspector = require('./inspector');
|
4 |
|
5 | const SANITIZATION_SCHEMA = {
|
6 | properties: {
|
7 | namespace: {
|
8 | def: 'global',
|
9 | optional: false
|
10 | },
|
11 | id: {
|
12 | optional: false
|
13 | }
|
14 | }
|
15 | };
|
16 |
|
17 | const 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 |
|
33 | const 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 | };
|
58 | ObjectId.ID_REGEX = /^[a-zA-Z][a-zA-Z0-9]{1,40}$/;
|
59 | ObjectId.coerce = (id) => id instanceof ObjectId ? id : new ObjectId(id);
|
60 |
|
61 | module.exports = ObjectId;
|