addon-sdk/source/lib/sdk/util/contract.js

Wed, 31 Dec 2014 06:09:35 +0100

author
Michael Schloh von Bennewitz <michael@schloh.com>
date
Wed, 31 Dec 2014 06:09:35 +0100
changeset 0
6474c204b198
permissions
-rw-r--r--

Cloned upstream origin tor-browser at tor-browser-31.3.0esr-4.5-1-build1
revision ID fc1c9ff7c1b2defdbc039f12214767608f46423f for hacking purpose.

michael@0 1 /* This Source Code Form is subject to the terms of the Mozilla Public
michael@0 2 * License, v. 2.0. If a copy of the MPL was not distributed with this
michael@0 3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
michael@0 4
michael@0 5 "use strict";
michael@0 6
michael@0 7 module.metadata = {
michael@0 8 "stability": "unstable"
michael@0 9 };
michael@0 10
michael@0 11 const { validateOptions: valid } = require("../deprecated/api-utils");
michael@0 12
michael@0 13 // Function takes property validation rules and returns function that given
michael@0 14 // an `options` object will return validated / normalized options back. If
michael@0 15 // option(s) are invalid validator will throw exception described by rules.
michael@0 16 // Returned will also have contain `rules` property with a given validation
michael@0 17 // rules and `properties` function that can be used to generate validated
michael@0 18 // property getter and setters can be mixed into prototype. For more details
michael@0 19 // see `properties` function below.
michael@0 20 function contract(rules) {
michael@0 21 function validator(options) {
michael@0 22 return valid(options || {}, rules);
michael@0 23 }
michael@0 24 validator.rules = rules
michael@0 25 validator.properties = function(modelFor) {
michael@0 26 return properties(modelFor, rules);
michael@0 27 }
michael@0 28 return validator;
michael@0 29 }
michael@0 30 exports.contract = contract
michael@0 31
michael@0 32 // Function takes `modelFor` instance state model accessor functions and
michael@0 33 // a property validation rules and generates object with getters and setters
michael@0 34 // that can be mixed into prototype. Property accessors update model for the
michael@0 35 // given instance. If you wish to react to property updates you can always
michael@0 36 // override setters to put specific logic.
michael@0 37 function properties(modelFor, rules) {
michael@0 38 let descriptor = Object.keys(rules).reduce(function(descriptor, name) {
michael@0 39 descriptor[name] = {
michael@0 40 get: function() { return modelFor(this)[name] },
michael@0 41 set: function(value) {
michael@0 42 let change = {};
michael@0 43 change[name] = value;
michael@0 44 modelFor(this)[name] = valid(change, rules)[name];
michael@0 45 }
michael@0 46 }
michael@0 47 return descriptor
michael@0 48 }, {});
michael@0 49 return Object.create(Object.prototype, descriptor);
michael@0 50 }
michael@0 51 exports.properties = properties

mercurial