UNPKG

decentralized-internet

Version:

An NPM library of programs to create decentralized web and distributed computing projects

1 lines 2.47 kB
"use strict";const Hoek=require("hoek"),Any=require("./any"),Cast=require("./cast"),Ref=require("./ref"),internals={};internals.Alternatives=class extends Any{constructor(){super(),this._type="alternatives",this._invalids.remove(null),this._inner.matches=[]}_base(e,t,s){let r=[];const n=this._inner.matches.length,i=this._settings&&this._settings.baseType;for(let o=0;o<n;++o){const a=this._inner.matches[o],h=a.schema;if(!h){if(a.is._validate(a.ref(t.parent,s),null,s,t.parent).errors){if(a.otherwise)return a.otherwise._validate(e,t,s);if(i&&o===n-1)return i._validate(e,t,s)}else if(a.then||i)return(a.then||i)._validate(e,t,s);continue}const c=h._validate(e,t,s);if(!c.errors)return c;r=r.concat(c.errors)}return{errors:r.length?r:this.createError("alternatives.base",null,t,s)}}try(){const e=Hoek.flatten(Array.prototype.slice.call(arguments));Hoek.assert(e.length,"Cannot add other alternatives without at least one schema");const t=this.clone();for(let s=0;s<e.length;++s){const r=Cast.schema(e[s]);r._refs.length&&(t._refs=t._refs.concat(r._refs)),t._inner.matches.push({schema:r})}return t}when(e,t){Hoek.assert(Ref.isRef(e)||"string"==typeof e,"Invalid reference:",e),Hoek.assert(t,"Missing options"),Hoek.assert("object"==typeof t,"Invalid options"),Hoek.assert(t.hasOwnProperty("is"),'Missing "is" directive'),Hoek.assert(void 0!==t.then||void 0!==t.otherwise,'options must have at least one of "then" or "otherwise"');const s=this.clone();let r=Cast.schema(t.is);null!==t.is&&(Ref.isRef(t.is)||t.is instanceof Any)||(r=r.required());const n={ref:Cast.ref(e),is:r,then:void 0!==t.then?Cast.schema(t.then):void 0,otherwise:void 0!==t.otherwise?Cast.schema(t.otherwise):void 0};return s._settings&&s._settings.baseType&&(n.then=n.then&&s._settings.baseType.concat(n.then),n.otherwise=n.otherwise&&s._settings.baseType.concat(n.otherwise)),Ref.push(s._refs,n.ref),s._refs=s._refs.concat(n.is._refs),n.then&&n.then._refs&&(s._refs=s._refs.concat(n.then._refs)),n.otherwise&&n.otherwise._refs&&(s._refs=s._refs.concat(n.otherwise._refs)),s._inner.matches.push(n),s}describe(){const e=Any.prototype.describe.call(this),t=[];for(let e=0;e<this._inner.matches.length;++e){const s=this._inner.matches[e];if(s.schema)t.push(s.schema.describe());else{const e={ref:s.ref.toString(),is:s.is.describe()};s.then&&(e.then=s.then.describe()),s.otherwise&&(e.otherwise=s.otherwise.describe()),t.push(e)}}return e.alternatives=t,e}},module.exports=new internals.Alternatives;