diff --git a/Gruntfile.js b/Gruntfile.js index 4289610..539873e 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -1,47 +1,43 @@ -'use strict'; +'use strict' -module.exports = function(grunt) { - - var mountFolder = function(connect, dir) { - return serveStatic(dir); - }; +module.exports = function (grunt) { + var mountFolder = function (connect, dir) { + return serveStatic(dir) + } - var path = require('path'); - var serveStatic = require('serve-static'); + var path = require('path') + var serveStatic = require('serve-static') - require('load-grunt-tasks')(grunt); + require('load-grunt-tasks')(grunt) var ports = { server: 9000, test: 8000, livereload: 35729, express: 3000 - }; - - function jsdocTask() { - var exec = require('child_process').exec; - /* jshint validthis:true */ - var done = this.async(); + } - var jsdocCmd = './node_modules/jsdoc/jsdoc'; + function jsdocTask () { + var exec = require('child_process').exec + var done = this.async() - var src = ' -r src'; - var dest = ' -d doc'; - var config = ' -c .jsdoc'; - var template = ' -t node_modules/jaguarjs-jsdoc'; + var jsdocCmd = './node_modules/jsdoc/jsdoc' - exec(jsdocCmd + src + dest + config + template, function(err, stdout, stderr) { - console.log(stdout); - console.log(stderr); - done(err === null); - }); + var src = ' -r src' + var dest = ' -d doc' + var config = ' -c .jsdoc' + var template = ' -t node_modules/jaguarjs-jsdoc' + exec(jsdocCmd + src + dest + config + template, function (err, stdout, stderr) { + console.log(stdout) + console.log(stderr) + done(err === null) + }) } - grunt.registerTask('jsdoc', 'Generates JSDoc', jsdocTask); + grunt.registerTask('jsdoc', 'Generates JSDoc', jsdocTask) grunt.initConfig({ - pkg: grunt.file.readJSON('./package.json'), clean: { @@ -59,7 +55,7 @@ module.exports = function(grunt) { }, 'test-browser': { src: ['test/browser/index.html'], - dest: '.tmp/', + dest: '.tmp/' } }, @@ -75,19 +71,6 @@ module.exports = function(grunt) { } }, - jshint: { - options: { - jshintrc: '.jshintrc', - reporter: require('jshint-stylish') - }, - all: [ - 'Gruntfile.js', - 'src/{,**/}*.js', - '!src/cryptography.js', // vendor @todo remove or clean this dep - 'test/{,**/}*.js', - 'examples/{,**/}*.js' - ] - }, execute: { nodeapp: { src: ['examples/nodeapp/main.js'] @@ -119,7 +102,7 @@ module.exports = function(grunt) { serve: { singleRun: false, browsers: [ - 'Chrome' + 'Chrome' ] } }, @@ -144,42 +127,62 @@ module.exports = function(grunt) { webserver: { options: { port: ports.server, - middleware: function(connect) { + middleware: function (connect) { return [ mountFolder(connect, 'examples/webapp/'), mountFolder(connect, 'dist/'), mountFolder(connect, 'bower_components/'), mountFolder(connect, 'vendor/') - ]; - }, + ] + } } }, 'test_webserver': { options: { port: ports.test, - middleware: function(connect) { + middleware: function (connect) { return [ mountFolder(connect, '.tmp/test/browser/'), mountFolder(connect, 'dist/'), mountFolder(connect, 'bower_components/'), mountFolder(connect, 'vendor/') - ]; - }, + ] + } } }, 'jsdoc_webserver': { options: { port: ports.test, - middleware: function(connect) { + middleware: function (connect) { return [ mountFolder(connect, 'doc/') - ]; - }, + ] + } } } }, + + standard: { + lint: { + src: [ + './{src,test}/**/*.js', + '*.js' + ] + }, + format: { + options: { + format: true, + lint: true + }, + src: [ + './{src,test}/**/*.js', + '*.js' + ] + } + }, + watch: { options: { nospawn: true, @@ -228,10 +231,10 @@ module.exports = function(grunt) { }, load: {} }, - mochaTest: { //test for nodejs app with mocha + mochaTest: { // test for nodejs app with mocha testCoverage: { options: { - reporter: 'spec', + reporter: 'spec' }, src: ['.tmp/coverage/test/node/test-suite.js'] }, @@ -268,11 +271,11 @@ module.exports = function(grunt) { ci: { src: ['test/node/test-suite.js'] } - }, //test for browser app with mocha and phanthom + }, // test for browser app with mocha and phanthom 'mocha_phantomjs': { options: { urls: [ - 'http://localhost:' + ports.test /*<%= connect.options.port %>*/ + 'http://localhost:' + ports.test /* <%= connect.options.port %>*/ ], setting: [ 'webSecurityEnabled=false', @@ -342,9 +345,9 @@ module.exports = function(grunt) { /* For more options: https://github.com/geddski/grunt-release#options */ options: { additionalFiles: ['bower.json'], - indentation: '\t', //default: ' ' (two spaces) - commitMessage: 'Release v<%= version %>', //default: 'release <%= version %>' - tagMessage: 'v<%= version %>', //default: 'Version <%= version %>', + indentation: '\t', // default: ' ' (two spaces) + commitMessage: 'Release v<%= version %>', // default: 'release <%= version %>' + tagMessage: 'v<%= version %>', // default: 'Version <%= version %>', tagName: 'v<%= version %>' } }, @@ -356,7 +359,7 @@ module.exports = function(grunt) { } } - }); + }) grunt.registerTask('serve:webapp', [ 'build', @@ -365,7 +368,7 @@ module.exports = function(grunt) { 'connect:webserver', 'open:webapp', 'watch:webapp' - ]); + ]) grunt.registerTask('serve:webapp:debug', [ 'build', @@ -373,71 +376,75 @@ module.exports = function(grunt) { 'connect:webserver', 'open:webapp', 'watch:webapp' - ]); + ]) grunt.registerTask('serve:nodeapp', [ 'express:load', 'execute:nodeapp', 'watch:nodeapp' - ]); + ]) grunt.registerTask('test', [ 'test:browser', 'mochaTest:ci' - ]); + ]) grunt.registerTask('test:browser', [ + 'standard:format', 'build', + 'standard:lint', 'copy:test-browser', 'preprocess:test-browser', 'express:load', 'connect:test_webserver', 'karma:unit' - ]); + ]) grunt.registerTask('test:node', [ + 'standard:format', 'build', + 'standard:lint', 'express:load', 'mochaTest:ci' - ]); //'mochaTest:tap', 'lineremover:tap' + ]) // 'mochaTest:tap', 'lineremover:tap' grunt.registerTask('test:browser:reload', [ 'copy:test-browser', 'preprocess:test-browser', 'express:load', 'mocha_phantomjs:ci' - ]); //mocha_phantomjs:tap, 'lineremover:tap' + ]) // mocha_phantomjs:tap, 'lineremover:tap' grunt.registerTask('test:node:reload', [ 'express:load', 'mocha_phantomjs:ci' - ]); //mocha_phantomjs:tap, 'lineremover:tap' + ]) // mocha_phantomjs:tap, 'lineremover:tap' grunt.registerTask('serve:test', [ + 'standard:format', 'build', 'copy:test-browser', 'preprocess:test-browser', 'express:load', 'karma:serve', 'watch:test' - ]); + ]) grunt.registerTask('serve:test:node', [ 'test:node', 'open:test', 'watch:test-node' - ]); + ]) grunt.registerTask('test:tap', [ 'test:browser', 'mocha_phantomjs:tap', 'mochaTest:tap' - // 'lineremover:tap' - ]); + // 'lineremover:tap' + ]) grunt.registerTask('coverage:node', [ 'clean', - 'jshint', 'build', 'blanket', 'copy:coverage', @@ -446,7 +453,7 @@ module.exports = function(grunt) { 'mochaTest:coverage', 'mochaTest:coveralls', 'mochaTest:travis-cov' - ]); + ]) grunt.registerTask('serve:jsdoc', [ 'clean', @@ -454,12 +461,11 @@ module.exports = function(grunt) { 'connect:jsdoc_webserver', 'open:test', 'watch:jsdoc' - ]); - - grunt.registerTask('build', ['versioncheck', 'preprocess:default', 'preprocess:polyfills', 'jsbeautifier']); + ]) - grunt.registerTask('dist', ['jshint', 'test']); + grunt.registerTask('build', ['versioncheck', 'preprocess:default', 'preprocess:polyfills', 'jsbeautifier']) - grunt.registerTask('default', ['dist']); + grunt.registerTask('dist', ['test']) -}; + grunt.registerTask('default', ['dist']) +} diff --git a/README.md b/README.md index aaa6bad..5eb862b 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,10 @@ corbel-js [![Test Coverage](https://codeclimate.com/github/bq/corbel-js/badges/coverage.svg)](https://codeclimate.com/github/bq/corbel-js/coverage) [![Codacy Badge](https://api.codacy.com/project/badge/grade/295a5a767259422b955c4c8f28158d05)](https://www.codacy.com/app/antai-pt/corbel-js) + +[![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) + + A SDK for [corbel][corbel-url] compatible with browsers and node. ## [Homepage](http://opensource.bq.com/corbel-js/) diff --git a/dist/corbel.js b/dist/corbel.js index 4597bce..f8c30fa 100644 --- a/dist/corbel.js +++ b/dist/corbel.js @@ -1,19 +1,20 @@ +; (function(root, factory) { - 'use strict'; + 'use strict' /* jshint unused: false */ + /* global define */ if (typeof define === 'function' && define.amd) { define([], function() { - return factory(root); - }); + return factory(root) + }) } else if (typeof module !== 'undefined' && module.exports) { - module.exports = factory.call(root, root, process || undefined); + module.exports = factory.call(root, root, process || undefined) } else if (root !== undefined) { - root.corbel = factory(root); + root.corbel = factory(root) } - })(this, function(root, process) { - 'use strict'; + 'use strict' /* jshint unused: false */ /** @@ -21,13 +22,14 @@ * @exports corbel * @namespace */ - var corbel = {}; + var corbel = {} - //-----------Utils and libraries (exports into corbel namespace)--------------------------- + // -----------Utils and libraries (exports into corbel namespace)--------------------------- + /* global corbel */ + ; (function() { - /** * @namespace * @memberOf corbel @@ -35,37 +37,36 @@ * @return {CorbelDriver} */ function CorbelDriver(config, events) { - if (events && typeof events === 'object') { - this._events = corbel.utils.clone(events); + this._events = corbel.utils.clone(events) } else { - this._events = {}; + this._events = {} } // create instance config - this.guid = corbel.utils.guid(); - this.config = corbel.Config.create(config); + this.guid = corbel.utils.guid() + this.config = corbel.Config.create(config) // create isntance modules with injected driver - this.iam = corbel.Iam.create(this); - this.resources = corbel.Resources.create(this); - this.assets = corbel.Assets.create(this); - this.oauth = corbel.Oauth.create(this); - this.notifications = corbel.Notifications.create(this); - this.ec = corbel.Ec.create(this); - this.evci = corbel.Evci.create(this); - this.borrow = corbel.Borrow.create(this); - this.composr = corbel.CompoSR.create(this); - this.scheduler = corbel.Scheduler.create(this); - this.webfs = corbel.Webfs.create(this); - this.domain = corbel.Domain.create(this); + this.iam = corbel.Iam.create(this) + this.resources = corbel.Resources.create(this) + this.assets = corbel.Assets.create(this) + this.oauth = corbel.Oauth.create(this) + this.notifications = corbel.Notifications.create(this) + this.ec = corbel.Ec.create(this) + this.evci = corbel.Evci.create(this) + this.borrow = corbel.Borrow.create(this) + this.composr = corbel.CompoSR.create(this) + this.scheduler = corbel.Scheduler.create(this) + this.webfs = corbel.Webfs.create(this) + this.domain = corbel.Domain.create(this) } /** * @return {CorbelDriver} A new instance of corbel driver with the same config */ CorbelDriver.prototype.clone = function() { - return new CorbelDriver(this.config.getConfig(), this._events); - }; + return new CorbelDriver(this.config.getConfig(), this._events) + } /** * Adds an event handler for especific event @@ -74,13 +75,13 @@ */ CorbelDriver.prototype.addEventListener = function(name, fn) { if (typeof fn !== 'function') { - throw new Error('corbel:error:invalid:type'); + throw new Error('corbel:error:invalid:type') } - this._events[name] = this._events[name] || []; + this._events[name] = this._events[name] || [] if (this._events[name].indexOf(fn) === -1) { - this._events[name].push(fn); + this._events[name].push(fn) } - }; + } /** * Removes the handler from event list @@ -89,12 +90,12 @@ */ CorbelDriver.prototype.removeEventListener = function(name, fn) { if (this._events[name]) { - var index = this._events[name].indexOf(fn); + var index = this._events[name].indexOf(fn) if (index !== -1) { - this._events[name].splice(index, 1); + this._events[name].splice(index, 1) } } - }; + } /** * Fires all events handlers for an specific event name @@ -104,10 +105,10 @@ CorbelDriver.prototype.dispatch = function(name, options) { if (this._events[name] && this._events[name].length) { this._events[name].forEach(function(fn) { - fn(options); - }); + fn(options) + }) } - }; + } /** * Adds an event handler for especific event @@ -115,7 +116,7 @@ * @param {string} name Event name * @param {Function} fn Function to call */ - CorbelDriver.prototype.on = CorbelDriver.prototype.addEventListener; + CorbelDriver.prototype.on = CorbelDriver.prototype.addEventListener /** * Removes the handler from event list @@ -123,7 +124,7 @@ * @param {string} name Event name * @param {Function} fn Function to remove */ - CorbelDriver.prototype.off = CorbelDriver.prototype.removeEventListener; + CorbelDriver.prototype.off = CorbelDriver.prototype.removeEventListener /** * Fires all events handlers for an specific event name @@ -131,9 +132,9 @@ * @param {string} name Event name * @param {Mixed} options Data for event handlers */ - CorbelDriver.prototype.trigger = CorbelDriver.prototype.dispatch; + CorbelDriver.prototype.trigger = CorbelDriver.prototype.dispatch - corbel.CorbelDriver = CorbelDriver; + corbel.CorbelDriver = CorbelDriver /** * Instanciates new corbel driver @@ -146,28 +147,28 @@ * @return {corbel.CorbelDriver} */ corbel.getDriver = function(config) { - config = config || {}; + config = config || {} if (!config.urlBase) { - throw new Error('error:undefined:urlbase'); + throw new Error('error:undefined:urlbase') } - return new CorbelDriver(config); - }; - - })(); + return new CorbelDriver(config) + } + })() + /*globals corbel */ + ; (function() { - /** * A module to some library corbel.utils * @exports utils * @namespace * @memberof corbel */ - var utils = corbel.utils = {}; + var utils = corbel.utils = {} /** * Extend a given object with all the properties in passed-in object(s). @@ -175,17 +176,16 @@ * @return {Object} */ utils.extend = function(obj) { - Array.prototype.slice.call(arguments, 1).forEach(function(source) { if (source) { for (var prop in source) { - obj[prop] = source[prop]; + obj[prop] = source[prop] } } - }); + }) - return obj; - }; + return obj + } /** * Set up the prototype chain, for subclasses. Uses a hash of prototype properties and class properties to be extended. @@ -194,61 +194,57 @@ * @return {Object} Return a new object that inherit from the context object */ utils.inherit = function(prototypeProperties, staticProperties) { - var parent = this, - child; - + var parent = this + var child if (prototypeProperties && prototypeProperties.hasOwnProperty('constructor')) { - child = prototypeProperties.constructor; + child = prototypeProperties.constructor } else { child = function() { - return parent.apply(this, arguments); - }; + return parent.apply(this, arguments) + } } - utils.extend(child, parent, staticProperties); + utils.extend(child, parent, staticProperties) var Surrogate = function() { - this.constructor = child; - }; + this.constructor = child + } - Surrogate.prototype = parent.prototype; - child.prototype = new Surrogate; // jshint ignore:line + Surrogate.prototype = parent.prototype + child.prototype = new Surrogate() if (prototypeProperties) { - utils.extend(child.prototype, prototypeProperties); + utils.extend(child.prototype, prototypeProperties) } - child.__super__ = parent.prototype; - - return child; - - }; + child.__super__ = parent.prototype + return child + } /** * Generate a uniq random GUID */ utils.guid = function() { - function s4() { return Math.floor((1 + Math.random()) * 0x10000) .toString(16) - .substring(1); + .substring(1) } return s4() + s4() + '-' + s4() + '-' + s4() + '-' + - s4() + '-' + s4() + s4() + s4(); - }; + s4() + '-' + s4() + s4() + s4() + } /** * Reload browser */ utils.reload = function() { if (window !== undefined) { - window.location.reload(); + window.location.reload() } - }; + } /** * Serialize a plain object to query string @@ -256,25 +252,24 @@ * @return {String} */ utils.param = function(obj) { - var str = []; + var str = [] for (var p in obj) { if (obj.hasOwnProperty(p)) { - str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p])); + str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p])) } } - return str.join('&'); - }; - + return str.join('&') + } utils.toURLEncoded = function(obj) { - var str = []; + var str = [] for (var p in obj) { if (obj.hasOwnProperty(p)) { - str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p])); + str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p])) } } - return str.join('&'); - }; + return str.join('&') + } /** * Translate this full exampe query to a Corbel Compliant QueryString @@ -341,175 +336,175 @@ * aggregation: { * '$count': '*' * } - * }; + * } */ utils.serializeParams = function(params) { - var result = ''; + var result = '' if (params === undefined || params === null) { - return result; + return result } if (!(params instanceof Object) && (typeof params !== 'object')) { - throw new Error('expected params to be an Object type, but got ' + typeof params); + throw new Error('expected params to be an Object type, but got ' + typeof params) } function getJsonEncodedStringify(param) { - return encodeURIComponent(JSON.stringify(param)); + return encodeURIComponent(JSON.stringify(param)) } if (params.aggregation) { - result = 'api:aggregation=' + getJsonEncodedStringify(params.aggregation); + result = 'api:aggregation=' + getJsonEncodedStringify(params.aggregation) } function queryObjectToString(params, key) { - var result = ''; - var query; - params.queryDomain = params.queryDomain || 'api'; - result += params.queryDomain + ':' + key + '='; + var result = '' + var query + params.queryDomain = params.queryDomain || 'api' + result += params.queryDomain + ':' + key + '=' try { if (typeof params[key] === 'string') { - query = JSON.parse(params[key]); + query = JSON.parse(params[key]) } else { - //Clone the object we don't want to modify the original query object - query = JSON.parse(JSON.stringify(params[key])); + // Clone the object we don't want to modify the original query object + query = JSON.parse(JSON.stringify(params[key])) } - result += getJsonEncodedStringify(query); + result += getJsonEncodedStringify(query) - return result; + return result } catch (e) { - //Return the query even if it is not a valid object - return result + params[key]; + // Return the query even if it is not a valid object + return result + params[key] } } if (params.query) { - params.queryDomain = params.queryDomain || 'api'; - result += result ? '&' : ''; - result += queryObjectToString(params, 'query'); + params.queryDomain = params.queryDomain || 'api' + result += result ? '&' : '' + result += queryObjectToString(params, 'query') } if (params.queries) { params.queries.forEach(function(query) { - result += result ? '&' : ''; - result += queryObjectToString(query, 'query'); - }); + result += result ? '&' : '' + result += queryObjectToString(query, 'query') + }) } if (params.condition) { - params.queryDomain = params.queryDomain || 'api'; - result += result ? '&' : ''; - result += queryObjectToString(params, 'condition'); + params.queryDomain = params.queryDomain || 'api' + result += result ? '&' : '' + result += queryObjectToString(params, 'condition') } if (params.conditions) { params.conditions.forEach(function(condition) { - result += result ? '&' : ''; - result += queryObjectToString(condition, 'condition'); - }); + result += result ? '&' : '' + result += queryObjectToString(condition, 'condition') + }) } if (params.search) { - result += result ? '&' : ''; + result += result ? '&' : '' - result += 'api:search='; + result += 'api:search=' if (params.search instanceof Object) { - result += getJsonEncodedStringify(params.search); + result += getJsonEncodedStringify(params.search) } else { - result += encodeURIComponent(params.search); + result += encodeURIComponent(params.search) } if (params.hasOwnProperty('indexFieldsOnly')) { - result += '&api:indexFieldsOnly=' + getJsonEncodedStringify(params.indexFieldsOnly); + result += '&api:indexFieldsOnly=' + getJsonEncodedStringify(params.indexFieldsOnly) } } if (params.distinct) { - result += result ? '&' : ''; - result += 'api:distinct=' + encodeURIComponent((params.distinct instanceof Array ? params.distinct.join(',') : params.distinct)); + result += result ? '&' : '' + result += 'api:distinct=' + encodeURIComponent((params.distinct instanceof Array ? params.distinct.join(',') : params.distinct)) } if (params.sort) { - result += result ? '&' : ''; - result += 'api:sort=' + getJsonEncodedStringify(params.sort); + result += result ? '&' : '' + result += 'api:sort=' + getJsonEncodedStringify(params.sort) } if (params.pagination) { if (params.pagination.page || params.pagination.page === 0) { - result += result ? '&' : ''; - result += 'api:page=' + params.pagination.page; + result += result ? '&' : '' + result += 'api:page=' + params.pagination.page } if (params.pagination.pageSize || params.pagination.pageSize === 0) { - result += result ? '&' : ''; - result += 'api:pageSize=' + params.pagination.pageSize; + result += result ? '&' : '' + result += 'api:pageSize=' + params.pagination.pageSize } } if (params.customQueryParams) { Object.keys(params.customQueryParams).forEach(function(param) { - result += result ? '&' : ''; - result += param + '=' + encodeURIComponent(params.customQueryParams[param]); - }); + result += result ? '&' : '' + result += param + '=' + encodeURIComponent(params.customQueryParams[param]) + }) } - return result; - }; + return result + } utils.defaults = function(destiny, defaults) { Object.keys(defaults).forEach(function(key) { if (typeof(destiny[key]) === 'undefined') { - destiny[key] = defaults[key]; + destiny[key] = defaults[key] } - }); + }) - return destiny; - }; + return destiny + } utils.pick = function(object, keys) { - var destiny = {}; + var destiny = {} keys.forEach(function(key) { - destiny[key] = object[key]; - }); + destiny[key] = object[key] + }) - return destiny; - }; + return destiny + } utils.clone = function clone(item) { if (!item) { - return item; + return item } // null, undefined values check - var types = [Number, String, Boolean], - result; + var types = [Number, String, Boolean] + var result - // normalizing primitives if someone did new String('aaa'), or new Number('444'); + // normalizing primitives if someone did new String('aaa'), or new Number('444') types.forEach(function(type) { if (item instanceof type) { - result = type(item); + result = type(item) } - }); + }) if (typeof result === 'undefined') { if (Object.prototype.toString.call(item) === '[object Array]') { - result = []; + result = [] item.forEach(function(child, index) { - result[index] = clone(child); - }); + result[index] = clone(child) + }) } else if (typeof item === 'object') { // testing that this is DOM if (item.nodeType && typeof item.cloneNode === 'function') { - result = item.cloneNode(true); + result = item.cloneNode(true) } else if (!item.prototype) { // check that this is a literal if (item instanceof Date) { - result = new Date(item); + result = new Date(item) } else { // it is an object literal - result = {}; + result = {} for (var i in item) { - result[i] = clone(item[i]); + result[i] = clone(item[i]) } } } else { @@ -517,18 +512,18 @@ // just keep the reference, or create new object if (false && item.constructor) { // would not advice to do that, reason? Read below - result = new item.constructor(); + result = new item.constructor() } else { - result = item; + result = item } } } else { - result = item; + result = item } } - return result; - }; + return result + } /** * Change the keys of the object to lowercase due to @@ -538,45 +533,45 @@ */ utils.keysToLowerCase = function(obj) { if (obj === undefined || obj === null) { - return obj; + return obj } else { - var key; - var keys = Object.keys(obj); - var n = keys.length; - var newobj = {}; + var key + var keys = Object.keys(obj) + var n = keys.length + var newobj = {} while (n--) { - key = keys[n]; - newobj[key.toLowerCase()] = obj[key]; + key = keys[n] + newobj[key.toLowerCase()] = obj[key] } - return newobj; + return newobj } - }; + } utils.isJSON = function(string) { try { - JSON.parse(string); + JSON.parse(string) } catch (e) { - return false; + return false } - return true; - }; + return true + } utils.isStream = function(data) { if (data.pipe && typeof data.pipe === 'function') { - return true; + return true } else { - return false; + return false } - }; + } utils.arrayToObject = function(array) { - var object = {}; + var object = {} array.map(function(element, index) { - object[index] = element; - }); - return object; - }; + object[index] = element + }) + return object + } /** * Creates a copy of Array with the same inner elements @@ -584,13 +579,13 @@ * @return {Array} A copy version of the array */ utils.copyArray = function(list) { - var newList = new Array(list.length); - var i = list.length; + var newList = new Array(list.length) + var i = list.length while (i--) { - newList[i] = list[i]; + newList[i] = list[i] } - return newList; - }; + return newList + } /** * Convert data URI to Blob. @@ -599,15 +594,14 @@ * @return {Blob} */ utils.dataURItoBlob = function(dataURI) { - - var serialize; + var serialize if (corbel.Config.isNode) { - console.log('NODE'); - // node environment - serialize = require('atob'); + console.log('NODE') + // node environment + serialize = require('atob') } else { - console.log('BROWSER'); - serialize = root.atob; + console.log('BROWSER') + serialize = root.atob } /* @@ -618,71 +612,68 @@ * Phrantom has ton Blob() constructor support, * use BlobBuilder instead. */ - var BlobBuilder; - var BlobConstructor; + var BlobBuilder + var BlobConstructor if (corbel.Config.isBrowser) { BlobBuilder = window.BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || - window.MSBlobBuilder; - BlobConstructor = window.Blob; + window.MSBlobBuilder + BlobConstructor = window.Blob } // convert base64 to raw binary data held in a string - var byteString = serialize(dataURI.split(',')[1]); + var byteString = serialize(dataURI.split(',')[1]) // separate out the mime component - var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]; + var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0] // write the bytes of the string to an ArrayBuffer - var arrayBuffer = new ArrayBuffer(byteString.length); - var _ia = new Uint8Array(arrayBuffer); + var arrayBuffer = new ArrayBuffer(byteString.length) + var _ia = new Uint8Array(arrayBuffer) for (var i = 0; i < byteString.length; i++) { - _ia[i] = byteString.charCodeAt(i); + _ia[i] = byteString.charCodeAt(i) } - var blob; + var blob if (BlobBuilder) { - blob = new BlobBuilder(); - blob.append(arrayBuffer); - blob = blob.getBlob(mimeString); + blob = new BlobBuilder() + blob.append(arrayBuffer) + blob = blob.getBlob(mimeString) } else { blob = new BlobConstructor([_ia], { type: mimeString - }); + }) } - return blob; - }; - - return utils; + return blob + } - })(); + return utils + })() + /*globals corbel */ + ; (function() { - - - /** * A module to make values validation. * @exports validate * @namespace * @memberof app */ - corbel.validate = {}; + corbel.validate = {} corbel.validate.values = function(keys, obj) { - var that = this; + var that = this keys.forEach(function(key) { - that.value(key, obj[key]); - }); - return true; - }; + that.value(key, obj[key]) + }) + return true + } corbel.validate.value = function(key, value) { - return this.isDefined(value, key + ' value is mandatory and cannot be undefined'); - }; - + return this.isDefined(value, key + ' value is mandatory and cannot be undefined') + } /** * Checks if some value is not undefined @@ -692,13 +683,13 @@ * @return {Boolean} */ corbel.validate.isDefined = function(value, message) { - var isUndefined = value === undefined; + var isUndefined = value === undefined if (isUndefined && message) { - throw new Error(message); + throw new Error(message) } - return !isUndefined; - }; + return !isUndefined + } /** * Checks if some value is defined and throw error @@ -709,13 +700,13 @@ */ corbel.validate.failIfIsDefined = function(value, message) { - var isDefined = value !== undefined; + var isDefined = value !== undefined if (isDefined && message) { - throw new Error(message); + throw new Error(message) } - return !isDefined; - }; + return !isDefined + } /** * Checks whenever value are null or not @@ -725,13 +716,13 @@ * @return {Boolean} */ corbel.validate.isNotNull = function(value, message) { - var isNull = value === null; + var isNull = value === null if (isNull && message) { - throw new Error(message); + throw new Error(message) } - return !isNull; - }; + return !isNull + } /** * Checks whenever a value is not null and not undefined @@ -741,8 +732,8 @@ * @return {Boolean} */ corbel.validate.isValue = function(value, message) { - return this.isDefined(value, message) && this.isNotNull(value, message); - }; + return this.isDefined(value, message) && this.isNotNull(value, message) + } /** * Checks if a variable is a type of object @@ -750,8 +741,8 @@ * @return {Boolean} */ corbel.validate.isObject = function(obj) { - return typeof obj === 'object'; - }; + return typeof obj === 'object' + } /** * Checks whenever a value is greater than other @@ -762,13 +753,13 @@ * @return {Boolean} */ corbel.validate.isGreaterThan = function(value, greaterThan, message) { - var gt = this.isValue(value) && value > greaterThan; + var gt = this.isValue(value) && value > greaterThan if (!gt && message) { - throw new Error(message); + throw new Error(message) } - return gt; - }; + return gt + } /** * Checks whenever a value is greater or equal than other @@ -779,19 +770,20 @@ * @return {Boolean} */ corbel.validate.isGreaterThanOrEqual = function(value, isGreaterThanOrEqual, message) { - var gte = this.isValue(value) && value >= isGreaterThanOrEqual; + var gte = this.isValue(value) && value >= isGreaterThanOrEqual if (!gte && message) { - throw new Error(message); + throw new Error(message) } - return gte; - }; + return gte + } + })() - })(); + /* global corbel */ + ; (function() { - /** * Base object with * @class @@ -800,8 +792,8 @@ * @memberof corbel */ corbel.Object = function() { - return this; - }; + return this + } /** * Gets my user assets @@ -809,15 +801,15 @@ * @see corbel.utils.inherit * @return {Object} */ - corbel.Object.inherit = corbel.utils.inherit; + corbel.Object.inherit = corbel.utils.inherit - return corbel.Object; + return corbel.Object + })() - })(); + ; (function() { - /* jshint camelcase:false */ corbel.cryptography = (function() { /* @@ -834,31 +826,31 @@ * Configurable variables. You may need to tweak these to be compatible with * the server-side, but the defaults work in most cases. */ - var hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase */ - var b64pad = ''; /* base-64 pad character. "=" for strict RFC compliance */ + // var hexcase = 0 hex output format. 0 - lowercase; 1 - uppercase + var b64pad = '' /* base-64 pad character. "=" for strict RFC compliance */ function b64_hmac_sha256(k, d) { - return rstr2b64(rstr_hmac_sha256(str2rstr_utf8(k), str2rstr_utf8(d))); + return rstr2b64(rstr_hmac_sha256(str2rstr_utf8(k), str2rstr_utf8(d))) } /* * Calculate the HMAC-sha256 of a key and some data (raw strings) */ function rstr_hmac_sha256(key, data) { - var bkey = rstr2binb(key); + var bkey = rstr2binb(key) if (bkey.length > 16) { - bkey = binb_sha256(bkey, key.length * 8); + bkey = binb_sha256(bkey, key.length * 8) } - var ipad = Array(16), - opad = Array(16); + var ipad = Array(16) + var opad = Array(16) for (var i = 0; i < 16; i++) { - ipad[i] = bkey[i] ^ 0x36363636; - opad[i] = bkey[i] ^ 0x5C5C5C5C; + ipad[i] = bkey[i] ^ 0x36363636 + opad[i] = bkey[i] ^ 0x5C5C5C5C } - var hash = binb_sha256(ipad.concat(rstr2binb(data)), 512 + data.length * 8); - return binb2rstr(binb_sha256(opad.concat(hash), 512 + 256)); + var hash = binb_sha256(ipad.concat(rstr2binb(data)), 512 + data.length * 8) + return binb2rstr(binb_sha256(opad.concat(hash), 512 + 256)) } /* @@ -868,19 +860,19 @@ try { b64pad } catch (e) { - b64pad = ''; + b64pad = '' } - var tab = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; - var output = ''; - var len = input.length; + var tab = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' + var output = '' + var len = input.length for (var i = 0; i < len; i += 3) { - var triplet = (input.charCodeAt(i) << 16) | (i + 1 < len ? input.charCodeAt(i + 1) << 8 : 0) | (i + 2 < len ? input.charCodeAt(i + 2) : 0); + var triplet = (input.charCodeAt(i) << 16) | (i + 1 < len ? input.charCodeAt(i + 1) << 8 : 0) | (i + 2 < len ? input.charCodeAt(i + 2) : 0) for (var j = 0; j < 4; j++) { - if (i * 8 + j * 6 > input.length * 8) output += b64pad; - else output += tab.charAt((triplet >>> 6 * (3 - j)) & 0x3F); + if (i * 8 + j * 6 > input.length * 8) output += b64pad + else output += tab.charAt((triplet >>> 6 * (3 - j)) & 0x3F) } } - return output; + return output } /* @@ -888,36 +880,36 @@ * For efficiency, this assumes the input is valid utf-16. */ function str2rstr_utf8(input) { - var output = ''; - var i = -1; - var x, y; + var output = '' + var i = -1 + var x, y while (++i < input.length) { /* Decode utf-16 surrogate pairs */ - x = input.charCodeAt(i); - y = i + 1 < input.length ? input.charCodeAt(i + 1) : 0; - if (0xD800 <= x && x <= 0xDBFF && 0xDC00 <= y && y <= 0xDFFF) { - x = 0x10000 + ((x & 0x03FF) << 10) + (y & 0x03FF); - i++; + x = input.charCodeAt(i) + y = i + 1 < input.length ? input.charCodeAt(i + 1) : 0 + if (x > 0xD800 && x <= 0xDBFF && y > 0xDC00 && y <= 0xDFFF) { + x = 0x10000 + ((x & 0x03FF) << 10) + (y & 0x03FF) + i++ } /* Encode output as utf-8 */ - if (x <= 0x7F) - output += String.fromCharCode(x); - else if (x <= 0x7FF) - output += String.fromCharCode(0xC0 | ((x >>> 6) & 0x1F), - 0x80 | (x & 0x3F)); - else if (x <= 0xFFFF) + if (x <= 0x7F) { + output += String.fromCharCode(x) + } else if (x <= 0x7FF) { + output += String.fromCharCode(0xC0 | ((x >>> 6) & 0x1F), 0x80 | (x & 0x3F)) + } else if (x <= 0xFFFF) { output += String.fromCharCode(0xE0 | ((x >>> 12) & 0x0F), 0x80 | ((x >>> 6) & 0x3F), - 0x80 | (x & 0x3F)); - else if (x <= 0x1FFFFF) + 0x80 | (x & 0x3F)) + } else if (x <= 0x1FFFFF) { output += String.fromCharCode(0xF0 | ((x >>> 18) & 0x07), 0x80 | ((x >>> 12) & 0x3F), 0x80 | ((x >>> 6) & 0x3F), - 0x80 | (x & 0x3F)); + 0x80 | (x & 0x3F)) + } } - return output; + return output } /* @@ -925,60 +917,63 @@ * Characters >255 have their high-byte silently ignored. */ function rstr2binb(input) { - var output = Array(input.length >> 2); - for (var i = 0; i < output.length; i++) - output[i] = 0; - for (var i = 0; i < input.length * 8; i += 8) - output[i >> 5] |= (input.charCodeAt(i / 8) & 0xFF) << (24 - i % 32); - return output; + var output = Array(input.length >> 2) + for (var i = 0; i < output.length; i++) { + output[i] = 0 + } + for (var j = 0; j < input.length * 8; j += 8) { + output[j >> 5] |= (input.charCodeAt(j / 8) & 0xFF) << (24 - j % 32) + } + return output } /* * Convert an array of big-endian words to a string */ function binb2rstr(input) { - var output = ''; - for (var i = 0; i < input.length * 32; i += 8) - output += String.fromCharCode((input[i >> 5] >>> (24 - i % 32)) & 0xFF); - return output; + var output = '' + for (var i = 0; i < input.length * 32; i += 8) { + output += String.fromCharCode((input[i >> 5] >>> (24 - i % 32)) & 0xFF) + } + return output } /* * Main sha256 function, with its support functions */ function sha256_S(X, n) { - return (X >>> n) | (X << (32 - n)); + return (X >>> n) | (X << (32 - n)) } function sha256_R(X, n) { - return (X >>> n); + return (X >>> n) } function sha256_Ch(x, y, z) { - return ((x & y) ^ ((~x) & z)); + return ((x & y) ^ ((~x) & z)) } function sha256_Maj(x, y, z) { - return ((x & y) ^ (x & z) ^ (y & z)); + return ((x & y) ^ (x & z) ^ (y & z)) } function sha256_Sigma0256(x) { - return (sha256_S(x, 2) ^ sha256_S(x, 13) ^ sha256_S(x, 22)); + return (sha256_S(x, 2) ^ sha256_S(x, 13) ^ sha256_S(x, 22)) } function sha256_Sigma1256(x) { - return (sha256_S(x, 6) ^ sha256_S(x, 11) ^ sha256_S(x, 25)); + return (sha256_S(x, 6) ^ sha256_S(x, 11) ^ sha256_S(x, 25)) } function sha256_Gamma0256(x) { - return (sha256_S(x, 7) ^ sha256_S(x, 18) ^ sha256_R(x, 3)); + return (sha256_S(x, 7) ^ sha256_S(x, 18) ^ sha256_R(x, 3)) } function sha256_Gamma1256(x) { - return (sha256_S(x, 17) ^ sha256_S(x, 19) ^ sha256_R(x, 10)); + return (sha256_S(x, 17) ^ sha256_S(x, 19) ^ sha256_R(x, 10)) } - var sha256_K = new Array( + var sha256_K = [ 1116352408, 1899447441, -1245643825, -373957723, 961987163, 1508970993, -1841331548, -1424204075, -670586216, 310598401, 607225278, 1426881987, 1925078388, -2132889090, -1680079193, -1046744716, -459576895, -272742522, 264347078, 604807628, 770255983, 1249150122, 1555081692, 1996064986, -1740746414, -1473132947, -1341970488, -1084653625, -958395405, -710438585, @@ -986,63 +981,67 @@ 1695183700, 1986661051, -2117940946, -1838011259, -1564481375, -1474664885, -1035236496, -949202525, -778901479, -694614492, -200395387, 275423344, 430227734, 506948616, 659060556, 883997877, 958139571, 1322822218, 1537002063, 1747873779, 1955562222, 2024104815, -2067236844, -1933114872, -1866530822, -1538233109, -1090935817, -965641998 - ); + ] function binb_sha256(m, l) { - var HASH = new Array(1779033703, -1150833019, 1013904242, -1521486534, - 1359893119, -1694144372, 528734635, 1541459225); - var W = new Array(64); - var a, b, c, d, e, f, g, h; - var i, j, T1, T2; + var HASH = [1779033703, -1150833019, 1013904242, -1521486534, + 1359893119, -1694144372, 528734635, 1541459225 + ] + var W = new Array(64) + var a, b, c, d, e, f, g, h + var i, j, T1, T2 /* append padding */ - m[l >> 5] |= 0x80 << (24 - l % 32); - m[((l + 64 >> 9) << 4) + 15] = l; + m[l >> 5] |= 0x80 << (24 - l % 32) + m[((l + 64 >> 9) << 4) + 15] = l for (i = 0; i < m.length; i += 16) { - a = HASH[0]; - b = HASH[1]; - c = HASH[2]; - d = HASH[3]; - e = HASH[4]; - f = HASH[5]; - g = HASH[6]; - h = HASH[7]; + a = HASH[0] + b = HASH[1] + c = HASH[2] + d = HASH[3] + e = HASH[4] + f = HASH[5] + g = HASH[6] + h = HASH[7] for (j = 0; j < 64; j++) { - if (j < 16) W[j] = m[j + i]; - else W[j] = safe_add(safe_add(safe_add(sha256_Gamma1256(W[j - 2]), W[j - 7]), - sha256_Gamma0256(W[j - 15])), W[j - 16]); + if (j < 16) { + W[j] = m[j + i] + } else { + W[j] = safe_add(safe_add(safe_add(sha256_Gamma1256(W[j - 2]), W[j - 7]), + sha256_Gamma0256(W[j - 15])), W[j - 16]) + } T1 = safe_add(safe_add(safe_add(safe_add(h, sha256_Sigma1256(e)), sha256_Ch(e, f, g)), - sha256_K[j]), W[j]); - T2 = safe_add(sha256_Sigma0256(a), sha256_Maj(a, b, c)); - h = g; - g = f; - f = e; - e = safe_add(d, T1); - d = c; - c = b; - b = a; - a = safe_add(T1, T2); + sha256_K[j]), W[j]) + T2 = safe_add(sha256_Sigma0256(a), sha256_Maj(a, b, c)) + h = g + g = f + f = e + e = safe_add(d, T1) + d = c + c = b + b = a + a = safe_add(T1, T2) } - HASH[0] = safe_add(a, HASH[0]); - HASH[1] = safe_add(b, HASH[1]); - HASH[2] = safe_add(c, HASH[2]); - HASH[3] = safe_add(d, HASH[3]); - HASH[4] = safe_add(e, HASH[4]); - HASH[5] = safe_add(f, HASH[5]); - HASH[6] = safe_add(g, HASH[6]); - HASH[7] = safe_add(h, HASH[7]); + HASH[0] = safe_add(a, HASH[0]) + HASH[1] = safe_add(b, HASH[1]) + HASH[2] = safe_add(c, HASH[2]) + HASH[3] = safe_add(d, HASH[3]) + HASH[4] = safe_add(e, HASH[4]) + HASH[5] = safe_add(f, HASH[5]) + HASH[6] = safe_add(g, HASH[6]) + HASH[7] = safe_add(h, HASH[7]) } - return HASH; + return HASH } function safe_add(x, y) { - var lsw = (x & 0xFFFF) + (y & 0xFFFF); - var msw = (x >> 16) + (y >> 16) + (lsw >> 16); - return (msw << 16) | (lsw & 0xFFFF); + var lsw = (x & 0xFFFF) + (y & 0xFFFF) + var msw = (x >> 16) + (y >> 16) + (lsw >> 16) + return (msw << 16) | (lsw & 0xFFFF) } /*! base64x-1.1.3 (c) 2012-2014 Kenji Urushima | kjur.github.com/jsjws/license @@ -1088,7 +1087,8 @@ * @see 'jwjws'(JWS JavaScript Library) home page http://kjur.github.com/jsjws/ * @see 'jwrsasign'(RSA Sign JavaScript Library) home page http://kjur.github.com/jsrsasign/ */ - function Base64x() {} + + // function Base64x () {} // ==== base64 / base64url ================================ /** @@ -1098,13 +1098,14 @@ * @return {String} Base64URL encoded string */ function b64tob64u(s) { - s = s.replace(/\=/g, ''); - s = s.replace(/\+/g, '-'); - s = s.replace(/\//g, '_'); - return s; + s = s.replace(/\=/g, '') + s = s.replace(/\+/g, '-') + s = s.replace(/\//g, '_') + return s } - var utf8tob64u, b64utoutf8; + // var utf8tob64u + // var b64utoutf8 return { rstr2b64: rstr2b64, @@ -1112,17 +1113,16 @@ b64_hmac_sha256: b64_hmac_sha256, b64tob64u: b64tob64u } - })(); - - })(); + })() + })() /* jshint camelcase:false */ + /* global corbel */ + ; (function() { - var jwt = corbel.jwt = { - EXPIRATION: 3500, ALGORITHM: 'HS256', TYP: 'JWT', @@ -1137,21 +1137,21 @@ * @return {String} jwt JWT string */ generate: function(claims, secret, alg) { - claims = claims || {}; - claims.exp = claims.exp || jwt._generateExp(); + claims = claims || {} + claims.exp = claims.exp || jwt._generateExp() if (!claims.iss) { - throw new Error('jwt:undefined:iss'); + throw new Error('jwt:undefined:iss') } if (!claims.aud) { - throw new Error('jwt:undefined:aud'); + throw new Error('jwt:undefined:aud') } - return jwt._generate(claims, secret, alg); + return jwt._generate(claims, secret, alg) }, _generate: function(claims, secret, alg) { - alg = alg || jwt.ALGORITHM; + alg = alg || jwt.ALGORITHM // Ensure claims specific order var claimsKeys = [ @@ -1168,81 +1168,82 @@ 'basic_auth.password', 'device_id' - ]; + ] - var finalClaims = {}; + var finalClaims = {} claimsKeys.forEach(function(key) { if (claims[key]) { - finalClaims[key] = claims[key]; + finalClaims[key] = claims[key] } - }); + }) - corbel.utils.extend(finalClaims, claims); + corbel.utils.extend(finalClaims, claims) if (Array.isArray(finalClaims.scope)) { - finalClaims.scope = finalClaims.scope.join(' '); + finalClaims.scope = finalClaims.scope.join(' ') } var bAlg = corbel.cryptography.rstr2b64(corbel.cryptography.str2rstr_utf8(JSON.stringify({ - typ: jwt.TYP, - alg: alg - }))), - bClaims = corbel.cryptography.rstr2b64(corbel.cryptography.str2rstr_utf8(JSON.stringify(finalClaims))), - segment = bAlg + '.' + bClaims, - assertion = corbel.cryptography.b64tob64u(corbel.cryptography.b64_hmac_sha256(secret, segment)); + typ: jwt.TYP, + alg: alg + }))) + var bClaims = corbel.cryptography.rstr2b64(corbel.cryptography.str2rstr_utf8(JSON.stringify(finalClaims))) + var segment = bAlg + '.' + bClaims + var assertion = corbel.cryptography.b64tob64u(corbel.cryptography.b64_hmac_sha256(secret, segment)) - return segment + '.' + assertion; + return segment + '.' + assertion }, _generateExp: function() { - return Math.round((new Date().getTime() / 1000)) + jwt.EXPIRATION; + return Math.round((new Date().getTime() / 1000)) + jwt.EXPIRATION }, decode: function(assertion) { - var serialize; + var serialize if (corbel.Config.isNode) { // node environment - serialize = require('atob'); + serialize = require('atob') } else { - serialize = root.atob; + serialize = root.atob } - var decoded = assertion.split('.'); + var decoded = assertion.split('.') try { - decoded[0] = JSON.parse(serialize(decoded[0])); + decoded[0] = JSON.parse(serialize(decoded[0])) } catch (e) { - decoded[0] = false; + decoded[0] = false } try { - decoded[1] = JSON.parse(serialize(decoded[1])); + decoded[1] = JSON.parse(serialize(decoded[1])) } catch (e) { - decoded[1] = false; + decoded[1] = false } if (!decoded[0] && !decoded[1]) { - throw new Error('corbel:jwt:decode:invalid_assertion'); + throw new Error('corbel:jwt:decode:invalid_assertion') } - decoded[0] = decoded[0] || {}; - decoded[1] = decoded[1] || {}; + decoded[0] = decoded[0] || {} + decoded[1] = decoded[1] || {} Object.keys(decoded[1]).forEach(function(key) { - decoded[0][key] = decoded[1][key]; - }); + decoded[0][key] = decoded[1][key] + }) - return decoded[0]; + return decoded[0] } - }; + } - return jwt; + return jwt + })() - })(); + /* global corbel XMLHttpRequest*/ + ; (function() { - /** * Request object available for brwoser and node environment * @exports request @@ -1255,7 +1256,6 @@ * @namespace */ method: { - /** * GET constant * @constant @@ -1300,7 +1300,7 @@ */ HEAD: 'HEAD' } - }; + } /** * Serialize handlers @@ -1314,9 +1314,9 @@ */ json: function(data, cb) { if (typeof data !== 'string') { - cb(JSON.stringify(data)); + cb(JSON.stringify(data)) } else { - cb(data); + cb(data) } }, /** @@ -1325,7 +1325,7 @@ * @return {string} */ 'form-urlencoded': function(data, cb) { - cb(corbel.utils.toURLEncoded(data)); + cb(corbel.utils.toURLEncoded(data)) }, /** * dataURI serialize handler @@ -1335,10 +1335,10 @@ dataURI: function(data, cb) { if (corbel.Config.isNode) { // in node transform to stream - cb(corbel.utils.toURLEncoded(data)); + cb(corbel.utils.toURLEncoded(data)) } else { // in browser transform to blob - cb(corbel.utils.dataURItoBlob(data)); + cb(corbel.utils.dataURItoBlob(data)) } }, /** @@ -1349,9 +1349,9 @@ */ blob: function(data, cb) { if (data instanceof ArrayBuffer) { - throw new Error('ArrayBuffer is not supported, please use Blob'); + throw new Error('ArrayBuffer is not supported, please use Blob') } else { - cb(data); + cb(data) } }, /** @@ -1361,12 +1361,12 @@ */ stream: function(data, cb) { if (data instanceof ArrayBuffer) { - throw new Error('ArrayBuffer is not supported, please use Blob, File, Stream or ArrayBufferView'); + throw new Error('ArrayBuffer is not supported, please use Blob, File, Stream or ArrayBufferView') } else { - cb(data); + cb(data) } } - }; + } /** * Serialize hada with according contentType handler @@ -1378,16 +1378,16 @@ request.serialize = function(data, contentType, cb) { var contentTypeSerializable = Object.keys(request.serializeHandlers).filter(function(type) { if (contentType.indexOf(type) !== -1) { - return type; + return type } - }); + }) if (contentTypeSerializable.length > 0) { - request.serializeHandlers[contentTypeSerializable[0]](data, cb); + request.serializeHandlers[contentTypeSerializable[0]](data, cb) } else { - cb(data); + cb(data) } - }; + } /** * Parse handlers @@ -1400,15 +1400,15 @@ * @return {mixed} */ json: function(data) { - data = data || '{}'; + data = data || '{}' if (typeof data === 'string') { - data = JSON.parse(data); + data = JSON.parse(data) } - return data; + return data } // 'blob' type do not require any process // @todo: xml - }; + } /** * Process the server response data to the specified object/array/blob/byteArray/text @@ -1418,23 +1418,23 @@ * @return {mixed} Processed data */ request.parse = function(data, responseType, dataType) { - var parsed; + var parsed Object.keys(request.parseHandlers).forEach(function(type) { if (responseType && responseType.indexOf(type) !== -1) { - parsed = request.parseHandlers[type](data, dataType); + parsed = request.parseHandlers[type](data, dataType) } - }); - parsed = parsed || data; - return parsed; - }; + }) + parsed = parsed || data + return parsed + } function doRequest(module, params, resolver) { if (corbel.Config.isBrowser) { - //browser - request._browserAjax.call(module, params, resolver); + // browser + request._browserAjax.call(module, params, resolver) } else { - //nodejs - request._nodeAjax.call(module, params, resolver); + // nodejs + request._nodeAjax.call(module, params, resolver) } } @@ -1453,15 +1453,15 @@ * @return {Promise} Promise about the request status and response */ request.send = function(options, driver) { - options = options || {}; - var module = this; + options = options || {} + var module = this if (!options.url) { - throw new Error('undefined:url'); + throw new Error('undefined:url') } if (typeof(options.url) !== 'string') { - throw new Error('invalid:url', options.url); + throw new Error('invalid:url', options.url) } var params = { @@ -1473,38 +1473,38 @@ responseType: options.responseType, withCredentials: options.withCredentials || true, useCookies: options.useCookies || false - }; + } - params = rewriteRequestToPostIfUrlLengthIsTooLarge(options, params); + params = rewriteRequestToPostIfUrlLengthIsTooLarge(options, params) // default content-type - params.headers['content-type'] = options.contentType || 'application/json'; + params.headers['content-type'] = options.contentType || 'application/json' - var dataMethods = [request.method.PUT, request.method.POST, request.method.PATCH]; + var dataMethods = [request.method.PUT, request.method.POST, request.method.PATCH] - var resolver; + var resolver var promise = new Promise(function(resolve, reject) { resolver = { resolve: resolve, reject: reject - }; + } if (driver) { - driver.trigger('request', params); + driver.trigger('request', params) } - }); + }) if (dataMethods.indexOf(params.method) !== -1) { request.serialize(options.data, params.headers['content-type'], function(serialized) { - params.data = serialized; - doRequest(module, params, resolver); - }); + params.data = serialized + doRequest(module, params, resolver) + }) } else { - doRequest(module, params, resolver); + doRequest(module, params, resolver) } - return promise; - }; + return promise + } var xhrSuccessStatus = { // file protocol always yields status code 0, assume 200 @@ -1512,7 +1512,7 @@ // Support: IE9 // #1450: sometimes IE returns 1223 when it should be 204 1223: 204 - }; + } /** * Process server response @@ -1522,45 +1522,42 @@ * @param {function} callbackError */ var processResponse = function(response, resolver, callbackSuccess, callbackError) { + // xhr = xhr.target || xhr || {} + var statusCode = xhrSuccessStatus[response.status] || response.status + var statusType = Number(response.status.toString()[0]) + var promiseResponse - //xhr = xhr.target || xhr || {}; - var statusCode = xhrSuccessStatus[response.status] || response.status, - statusType = Number(response.status.toString()[0]), - promiseResponse; - - var data = response.response; - var headers = corbel.utils.keysToLowerCase(response.headers); + var data = response.response + var headers = corbel.utils.keysToLowerCase(response.headers) if (statusType <= 3 && !response.error) { - if (response.response) { - data = request.parse(response.response, response.responseType, response.dataType); + data = request.parse(response.response, response.responseType, response.dataType) } if (callbackSuccess) { - callbackSuccess.call(this, data, statusCode, response.responseObject, headers); + callbackSuccess.call(this, data, statusCode, response.responseObject, headers) } promiseResponse = { data: data, status: statusCode, headers: headers - }; + } - promiseResponse[response.responseObjectType] = response.responseObject; + promiseResponse[response.responseObjectType] = response.responseObject - resolver.resolve(promiseResponse); + resolver.resolve(promiseResponse) } else { - - var disconnected = response.error && response.status === 0; - statusCode = disconnected ? 0 : statusCode; + var disconnected = response.error && response.status === 0 + statusCode = disconnected ? 0 : statusCode if (callbackError) { - callbackError.call(this, response.error, statusCode, response.responseObject, headers); + callbackError.call(this, response.error, statusCode, response.responseObject, headers) } if (response.response) { - data = request.parse(response.response, response.responseType, response.dataType); + data = request.parse(response.response, response.responseType, response.dataType) } promiseResponse = { @@ -1568,61 +1565,61 @@ status: statusCode, error: response.error, headers: headers - }; + } - promiseResponse[response.responseObjectType] = response.responseObject; + promiseResponse[response.responseObjectType] = response.responseObject - resolver.reject(promiseResponse); + resolver.reject(promiseResponse) } - }; + } var rewriteRequestToPostIfUrlLengthIsTooLarge = function(options, params) { - var AUTOMATIC_HTTP_METHOD_OVERRIDE = corbel.Config.AUTOMATIC_HTTP_METHOD_OVERRIDE || true; - var HTTP_METHOD_OVERRIDE_WITH_URL_SIZE_BIGGER_THAN = corbel.Config.HTTP_METHOD_OVERRIDE_WITH_URL_SIZE_BIGGER_THAN || 2048; + var AUTOMATIC_HTTP_METHOD_OVERRIDE = corbel.Config.AUTOMATIC_HTTP_METHOD_OVERRIDE || true + var HTTP_METHOD_OVERRIDE_WITH_URL_SIZE_BIGGER_THAN = corbel.Config.HTTP_METHOD_OVERRIDE_WITH_URL_SIZE_BIGGER_THAN || 2048 if (AUTOMATIC_HTTP_METHOD_OVERRIDE && params.method === request.method.GET && params.url.length > HTTP_METHOD_OVERRIDE_WITH_URL_SIZE_BIGGER_THAN) { - var url = params.url.split('?'); - params.method = request.method.POST; - params.headers['X-HTTP-Method-Override'] = request.method.GET; - params.url = url[0]; - options.data = encodeUrlToForm(url[1]); - options.contentType = 'application/x-www-form-urlencoded'; - } - return params; - }; + var url = params.url.split('?') + params.method = request.method.POST + params.headers['X-HTTP-Method-Override'] = request.method.GET + params.url = url[0] + options.data = encodeUrlToForm(url[1]) + options.contentType = 'application/x-www-form-urlencoded' + } + return params + } var encodeUrlToForm = function(url) { - var form = {}; + var form = {} url.split('&').forEach(function(formEntry) { - var formPair = formEntry.split('='); - //value require double encode in Override Method Filter - form[formPair[0]] = formPair[1]; - }); - return form; - }; + var formPair = formEntry.split('=') + // value require double encode in Override Method Filter + form[formPair[0]] = formPair[1] + }) + return form + } request._getNodeRequestAjax = function(params) { - var requestAjax = require('request'); + var requestAjax = require('request') if (request.isCrossDomain(params.url) && params.withCredentials && params.useCookies) { requestAjax = requestAjax.defaults({ jar: true - }); + }) } - return requestAjax; - }; + return requestAjax + } request._getNodeRequestCallback = function(context, params, resolver) { return function(error, response, body) { - var responseType; - var status; + var responseType + var status if (error) { - responseType = undefined; - status = 0; + responseType = undefined + status = 0 } else { - responseType = response.responseType || response.headers['content-type']; - status = response.statusCode; + responseType = response.responseType || response.headers['content-type'] + status = response.statusCode } processResponse.call(context, { @@ -1634,33 +1631,30 @@ headers: response ? response.headers : {}, responseObjectType: 'response', error: error - }, resolver, params.callbackSuccess, params.callbackError); - - }; - }; + }, resolver, params.callbackSuccess, params.callbackError) + } + } request._nodeAjax = function(params, resolver) { - var requestAjax = request._getNodeRequestAjax(params); + var requestAjax = request._getNodeRequestAjax(params) var requestOptions = { method: params.method, url: params.url, - headers: params.headers, - }; + headers: params.headers + } - var data = params.data || ''; + var data = params.data || '' - var callbackRequest = request._getNodeRequestCallback(this, params, resolver); + var callbackRequest = request._getNodeRequestCallback(this, params, resolver) if (corbel.utils.isStream(data)) { - data.pipe(requestAjax(requestOptions, callbackRequest)); + data.pipe(requestAjax(requestOptions, callbackRequest)) } else { - requestOptions.body = data; - requestAjax(requestOptions, callbackRequest); + requestOptions.body = data + requestAjax(requestOptions, callbackRequest) } - - - }; + } /** * Check if an url should be process as a crossdomain resource. @@ -1669,11 +1663,11 @@ */ request.isCrossDomain = function(url) { if (url && typeof(url) === 'string' && url.indexOf('http') !== -1) { - return true; + return true } else { - return false; + return false } - }; + } /** * https://gist.github.com/monsur/706839 @@ -1681,46 +1675,46 @@ * @return {Object} */ request._parseResponseHeaders = function(headerStr) { - var headers = {}; + var headers = {} if (!headerStr) { - return headers; + return headers } - var headerPairs = headerStr.split('\u000d\u000a'); + var headerPairs = headerStr.split('\u000d\u000a') for (var i = 0; i < headerPairs.length; i++) { - var headerPair = headerPairs[i]; - // Can't use split() here because it does the wrong thing - // if the header value has the string ": " in it. - var index = headerPair.indexOf('\u003a\u0020'); + var headerPair = headerPairs[i] + // Can't use split() here because it does the wrong thing + // if the header value has the string ": " in it. + var index = headerPair.indexOf('\u003a\u0020') if (index > 0) { - var key = headerPair.substring(0, index); - var val = headerPair.substring(index + 2); - headers[key] = val; + var key = headerPair.substring(0, index) + var val = headerPair.substring(index + 2) + headers[key] = val } } - return headers; - }; + return headers + } request._browserAjax = function(params, resolver) { - var httpReq = new XMLHttpRequest(); + var httpReq = new XMLHttpRequest() // jshint ignore:line - httpReq.open(params.method, params.url, true); + httpReq.open(params.method, params.url, true) if (request.isCrossDomain(params.url) && params.withCredentials) { - httpReq.withCredentials = true; + httpReq.withCredentials = true } /* add request headers */ for (var header in params.headers) { if (params.headers.hasOwnProperty(header)) { - httpReq.setRequestHeader(header, params.headers[header]); + httpReq.setRequestHeader(header, params.headers[header]) } } // 'blob' support - httpReq.responseType = params.responseType || httpReq.responseType; + httpReq.responseType = params.responseType || httpReq.responseType httpReq.onload = function(xhr) { - xhr = xhr.target || xhr; // only for mock testing purpose + xhr = xhr.target || xhr // only for mock testing purpose processResponse.call(this, { responseObject: xhr, @@ -1731,17 +1725,16 @@ headers: request._parseResponseHeaders(xhr.getAllResponseHeaders()), responseObjectType: 'xhr', error: xhr.error - }, resolver, params.callbackSuccess, params.callbackError); + }, resolver, params.callbackSuccess, params.callbackError) - //delete callbacks - }.bind(this); + // delete callbacks + }.bind(this) - //response fail () + // response fail () httpReq.onerror = function(xhr) { + xhr = xhr.target || xhr // only for fake sinon response xhr - xhr = xhr.target || xhr; // only for fake sinon response xhr - - var error = xhr.error ? xhr.error : true; + var error = xhr.error ? xhr.error : true processResponse.call(this, { responseObject: xhr, @@ -1751,26 +1744,25 @@ status: xhr.status, responseObjectType: 'xhr', error: error - }, resolver, params.callbackSuccess, params.callbackError); - - }.bind(this); - + }, resolver, params.callbackSuccess, params.callbackError) + }.bind(this) if (params.data) { - httpReq.send(params.data); + httpReq.send(params.data) } else { - //IE fix, send nothing (not null or undefined) - httpReq.send(); + // IE fix, send nothing (not null or undefined) + httpReq.send() } - }; + } - return request; + return request + })() - })(); + /*globals corbel */ + ; (function() { - /** * A base object to inherit from for make corbel-js requests with custom behavior. * @exports Services @@ -1778,8 +1770,7 @@ * @extends corbel.Object * @memberof corbel */ - var Services = corbel.Services = corbel.Object.inherit({ //instance props - + var Services = corbel.Services = corbel.Object.inherit({ // instance props /** * Creates a new Services * @memberof corbel.Services.prototype @@ -1787,13 +1778,13 @@ * @return {corbel.Services} */ constructor: function(driver) { - this.driver = driver; + this.driver = driver }, extractLocationId: function(res) { - console.log('corbel-js:service:extractLocationId', res); - var uri = res.jqXHR.getResponseHeader('Location'); - return uri ? uri.substr(uri.lastIndexOf('/') + 1) : undefined; + console.log('corbel-js:service:extractLocationId', res) + var uri = res.jqXHR.getResponseHeader('Location') + return uri ? uri.substr(uri.lastIndexOf('/') + 1) : undefined }, /** @@ -1807,58 +1798,52 @@ * @param {object} args The request arguments. */ request: function(args) { + this.driver.trigger('service:request:before', args) - this.driver.trigger('service:request:before', args); - - var that = this; + var that = this return this._requestWithRetries(args).then(function(response) { - that.driver.trigger('service:request:after', response); - that.driver.config.set(corbel.Services._UNAUTHORIZED_NUM_RETRIES, 0); - return response; + that.driver.trigger('service:request:after', response) + that.driver.config.set(corbel.Services._UNAUTHORIZED_NUM_RETRIES, 0) + return response }).catch(function(error) { - that.driver.trigger('service:request:after', error); - that.driver.config.set(corbel.Services._UNAUTHORIZED_NUM_RETRIES, 0); - throw error; - }); - + that.driver.trigger('service:request:after', error) + that.driver.config.set(corbel.Services._UNAUTHORIZED_NUM_RETRIES, 0) + throw error + }) }, _requestWithRetries: function(args) { - var that = this; - var maxRetries = corbel.Services._UNAUTHORIZED_MAX_RETRIES; - var requestParameters = that._buildParams(args); + var that = this + var maxRetries = corbel.Services._UNAUTHORIZED_MAX_RETRIES + var requestParameters = that._buildParams(args) return that._doRequest(requestParameters) .catch(function(response) { - - var retries = that.driver.config.get(corbel.Services._UNAUTHORIZED_NUM_RETRIES, 0); + var retries = that.driver.config.get(corbel.Services._UNAUTHORIZED_NUM_RETRIES, 0) if (retries < maxRetries && response.status === corbel.Services._UNAUTHORIZED_STATUS_CODE) { - - //A 401 request within, refresh the token and retry the request. + // A 401 request within, refresh the token and retry the request. return that._refreshToken() .then(function() { - - that.driver.config.set(corbel.Services._UNAUTHORIZED_NUM_RETRIES, retries + 1); - //@TODO: see if we need to upgrade the token to access assets. + that.driver.config.set(corbel.Services._UNAUTHORIZED_NUM_RETRIES, retries + 1) + // @TODO: see if we need to upgrade the token to access assets. return that._requestWithRetries(args).catch(function(retryResponse) { // rejects whole promise with the retry response - response = retryResponse; - throw response; - }); - }).catch(function() { - //Has failed refreshing, reject request - console.log('corbeljs:services:token:refresh:fail'); - - throw response; - }); - + response = retryResponse + throw response + }) + }) + .catch(function() { + // Has failed refreshing, reject request + console.log('corbeljs:services:token:refresh:fail') + + throw response + }) } else { - console.log('corbeljs:services:token:no_refresh', response.status); - throw response; + console.log('corbeljs:services:token:no_refresh', response.status) + throw response } - - }); + }) }, /** @@ -1868,42 +1853,37 @@ * @return {Promise} */ _doRequest: function(params) { - var that = this; + var that = this return corbel.request.send(params, that.driver).then(function(response) { + that.driver.config.set(corbel.Services._FORCE_UPDATE_STATUS, 0) + that.driver.config.set(corbel.Services._UNAUTHORIZED_NUM_RETRIES, 0) - that.driver.config.set(corbel.Services._FORCE_UPDATE_STATUS, 0); - that.driver.config.set(corbel.Services._UNAUTHORIZED_NUM_RETRIES, 0); - - return response; - + return response }).catch(function(response) { // Force update if (response.status === corbel.Services._FORCE_UPDATE_STATUS_CODE && response.textStatus === corbel.Services._FORCE_UPDATE_TEXT) { - - var retries = that.driver.config.get(corbel.Services._FORCE_UPDATE_STATUS, 0); + var retries = that.driver.config.get(corbel.Services._FORCE_UPDATE_STATUS, 0) if (retries < corbel.Services._FORCE_UPDATE_MAX_RETRIES) { - retries++; - that.driver.config.set(corbel.Services._FORCE_UPDATE_STATUS, retries); + retries++ + that.driver.config.set(corbel.Services._FORCE_UPDATE_STATUS, retries) - that.driver.trigger('force:update', response); + that.driver.trigger('force:update', response) - throw response; + throw response } else { - throw response; + throw response } } else { - throw response; + throw response } - - }); + }) }, - _refreshToken: function() { - var tokenObject = this.driver.config.get(corbel.Iam.IAM_TOKEN, {}); + var tokenObject = this.driver.config.get(corbel.Iam.IAM_TOKEN, {}) - return this._refreshHandler(tokenObject); + return this._refreshHandler(tokenObject) }, /** * Default token refresh handler @@ -1911,33 +1891,32 @@ * @return {Promise} */ _refreshHandler: function(tokenObject) { - var that = this; + var that = this if (this.driver._refreshHandlerPromise) { - return this.driver._refreshHandlerPromise; + return this.driver._refreshHandlerPromise } if (tokenObject.refreshToken) { - console.log('corbeljs:services:token:refresh'); + console.log('corbeljs:services:token:refresh') this.driver._refreshHandlerPromise = this.driver.iam.token().refresh( tokenObject.refreshToken, - this.driver.config.get(corbel.Iam.IAM_TOKEN_SCOPES, '') - ); - + this.driver.config.get(corbel.Iam.IAM_TOKEN_SCOPES, '')) } else { - console.log('corbeljs:services:token:create'); - this.driver._refreshHandlerPromise = this.driver.iam.token().create(); + console.log('corbeljs:services:token:create') + this.driver._refreshHandlerPromise = this.driver.iam.token().create() } return this.driver._refreshHandlerPromise .then(function(response) { - that.driver.trigger('token:refresh', response.data); - that.driver._refreshHandlerPromise = null; - return response; - }).catch(function(err) { - that.driver._refreshHandlerPromise = null; - throw err; - }); + that.driver.trigger('token:refresh', response.data) + that.driver._refreshHandlerPromise = null + return response + }) + .catch(function(err) { + that.driver._refreshHandlerPromise = null + throw err + }) }, /** @@ -1946,14 +1925,14 @@ */ _addAuthorization: function(params) { // @todo: support to oauth token and custom handlers - var accessToken = this.driver.config.get(corbel.Iam.IAM_TOKEN, {}).accessToken; + var accessToken = this.driver.config.get(corbel.Iam.IAM_TOKEN, {}).accessToken // Use access access token if exists if (accessToken) { - params.headers.Authorization = 'Bearer ' + accessToken; - params.withCredentials = true; + params.headers.Authorization = 'Bearer ' + accessToken + params.withCredentials = true } - return params; + return params }, /** @@ -1967,7 +1946,6 @@ * @return {object} */ _buildParams: function(args) { - // Default values var defaults = { dataType: 'json', @@ -1977,42 +1955,42 @@ Accept: 'application/json' }, method: corbel.request.method.GET - }; + } // do not modify args object - var params = corbel.utils.defaults({}, args); - params = corbel.utils.defaults(params, defaults); + var params = corbel.utils.defaults({}, args) + params = corbel.utils.defaults(params, defaults) if (!params.url) { - throw new Error('You must define an url'); + throw new Error('You must define an url') } if (params.query) { - params.url += '?' + params.query; + params.url += '?' + params.query } if (params.noRedirect) { - params.headers['No-Redirect'] = true; + params.headers['No-Redirect'] = true } if (params.Accept) { - params.headers.Accept = params.Accept; - params.dataType = undefined; // Accept & dataType are incompatibles + params.headers.Accept = params.Accept + params.dataType = undefined // Accept & dataType are incompatibles } // set correct accept & contentType in case of blob // @todo: remove contentType+accept same-type constraint if (params.dataType === 'blob') { if (corbel.Config.isBrowser) { - params.headers.Accept = params.data.type; - params.contentType = params.data.type; - params.dataType = undefined; // Accept & dataType are incompatibles + params.headers.Accept = params.data.type + params.contentType = params.data.type + params.dataType = undefined // Accept & dataType are incompatibles } } - params = this._addAuthorization(params); + params = this._addAuthorization(params) - return corbel.utils.pick(params, ['url', 'dataType', 'contentType', 'method', 'headers', 'data', 'dataFilter', 'responseType', 'withCredentials', 'success', 'error']); + return corbel.utils.pick(params, ['url', 'dataType', 'contentType', 'method', 'headers', 'data', 'dataFilter', 'responseType', 'withCredentials', 'success', 'error']) }, /** @@ -2020,26 +1998,24 @@ * @return {string} */ _buildUri: function() { - - var uri = ''; + var uri = '' if (this.urlBase.slice(-1) !== '/') { - uri += '/'; + uri += '/' } Array.prototype.slice.call(arguments).forEach(function(argument) { if (argument) { - uri += argument + '/'; + uri += argument + '/' } - }); + }) // remove last '/' - uri = uri.slice(0, -1); + uri = uri.slice(0, -1) - return this.urlBase + uri; + return this.urlBase + uri } }, { - /** * _FORCE_UPDATE_TEXT constant * @constant @@ -2109,15 +2085,15 @@ * @return {String} id from the Location */ getLocationId: function(responseObject) { - responseObject = responseObject || {}; - var location; + responseObject = responseObject || {} + var location if (responseObject.xhr) { - location = responseObject.xhr.getResponseHeader('location'); + location = responseObject.xhr.getResponseHeader('location') } else if (responseObject.response && responseObject.response.headers.location) { - location = responseObject.response.headers.location; + location = responseObject.response.headers.location } - return location ? location.substr(location.lastIndexOf('/') + 1) : undefined; + return location ? location.substr(location.lastIndexOf('/') + 1) : undefined }, /** @@ -2128,60 +2104,57 @@ */ addEmptyJson: function(response, type) { if (!response && type === 'json') { - response = '{}'; + response = '{}' } - return response; + return response } - }); + }) - return Services; + return Services + })() - })(); - - //----------corbel modules---------------- + // ----------corbel modules---------------- function Config(config) { - config = config || {}; - // config default values - this.config = {}; + config = config || {} + // config default values + this.config = {} - corbel.utils.extend(this.config, config); + corbel.utils.extend(this.config, config) } - Config.URL_BASE_PLACEHOLDER = '{{module}}'; - Config.URL_BASE_PORT_PLACEHOLDER = '{{modulePort}}'; + Config.URL_BASE_PLACEHOLDER = '{{module}}' + Config.URL_BASE_PORT_PLACEHOLDER = '{{modulePort}}' - corbel.Config = Config; + corbel.Config = Config var processExist = function() { - return typeof(process) !== 'undefined' || {}.toString.call(process) === '[object process]'; - }; - + return typeof(process) !== 'undefined' || {}.toString.call(process) === '[object process]' + } if (typeof module !== 'undefined' && module.exports && processExist() && typeof window === 'undefined') { - Config.__env__ = process.env.NODE_ENV === 'browser' ? 'browser' : 'node'; + Config.__env__ = process.env.NODE_ENV === 'browser' ? 'browser' : 'node' } else { - Config.__env__ = 'browser'; + Config.__env__ = 'browser' } + Config.isNode = Config.__env__ === 'node' - Config.isNode = Config.__env__ === 'node'; - - Config.isBrowser = Config.__env__ === 'browser'; + Config.isBrowser = Config.__env__ === 'browser' /** * Client type * @type {String} * @default */ - Config.clientType = Config.isNode ? 'NODE' : 'WEB'; + Config.clientType = Config.isNode ? 'NODE' : 'WEB' if (Config.isNode) { - Config.wwwRoot = 'localhost'; + Config.wwwRoot = 'localhost' } else { - Config.wwwRoot = window.location.protocol + '//' + window.location.host + window.location.pathname; + Config.wwwRoot = window.location.protocol + '//' + window.location.host + window.location.pathname } /** @@ -2189,25 +2162,25 @@ * @return {Object} */ Config.create = function(config) { - return new Config(config); - }; + return new Config(config) + } /** * Returns all application config params * @return {Object} */ Config.prototype.getConfig = function() { - return this.config; - }; + return this.config + } /** * Overrides current config with params object config * @param {Object} config An object with params to set as new config */ Config.prototype.setConfig = function(config) { - this.config = corbel.utils.extend(this.config, config); - return this; - }; + this.config = corbel.utils.extend(this.config, config) + return this + } /** * Gets a specific config param @@ -2218,27 +2191,24 @@ Config.prototype.get = function(field, defaultValue) { if (this.config[field] === undefined) { if (defaultValue === undefined) { - throw new Error('config:undefined:' + field + ''); + throw new Error('config:undefined:' + field + '') } else { - return defaultValue; + return defaultValue } } - return this.config[field]; - }; + return this.config[field] + } Config.prototype.getCurrentEndpoint = function(moduleName, port) { - var moduleEndpoint = moduleName + 'Endpoint'; - var endpoint = this.get(moduleEndpoint, null) ? - this.get(moduleEndpoint) : - this.get('urlBase'); - endpoint = endpoint.replace(corbel.Config.URL_BASE_PLACEHOLDER, moduleName); + var moduleEndpoint = moduleName + 'Endpoint' + var endpoint = this.get(moduleEndpoint, null) ? this.get(moduleEndpoint) : this.get('urlBase') + endpoint = endpoint.replace(corbel.Config.URL_BASE_PLACEHOLDER, moduleName) if (port) { - endpoint = endpoint.replace(corbel.Config.URL_BASE_PORT_PLACEHOLDER, port); + endpoint = endpoint.replace(corbel.Config.URL_BASE_PORT_PLACEHOLDER, port) } - return endpoint; - }; - + return endpoint + } /** * Sets a new value for specific config param @@ -2246,12 +2216,13 @@ * @param {Mixed} value Config param value */ Config.prototype.set = function(field, value) { - this.config[field] = value; - }; + this.config[field] = value + } + /* global corbel */ + ; (function() { - /** * A module to make iam requests. * @exports iam @@ -2260,21 +2231,21 @@ */ var Iam = corbel.Iam = function(driver) { - this.driver = driver; - }; + this.driver = driver + } - Iam.moduleName = 'iam'; - Iam.defaultPort = 8082; + Iam.moduleName = 'iam' + Iam.defaultPort = 8082 Iam.create = function(driver) { - return new Iam(driver); - }; + return new Iam(driver) + } - Iam.GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:jwt-bearer'; - Iam.AUD = 'http://iam.bqws.io'; - Iam.IAM_TOKEN = 'iamToken'; - Iam.IAM_TOKEN_SCOPES = 'iamScopes'; - Iam.IAM_DOMAIN = 'domain'; + Iam.GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:jwt-bearer' + Iam.AUD = 'http://iam.bqws.io' + Iam.IAM_TOKEN = 'iamToken' + Iam.IAM_TOKEN_SCOPES = 'iamScopes' + Iam.IAM_DOMAIN = 'domain' /** * COMMON MIXINS @@ -2289,23 +2260,23 @@ */ Iam._buildUri = function(uri, id) { if (id) { - uri += '/' + id; + uri += '/' + id } - var urlBase = this.driver.config.getCurrentEndpoint(Iam.moduleName, corbel.Iam._buildPort(this.driver.config)); + var urlBase = this.driver.config.getCurrentEndpoint(Iam.moduleName, corbel.Iam._buildPort(this.driver.config)) - return urlBase + uri; - }; + return urlBase + uri + } Iam._buildPort = function(config) { - return config.get('iamPort', null) || corbel.Iam.defaultPort; - }; - - })(); + return config.get('iamPort', null) || corbel.Iam.defaultPort + } + })() + /* global corbel */ + ; (function() { - /** * Creates a ClientBuilder for client managing requests. * @@ -2315,10 +2286,10 @@ * @return {corbel.Iam.ClientBuilder} */ corbel.Iam.prototype.client = function(domainId, clientId) { - var client = new ClientBuilder(domainId, clientId); - client.driver = this.driver; - return client; - }; + var client = new ClientBuilder(domainId, clientId) + client.driver = this.driver + return client + } /** * A builder for client management requests. @@ -2330,11 +2301,10 @@ * @memberOf iam */ var ClientBuilder = corbel.Iam.ClientBuilder = corbel.Services.inherit({ - constructor: function(domainId, clientId) { - this.domainId = domainId; - this.clientId = clientId; - this.uri = 'domain'; + this.domainId = domainId + this.clientId = clientId + this.uri = 'domain' }, /** @@ -2358,15 +2328,15 @@ * with a {@link corbelError}. */ create: function(client) { - console.log('iamInterface.domain.create', client); - corbel.validate.value('domainId', this.domainId); + console.log('iamInterface.domain.create', client) + corbel.validate.value('domainId', this.domainId) return this.request({ url: this._buildUri(this.uri + '/' + this.domainId + '/client'), method: corbel.request.method.POST, data: client }).then(function(res) { - return corbel.Services.getLocationId(res); - }); + return corbel.Services.getLocationId(res) + }) }, /** @@ -2380,12 +2350,12 @@ * @return {Promise} A promise with the client or fails with a {@link corbelError}. */ get: function() { - console.log('iamInterface.domain.get', this.clientId); - corbel.validate.values(['domainId', 'clientId'], this); + console.log('iamInterface.domain.get', this.clientId) + corbel.validate.values(['domainId', 'clientId'], this) return this.request({ url: this._buildUri(this.uri + '/' + this.domainId + '/client/' + this.clientId), method: corbel.request.method.GET - }); + }) }, /** @@ -2398,14 +2368,14 @@ * @see {@link corbel.util.serializeParams} to see a example of the params */ getAll: function(params) { - corbel.validate.failIfIsDefined(this.clientId, 'This function not allowed client identifier'); - corbel.validate.value('domainId', this.domainId); - console.log('iamInterface.domain.getAll'); + corbel.validate.failIfIsDefined(this.clientId, 'This function not allowed client identifier') + corbel.validate.value('domainId', this.domainId) + console.log('iamInterface.domain.getAll') return this.request({ url: this._buildUri(this.uri + '/' + this.domainId + '/client'), method: corbel.request.method.GET, query: params ? corbel.utils.serializeParams(params) : null - }); + }) }, /** @@ -2427,13 +2397,13 @@ * @return {Promise} A promise or fails with a {@link corbelError}. */ update: function(client) { - console.log('iamInterface.domain.update', client); - corbel.validate.values(['domainId', 'clientId'], this); + console.log('iamInterface.domain.update', client) + corbel.validate.values(['domainId', 'clientId'], this) return this.request({ url: this._buildUri(this.uri + '/' + this.domainId + '/client/' + this.clientId), method: corbel.request.method.PUT, data: client - }); + }) }, /** @@ -2447,24 +2417,24 @@ * @return {Promise} A promise or fails with a {@link corbelError}. */ remove: function() { - console.log('iamInterface.domain.remove', this.domainId, this.clientId); - corbel.validate.values(['domainId', 'clientId'], this); + console.log('iamInterface.domain.remove', this.domainId, this.clientId) + corbel.validate.values(['domainId', 'clientId'], this) return this.request({ url: this._buildUri(this.uri + '/' + this.domainId + '/client/' + this.clientId), method: corbel.request.method.DELETE - }); + }) }, _buildUri: corbel.Iam._buildUri - }); - - })(); + }) + })() + /* global corbel */ + ; (function() { - /** * Creates a DomainBuilder for domain managing requests. * @@ -2473,10 +2443,10 @@ * @return {corbel.Iam.DomainBuilder} */ corbel.Iam.prototype.domain = function(domainId) { - var domain = new DomainBuilder(domainId); - domain.driver = this.driver; - return domain; - }; + var domain = new DomainBuilder(domainId) + domain.driver = this.driver + return domain + } /** * A builder for domain management requests. @@ -2487,10 +2457,9 @@ * @memberOf iam */ var DomainBuilder = corbel.Iam.DomainBuilder = corbel.Services.inherit({ - constructor: function(domainId) { - this.domainId = domainId; - this.uri = 'domain'; + this.domainId = domainId + this.uri = 'domain' }, _buildUri: corbel.Iam._buildUri, @@ -2514,14 +2483,14 @@ * with a {@link corbelError}. */ create: function(domain) { - console.log('iamInterface.domain.create', domain); + console.log('iamInterface.domain.create', domain) return this.request({ url: this._buildUri(this.uri), method: corbel.request.method.POST, data: domain }).then(function(res) { - return corbel.Services.getLocationId(res); - }); + return corbel.Services.getLocationId(res) + }) }, /** @@ -2533,16 +2502,15 @@ * @return {Promise} A promise with the domain or fails with a {@link corbelError}. */ get: function() { - console.log('iamInterface.domain.get', this.domainId); - corbel.validate.value('domainId', this.domainId); + console.log('iamInterface.domain.get', this.domainId) + corbel.validate.value('domainId', this.domainId) return this.request({ url: this._buildUri(this.uri + '/' + this.domainId), method: corbel.request.method.GET - }); + }) }, - /** * Gets all domains. * @@ -2553,13 +2521,13 @@ * @see {@link corbel.util.serializeParams} to see a example of the params */ getAll: function(params) { - corbel.validate.failIfIsDefined(this.domainId, 'This function not allowed domain identifier'); - console.log('iamInterface.domain.getAll'); + corbel.validate.failIfIsDefined(this.domainId, 'This function not allowed domain identifier') + console.log('iamInterface.domain.getAll') return this.request({ url: this._buildUri(this.uri), method: corbel.request.method.GET, query: params ? corbel.utils.serializeParams(params) : null - }); + }) }, /** @@ -2580,14 +2548,14 @@ * @return {Promise} A promise or fails with a {@link corbelError}. */ update: function(domain) { - console.log('iamInterface.domain.update', domain); - corbel.validate.value('domainId', this.domainId); + console.log('iamInterface.domain.update', domain) + corbel.validate.value('domainId', this.domainId) return this.request({ url: this._buildUri(this.uri + '/' + this.domainId), method: corbel.request.method.PUT, data: domain - }); + }) }, /** @@ -2601,31 +2569,31 @@ * @return {Promise} A promise or fails with a {@link corbelError}. */ remove: function() { - console.log('iamInterface.domain.remove', this.domainId); - corbel.validate.value('domainId', this.domainId); + console.log('iamInterface.domain.remove', this.domainId) + corbel.validate.value('domainId', this.domainId) return this.request({ url: this._buildUri(this.uri + '/' + this.domainId), method: corbel.request.method.DELETE - }); + }) } - }); - - })(); + }) + })() + /* global corbel */ + ; (function() { - /** * Creates a ScopeBuilder for scope managing requests. * @param {String} id Scope id. * @return {corbel.Iam.ScopeBuilder} */ corbel.Iam.prototype.scope = function(id) { - var scope = new ScopeBuilder(id); - scope.driver = this.driver; - return scope; - }; + var scope = new ScopeBuilder(id) + scope.driver = this.driver + return scope + } /** * A builder for scope management requests. @@ -2636,10 +2604,9 @@ * @memberOf iam */ var ScopeBuilder = corbel.Iam.ScopeBuilder = corbel.Services.inherit({ - constructor: function(id) { - this.id = id; - this.uri = 'scope'; + this.id = id + this.uri = 'scope' }, _buildUri: corbel.Iam._buildUri, @@ -2659,14 +2626,14 @@ * with a {@link corbelError}. */ create: function(scope) { - console.log('iamInterface.scope.create', scope); + console.log('iamInterface.scope.create', scope) return this.request({ url: this._buildUri(this.uri), method: corbel.request.method.POST, data: scope }).then(function(res) { - return corbel.Services.getLocationId(res); - }); + return corbel.Services.getLocationId(res) + }) }, /** @@ -2678,13 +2645,13 @@ * @return {Promise} A promise with the scope or fails with a {@link corbelError}. */ get: function() { - console.log('iamInterface.scope.get', this.id); - corbel.validate.value('id', this.id); + console.log('iamInterface.scope.get', this.id) + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri + '/' + this.id), method: corbel.request.method.GET - }); + }) }, /** @@ -2695,31 +2662,31 @@ * @return {Promise} A promise user or fails with a {@link corbelError}. */ remove: function() { - console.log('iamInterface.scope.remove', this.id); - corbel.validate.value('id', this.id); + console.log('iamInterface.scope.remove', this.id) + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri + '/' + this.id), method: corbel.request.method.DELETE - }); + }) } - }); - - })(); + }) + })() + /* global corbel */ + ; (function() { - /** * Creates a TokenBuilder for token requests * @return {corbel.Iam.TokenBuilder} */ corbel.Iam.prototype.token = function() { - var tokenBuilder = new TokenBuilder(this.driver); - tokenBuilder.driver = this.driver; - return tokenBuilder; - }; + var tokenBuilder = new TokenBuilder(this.driver) + tokenBuilder.driver = this.driver + return tokenBuilder + } /** * A builder for token requests @@ -2727,9 +2694,8 @@ * @memberOf Iam */ var TokenBuilder = corbel.Iam.TokenBuilder = corbel.Services.inherit({ - constructor: function() { - this.uri = 'oauth/token'; + this.uri = 'oauth/token' }, _buildUri: corbel.Iam._buildUri, @@ -2745,18 +2711,18 @@ * @return {String} JWT assertion */ _getJwt: function(params) { - params = params || {}; - params.claims = params.claims || {}; + params = params || {} + params.claims = params.claims || {} if (params.jwt) { - return params.jwt; + return params.jwt } - var secret = params.secret || this.driver.config.get('clientSecret'); - params.claims.iss = params.claims.iss || this.driver.config.get('clientId'); - params.claims.aud = params.claims.aud || this.driver.config.get('audience', corbel.Iam.AUD); - params.claims.scope = params.claims.scope || this.driver.config.get('scopes', ''); - return corbel.jwt.generate(params.claims, secret); + var secret = params.secret || this.driver.config.get('clientSecret') + params.claims.iss = params.claims.iss || this.driver.config.get('clientId') + params.claims.aud = params.claims.aud || this.driver.config.get('audience', corbel.Iam.AUD) + params.claims.scope = params.claims.scope || this.driver.config.get('scopes', '') + return corbel.jwt.generate(params.claims, secret) }, _doGetTokenRequest: function(uri, params, setCookie) { @@ -2768,15 +2734,15 @@ 'grant_type': corbel.Iam.GRANT_TYPE }, params.oauth)), withCredentials: true - }; + } if (setCookie) { args.headers = { RequestCookie: 'true' - }; + } } - return corbel.request.send(args); + return corbel.request.send(args) }, _doPostTokenRequest: function(uri, params, setCookie) { @@ -2789,14 +2755,14 @@ }, contentType: 'application/x-www-form-urlencoded; charset=UTF-8', withCredentials: true - }; + } if (setCookie) { args.headers = { RequestCookie: 'true' - }; + } } - return corbel.request.send(args); + return corbel.request.send(args) }, /** @@ -2810,47 +2776,45 @@ * * @param {string} params["oauth.service"] Service that will provide the authorization, e.g. facebook String * * @param {string} params["oauth.code"] Code used in OAuth2 for exanging for a token String only if OAuth2 - * @param {string} params["oauth.access_token"] Access token used in OAuth2 for authentication. WARNING!! It is not recommended to pass an access token directly from the client, the oauth.code claim should be used instead. String + * @param {string} params["oauth.access_token"] Access token used in OAuth2 for authentication. WARNING!! It is not recommended to pass an access token directly from the client, the oauth.code claim should be used instead String * @param {string} params["oauth.redirect_uri"] URI used by the client in OAuth2 to redirect the user when he does the login String only if OAuth2 * @param {string} params["oauth.token"] Token returned by OAuth1 server to the client when the user does the login String only if OAuth1 * @param {string} params["oauth.verifier"] Verifier returned by OAuth1 server to the client when the user does the login - * * @param {Boolean} [setCookie] Sends 'RequestCookie' to server * @return {Promise} Q promise that resolves to an AccessToken {Object} or rejects with a {@link corbelError} */ create: function(params, setCookie) { - params = params || {}; - // if there are oauth params this mean we should do use the GET verb - var promise; + params = params || {} + // if there are oauth params this mean we should do use the GET verb + var promise try { if (params.oauth) { - promise = this._doGetTokenRequest(this.uri, params, setCookie); + promise = this._doGetTokenRequest(this.uri, params, setCookie) } // otherwise we use the traditional POST verb. - promise = this._doPostTokenRequest(this.uri, params, setCookie); - + promise = this._doPostTokenRequest(this.uri, params, setCookie) } catch (e) { - console.log('error', e); - return Promise.reject(e); + console.log('error', e) + return Promise.reject(e) } - var that = this; + var that = this return promise.then(function(response) { - that.driver.config.set(corbel.Iam.IAM_TOKEN, response.data); - that.driver.config.set(corbel.Iam.IAM_DOMAIN, corbel.jwt.decode(response.data.accessToken).domainId); + that.driver.config.set(corbel.Iam.IAM_TOKEN, response.data) + that.driver.config.set(corbel.Iam.IAM_DOMAIN, corbel.jwt.decode(response.data.accessToken).domainId) if (params.jwt) { - that.driver.config.set(corbel.Iam.IAM_TOKEN_SCOPES, corbel.jwt.decode(params.jwt).scope); + that.driver.config.set(corbel.Iam.IAM_TOKEN_SCOPES, corbel.jwt.decode(params.jwt).scope) } if (params.claims) { if (params.claims.scope) { - that.driver.config.set(corbel.Iam.IAM_TOKEN_SCOPES, params.claims.scope); + that.driver.config.set(corbel.Iam.IAM_TOKEN_SCOPES, params.claims.scope) } else { - that.driver.config.set(corbel.Iam.IAM_TOKEN_SCOPES, that.driver.config.get('scopes', '')); + that.driver.config.set(corbel.Iam.IAM_TOKEN_SCOPES, that.driver.config.get('scopes', '')) } } - return response; - }); + return response + }) }, /** @@ -2862,48 +2826,45 @@ * @return {Promise} Q promise that resolves to an AccesToken {Object} or rejects with a {@link corbelError} */ refresh: function(refreshToken, scopes) { - // console.log('iamInterface.token.refresh', refreshToken); + // console.log('iamInterface.token.refresh', refreshToken) // we need refresh token to refresh access token - corbel.validate.isValue(refreshToken, 'Refresh access token request must contains refresh token'); - // we need create default claims to refresh access token + corbel.validate.isValue(refreshToken, 'Refresh access token request must contains refresh token') + // we need create default claims to refresh access token var params = { claims: { 'scope': scopes, 'refresh_token': refreshToken } - }; - var that = this; + } + var that = this try { - return this._doPostTokenRequest(this.uri, params) .then(function(response) { - that.driver.config.set(corbel.Iam.IAM_TOKEN, response.data); - return response; - }); - + that.driver.config.set(corbel.Iam.IAM_TOKEN, response.data) + return response + }) } catch (e) { - console.log('error', e); - return Promise.reject(e); + console.log('error', e) + return Promise.reject(e) } - } + }) + })() - }); - - })(); + /* global corbel */ + ; (function() { - /** * Starts a username request * @return {corbel.Iam.UsernameBuilder} The builder to create the request */ corbel.Iam.prototype.username = function() { - var username = new UsernameBuilder(); - username.driver = this.driver; - return username; - }; + var username = new UsernameBuilder() + username.driver = this.driver + return username + } /** * Builder for creating requests of users name @@ -2911,9 +2872,8 @@ * @memberOf iam */ var UsernameBuilder = corbel.Iam.UsernameBuilder = corbel.Services.inherit({ - constructor: function() { - this.uri = 'username'; + this.uri = 'username' }, _buildUri: corbel.Iam._buildUri, @@ -2926,20 +2886,20 @@ * @return {Promise} A promise which resolves into usename availability boolean state. */ availability: function(username) { - console.log('iamInterface.username.availability', username); - corbel.validate.value('username', username); + console.log('iamInterface.username.availability', username) + corbel.validate.value('username', username) return this.request({ url: this._buildUri(this.uri, username), method: corbel.request.method.HEAD }).then(function() { - return false; + return false }).catch(function(response) { if (response.status === 404) { - return true; + return true } else { - return Promise.reject(response); + return Promise.reject(response) } - }); + }) }, /** @@ -2953,50 +2913,50 @@ * @return {Promise} A promise with the user or fails with a {@link corbelError}. */ getUserId: function(username) { - console.log('iamInterface.username.getUserId', username); - corbel.validate.value('username', username); + console.log('iamInterface.username.getUserId', username) + corbel.validate.value('username', username) return this.request({ url: this._buildUri(this.uri, username), method: corbel.request.method.GET - }); + }) } - }); - - })(); + }) + })() + /* global corbel */ + ; (function() { - - /** + /* * Starts a user request * @param {string} [id=id|'me'] Id of the user to perform the request * @return {corbel.Iam.UserBuilder|corbel.Iam.UserMeBuilder} The builder to create the request */ corbel.Iam.prototype.user = function(id) { - var builder; + var builder if (id === 'me') { - builder = new UserBuilder('me'); + builder = new UserBuilder('me') } else if (id) { - builder = new UserBuilder(id); + builder = new UserBuilder(id) } else { - builder = new UserMeBuilder('me'); + builder = new UserMeBuilder('me') } - builder.driver = this.driver; - return builder; - }; + builder.driver = this.driver + return builder + } /** * Starts a users request * @return {corbel.Iam.UserBuilder|corbel.Iam.UsersBuilder} The builder to create the request */ corbel.Iam.prototype.users = function() { - var builder = new UsersBuilder(); + var builder = new UsersBuilder() - builder.driver = this.driver; - return builder; - }; + builder.driver = this.driver + return builder + } /** * getUser mixin for UserBuilder & UsersBuilder @@ -3006,12 +2966,12 @@ * @return {Promise} */ corbel.Iam._getUser = function(method, uri, id, postfix) { - var url = (postfix ? this._buildUri(uri, id) + postfix : this._buildUri(uri, id)); + var url = (postfix ? this._buildUri(uri, id) + postfix : this._buildUri(uri, id)) return this.request({ url: url, method: corbel.request.method.GET - }); - }; + }) + } /** * Builder for a specific user requests @@ -3020,10 +2980,9 @@ * @param {string} id The id of the user */ var CommonUserBuilder = corbel.Iam.CommonUserBuilder = corbel.Services.inherit({ - constructor: function(id) { - this.uri = 'user'; - this.id = id; + this.uri = 'user' + this.id = id }, _buildUri: corbel.Iam._buildUri, @@ -3036,27 +2995,27 @@ * @return {Promise} Q promise that resolves to a User {Object} or rejects with a {@link corbelError} */ get: function() { - console.log('iamInterface.user.get'); - corbel.validate.value('id', this.id); - return this._getUser(corbel.request.method.GET, this.uri, this.id); + console.log('iamInterface.user.get') + corbel.validate.value('id', this.id) + return this._getUser(corbel.request.method.GET, this.uri, this.id) }, /** * Updates the user * @method * @memberOf corbel.Iam.UserBuilder - * @param {Object} data The data to update - * @return {Promise} Q promise that resolves to undefined (void) or rejects with a {@link corbelError} + * @param {Object} The data to update + * @return {Promise} promise that resolves to undefined (void) or rejects with a {@link corbelError} */ _update: function(data) { - console.log('iamInterface.user.update', data); - corbel.validate.value('id', this.id); + console.log('iamInterface.user.update', data) + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id), method: corbel.request.method.PUT, data: data - }); + }) }, /** @@ -3066,31 +3025,31 @@ * @return {Promise} Q promise that resolves to undefined (void) or rejects with a {@link corbelError} */ _delete: function() { - console.log('iamInterface.user.delete'); - corbel.validate.value('id', this.id); + console.log('iamInterface.user.delete') + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id), method: corbel.request.method.DELETE - }); + }) }, /** * Sign Out the logged user. * @example - * iam().user('me').signOut(); + * iam().user('me').signOut() * @method * @memberOf corbel.Iam.UsersBuilder * @return {Promise} Q promise that resolves to a User {Object} or rejects with a {@link corbelError} */ _signOut: function() { - console.log('iamInterface.users.signOutMe'); - corbel.validate.value('id', this.id); + console.log('iamInterface.users.signOutMe') + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id) + '/signout', method: corbel.request.method.PUT - }); + }) }, /** @@ -3100,13 +3059,13 @@ * @return {Promise} Q promise that resolves to undefined (void) or rejects with a {@link corbelError} */ _disconnect: function() { - console.log('iamInterface.user.disconnect'); - corbel.validate.value('id', this.id); + console.log('iamInterface.user.disconnect') + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id) + '/disconnect', method: corbel.request.method.PUT - }); + }) }, /** @@ -3119,15 +3078,15 @@ * @return {Promise} Q promise that resolves to undefined (void) or rejects with a {@link corbelError} */ addIdentity: function(identity) { - // console.log('iamInterface.user.addIdentity', identity); - corbel.validate.isValue(identity, 'Missing identity'); - corbel.validate.value('id', this.id); + // console.log('iamInterface.user.addIdentity', identity) + corbel.validate.isValue(identity, 'Missing identity') + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id) + '/identity', method: corbel.request.method.POST, data: identity - }); + }) }, /** @@ -3137,13 +3096,13 @@ * @return {Promise} Q promise that resolves to {Array} of Identity or rejects with a {@link corbelError} */ _getIdentities: function() { - console.log('iamInterface.user.getIdentities'); - corbel.validate.value('id', this.id); + console.log('iamInterface.user.getIdentities') + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id) + '/identity', method: corbel.request.method.GET - }); + }) }, /** * User device register @@ -3156,16 +3115,16 @@ * @return {Promise} Q promise that resolves to a User {Object} or rejects with a {@link corbelError} */ _registerDevice: function(data) { - console.log('iamInterface.user.registerDevice'); - corbel.validate.value('id', this.id); + console.log('iamInterface.user.registerDevice') + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id) + '/devices', method: corbel.request.method.PUT, data: data }).then(function(res) { - return corbel.Services.getLocationId(res); - }); + return corbel.Services.getLocationId(res) + }) }, /** @@ -3176,16 +3135,16 @@ * @return {Promise} Q promise that resolves to a Device {Object} or rejects with a {@link corbelError} */ _getDevice: function(deviceId) { - console.log('iamInterface.user.getDevice'); + console.log('iamInterface.user.getDevice') corbel.validate.values(['id', 'deviceId'], { 'id': this.id, 'deviceId': deviceId - }); + }) return this.request({ url: this._buildUri(this.uri, this.id) + '/devices/' + deviceId, method: corbel.request.method.GET - }); + }) }, /** @@ -3195,12 +3154,12 @@ * @return {Promise} Q promise that resolves to a Device {Object} or rejects with a {@link corbelError} */ _getDevices: function() { - console.log('iamInterface.user.getDevices'); - corbel.validate.value('id', this.id); + console.log('iamInterface.user.getDevices') + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id) + '/devices/', method: corbel.request.method.GET - }); + }) }, /** @@ -3211,12 +3170,12 @@ * @return {Promise} Q promise that resolves to a Device {Object} or rejects with a {@link corbelError} */ _deleteDevice: function(deviceId) { - console.log('iamInterface.user.deleteDevice'); - corbel.validate.value('deviceId', deviceId); + console.log('iamInterface.user.deleteDevice') + corbel.validate.value('deviceId', deviceId) return this.request({ url: this._buildUri(this.uri, this.id) + '/devices/' + deviceId, method: corbel.request.method.DELETE - }); + }) }, /** * Get user profiles @@ -3225,13 +3184,13 @@ * @return {Promise} Q promise that resolves to a User Profile or rejects with a {@link corbelError} */ _getProfile: function() { - console.log('iamInterface.user.getProfile'); - corbel.validate.value('id', this.id); + console.log('iamInterface.user.getProfile') + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id) + '/profile', method: corbel.request.method.GET - }); + }) }, /** @@ -3242,14 +3201,14 @@ * @return {Promise} Q promise that resolves to undefined (void) or rejects with a {@link SilkRoadError} */ addGroups: function(groups) { - console.log('iamInterface.user.addGroups'); - corbel.validate.value('id', this.id); + console.log('iamInterface.user.addGroups') + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id) + '/groups', method: corbel.request.method.PUT, data: groups - }); + }) }, /** @@ -3260,90 +3219,90 @@ * @return {Promise} Q promise that resolves to undefined (void) or rejects with a {@link SilkRoadError} */ _deleteGroup: function(group) { - console.log('iamInterface.user.deleteGroup'); + console.log('iamInterface.user.deleteGroup') corbel.validate.values(['id', 'group'], { 'id': this.id, 'group': group - }); + }) return this.request({ url: this._buildUri(this.uri, this.id) + '/groups/' + group, method: corbel.request.method.DELETE - }); + }) } - }); + }) - var UserBuilder = corbel.Iam.CommonUserBuilder.inherit({ + var UserBuilder = CommonUserBuilder.inherit({ deleteGroup: function() { - return this._deleteGroup.apply(this, arguments); + return this._deleteGroup.apply(this, arguments) }, update: function() { - return this._update.apply(this, arguments); + return this._update.apply(this, arguments) }, delete: function() { - return this._delete.apply(this, arguments); + return this._delete.apply(this, arguments) }, registerDevice: function() { - return this._registerDevice.apply(this, arguments); + return this._registerDevice.apply(this, arguments) }, getDevices: function() { - return this._getDevices.apply(this, arguments); + return this._getDevices.apply(this, arguments) }, getDevice: function() { - return this._getDevice.apply(this, arguments); + return this._getDevice.apply(this, arguments) }, deleteDevice: function() { - return this._deleteDevice.apply(this, arguments); + return this._deleteDevice.apply(this, arguments) }, signOut: function() { - return this._signOut.apply(this, arguments); + return this._signOut.apply(this, arguments) }, disconnect: function() { - return this._disconnect.apply(this, arguments); + return this._disconnect.apply(this, arguments) }, getIdentities: function() { - return this._getIdentities.apply(this, arguments); + return this._getIdentities.apply(this, arguments) }, getProfile: function() { - return this._getProfile.apply(this, arguments); + return this._getProfile.apply(this, arguments) } - }); + }) - var UserMeBuilder = corbel.Iam.CommonUserBuilder.inherit({ + var UserMeBuilder = CommonUserBuilder.inherit({ deleteMyGroup: function() { - return this._deleteGroup.apply(this, arguments); + return this._deleteGroup.apply(this, arguments) }, updateMe: function() { - return this._update.apply(this, arguments); + return this._update.apply(this, arguments) }, deleteMe: function() { - return this._delete.apply(this, arguments); + return this._delete.apply(this, arguments) }, registerMyDevice: function() { - return this._registerDevice.apply(this, arguments); + return this._registerDevice.apply(this, arguments) }, getMyDevices: function() { - return this._getDevices.apply(this, arguments); + return this._getDevices.apply(this, arguments) }, getMyDevice: function() { - return this._getDevice.apply(this, arguments); + return this._getDevice.apply(this, arguments) }, deleteMyDevice: function() { - return this._deleteDevice.apply(this, arguments); + return this._deleteDevice.apply(this, arguments) }, signOutMe: function() { - return this._signOut.apply(this, arguments); + return this._signOut.apply(this, arguments) }, disconnectMe: function() { - return this._disconnect.apply(this, arguments); + return this._disconnect.apply(this, arguments) }, getMyIdentities: function() { - return this._getIdentities.apply(this, arguments); + return this._getIdentities.apply(this, arguments) }, getMyProfile: function() { - return this._getProfile.apply(this, arguments); + return this._getProfile.apply(this, arguments) } - }); + }) /** * Builder for creating requests of users collection @@ -3351,9 +3310,8 @@ * @memberOf iam */ var UsersBuilder = corbel.Iam.UsersBuilder = corbel.Services.inherit({ - constructor: function() { - this.uri = 'user'; + this.uri = 'user' }, _buildUri: corbel.Iam._buildUri, @@ -3366,15 +3324,15 @@ * @return {Promise} Q promise that resolves to undefined (void) or rejects with a {@link corbelError} */ sendResetPasswordEmail: function(userEmailToReset) { - console.log('iamInterface.users.sendResetPasswordEmail', userEmailToReset); - var query = 'email=' + userEmailToReset; + console.log('iamInterface.users.sendResetPasswordEmail', userEmailToReset) + var query = 'email=' + userEmailToReset return this.request({ url: this._buildUri(this.uri + '/resetPassword'), method: corbel.request.method.GET, query: query }).then(function(res) { - return corbel.Services.getLocationId(res); - }); + return corbel.Services.getLocationId(res) + }) }, /** @@ -3385,14 +3343,14 @@ * @return {Promise} A promise which resolves into the ID of the created user or fails with a {@link corbelError}. */ create: function(data) { - console.log('iamInterface.users.create', data); + console.log('iamInterface.users.create', data) return this.request({ url: this._buildUri(this.uri), method: corbel.request.method.POST, data: data }).then(function(res) { - return corbel.Services.getLocationId(res); - }); + return corbel.Services.getLocationId(res) + }) }, /** @@ -3402,45 +3360,46 @@ * @return {Promise} Q promise that resolves to an {Array} of Users or rejects with a {@link corbelError} */ get: function(params) { - console.log('iamInterface.users.get', params); + console.log('iamInterface.users.get', params) return this.request({ url: this._buildUri(this.uri), method: corbel.request.method.GET, query: params ? corbel.utils.serializeParams(params) : null - }); + }) }, getProfiles: function(params) { - console.log('iamInterface.users.getProfiles', params); + console.log('iamInterface.users.getProfiles', params) return this.request({ url: this._buildUri(this.uri) + '/profile', method: corbel.request.method.GET, - query: params ? corbel.utils.serializeParams(params) : null //TODO cambiar por util e implementar dicho metodo - }); + query: params ? corbel.utils.serializeParams(params) : null // TODO cambiar por util e implementar dicho metodo + }) } - }); - })(); + }) + })() + /* global corbel */ + ; (function() { - /** * Creates a GroupBuilder for group requests * * @return {iam.GroupBuilder | iam.GroupsBuilder} */ corbel.Iam.prototype.group = function(id) { - var builder; + var builder if (id) { - builder = new GroupBuilder(id); + builder = new GroupBuilder(id) } else { - builder = new GroupsBuilder(); + builder = new GroupsBuilder() } - builder.driver = this.driver; - return builder; - }; + builder.driver = this.driver + return builder + } /** * A builder for group requests without id (getAll and creation). @@ -3449,9 +3408,8 @@ * @memberOf iam */ var GroupsBuilder = corbel.Iam.GroupsBuilder = corbel.Services.inherit({ - constructor: function() { - this.uri = 'group'; + this.uri = 'group' }, _buildUri: corbel.Iam._buildUri, @@ -3467,13 +3425,13 @@ * @return {Promise} Q promise that resolves to an array of groups. */ getAll: function(params) { - console.log('iamInterface.groups.getAll'); + console.log('iamInterface.groups.getAll') return this.request({ url: this._buildUri(this.uri), method: corbel.request.method.GET, query: params ? corbel.utils.serializeParams(params) : null, withAuth: true - }); + }) }, /** @@ -3490,18 +3448,18 @@ * @return {Promise} A promise which resolves into the ID of the created group or fails with a {@link SilkRoadError}. */ create: function(data) { - console.log('iamInterface.groups.create', data); + console.log('iamInterface.groups.create', data) return this.request({ url: this._buildUri(this.uri), method: corbel.request.method.POST, data: data, withAuth: true }).then(function(res) { - return corbel.Services.getLocationId(res); - }); + return corbel.Services.getLocationId(res) + }) } - }); + }) /** * A builder for group requests. @@ -3511,10 +3469,9 @@ * @param {String} id The id of the group. */ var GroupBuilder = corbel.Iam.GroupBuilder = corbel.Services.inherit({ - constructor: function(id) { - this.uri = 'group'; - this.id = id; + this.uri = 'group' + this.id = id }, _buildUri: corbel.Iam._buildUri, @@ -3527,13 +3484,13 @@ * @return {Promise} Q promise that resolves to a group or rejects with a {@link SilkRoadError}. */ get: function() { - console.log('iamInterface.group.get'); - corbel.validate.value('id', this.id); + console.log('iamInterface.group.get') + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id), method: corbel.request.method.GET, withAuth: true - }); + }) }, /** @@ -3547,15 +3504,15 @@ * @return {Promise} A promise which resolves to undefined(void) or fails with a {@link SilkRoadError}. */ addScopes: function(scopes) { - console.log('iamInterface.group.addScopes', scopes); - corbel.validate.value('id', this.id); + console.log('iamInterface.group.addScopes', scopes) + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id) + '/scopes', method: corbel.request.method.PUT, data: scopes, withAuth: true - }); + }) }, /** @@ -3569,14 +3526,14 @@ * @return {Promise} A promise which resolves to undefined(void) or fails with a {@link SilkRoadError}. */ removeScope: function(scope) { - console.log('iamInterface.group.removeScope', scope); - corbel.validate.value('id', this.id); + console.log('iamInterface.group.removeScope', scope) + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id) + '/scopes/' + scope, method: corbel.request.method.DELETE, withAuth: true - }); + }) }, /** @@ -3587,33 +3544,33 @@ * @return {Promise} A promise which resolves to undefined(void) or fails with a {@link SilkRoadError}. */ delete: function() { - console.log('iamInterface.group.delete'); - corbel.validate.value('id', this.id); + console.log('iamInterface.group.delete') + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id), method: corbel.request.method.DELETE, withAuth: true - }); + }) } - }); - - })(); + }) + })() + /* global corbel */ + ; (function() { - /** * Creates a EmailBuilder for email requests * @return {corbel.Iam.EmailBuilder} */ corbel.Iam.prototype.email = function() { - var builder; - builder = new EmailBuilder(); - builder.driver = this.driver; - return builder; - }; + var builder + builder = new EmailBuilder() + builder.driver = this.driver + return builder + } /** * Builder for creating requests of email @@ -3621,9 +3578,8 @@ * @memberOf iam */ var EmailBuilder = corbel.Iam.EmailBuilder = corbel.Services.inherit({ - constructor: function() { - this.uri = 'email'; + this.uri = 'email' }, _buildUri: corbel.Iam._buildUri, @@ -3639,13 +3595,13 @@ * @return {Promise} A promise with the user or fails with a {@link corbelError}. */ getUserId: function(email) { - console.log('iamInterface.email.getUserId', email); - corbel.validate.value('email', email); + console.log('iamInterface.email.getUserId', email) + corbel.validate.value('email', email) return this.request({ url: this._buildUri(this.uri, email), method: corbel.request.method.GET - }); + }) }, /** @@ -3656,33 +3612,31 @@ * @return {Promise} A promise which resolves into email availability boolean state. */ availability: function(email) { - console.log('iamInterface.email.availability', email); - corbel.validate.value('email', email); + console.log('iamInterface.email.availability', email) + corbel.validate.value('email', email) return this.request({ url: this._buildUri(this.uri, email), method: corbel.request.method.HEAD }).then( function() { - return false; + return false }, function(response) { if (response.status === 404) { - return true; + return true } else { - return Promise.reject(response); + return Promise.reject(response) } } - ); + ) } - }); - })(); - + }) + })() var aggregationBuilder = (function() { - - var aggregationBuilder = {}; + var aggregationBuilder = {} /** * Adds a count operation to aggregation @@ -3690,19 +3644,19 @@ * @return {RequestParamsBuilder} RequestParamsBuilder */ aggregationBuilder.count = function(field) { - this.params.aggregation = this.params.aggregation || {}; - this.params.aggregation.$count = field; - return this; - }; + this.params.aggregation = this.params.aggregation || {} + this.params.aggregation.$count = field + return this + } - return aggregationBuilder; + return aggregationBuilder + })() - })(); + module.exports = aggregationBuilder var queryBuilder = (function() { - - var queryBuilder = {}; + var queryBuilder = {} /** * Adds an Equal criteria to query @@ -3711,9 +3665,9 @@ * @return {RequestParamsBuilder} RequestParamsBuilder */ queryBuilder.eq = function(field, value) { - this.addCriteria('$eq', field, value); - return this; - }; + this.addCriteria('$eq', field, value) + return this + } /** * Adds a Greater Than criteria to query @@ -3722,9 +3676,9 @@ * @return {RequestParamsBuilder} RequestParamsBuilder */ queryBuilder.gt = function(field, value) { - this.addCriteria('$gt', field, value); - return this; - }; + this.addCriteria('$gt', field, value) + return this + } /** * Adds a Greater Than Or Equal criteria to query @@ -3733,9 +3687,9 @@ * @return {RequestParamsBuilder} RequestParamsBuilder */ queryBuilder.gte = function(field, value) { - this.addCriteria('$gte', field, value); - return this; - }; + this.addCriteria('$gte', field, value) + return this + } /** * Adds a Less Than criteria to query @@ -3744,9 +3698,9 @@ * @return {RequestParamsBuilder} RequestParamsBuilder */ queryBuilder.lt = function(field, value) { - this.addCriteria('$lt', field, value); - return this; - }; + this.addCriteria('$lt', field, value) + return this + } /** * Adds a Less Than Or Equal criteria to query @@ -3755,9 +3709,9 @@ * @return {RequestParamsBuilder} RequestParamsBuilder */ queryBuilder.lte = function(field, value) { - this.addCriteria('$lte', field, value); - return this; - }; + this.addCriteria('$lte', field, value) + return this + } /** * Adds a Not Equal criteria to query @@ -3766,9 +3720,9 @@ * @return {RequestParamsBuilder} RequestParamsBuilder */ queryBuilder.ne = function(field, value) { - this.addCriteria('$ne', field, value); - return this; - }; + this.addCriteria('$ne', field, value) + return this + } /** * Adds a Like criteria to query @@ -3777,9 +3731,9 @@ * @return {RequestParamsBuilder} RequestParamsBuilder */ queryBuilder.like = function(field, value) { - this.addCriteria('$like', field, value); - return this; - }; + this.addCriteria('$like', field, value) + return this + } /** * Adds an In criteria to query @@ -3788,9 +3742,9 @@ * @return {RequestParamsBuilder} RequestParamsBuilder */ queryBuilder.in = function(field, values) { - this.addCriteria('$in', field, values); - return this; - }; + this.addCriteria('$in', field, values) + return this + } /** * Adds an All criteria to query @@ -3799,9 +3753,9 @@ * @return {RequestParamsBuilder} RequestParamsBuilder */ queryBuilder.all = function(field, values) { - this.addCriteria('$all', field, values); - return this; - }; + this.addCriteria('$all', field, values) + return this + } /** * Adds an Element Match criteria to query @@ -3810,36 +3764,36 @@ * @return {RequestParamsBuilder} RequestParamsBuilder */ queryBuilder.elemMatch = function(field, query) { - this.addCriteria('$elem_match', field, query); - return this; - }; + this.addCriteria('$elem_match', field, query) + return this + } /** * Sets an specific queryDomain, by default 'api'. * @param {String} queryDomain query domain name, 'api' and '7digital' supported */ queryBuilder.setQueryDomain = function(queryDomain) { - this.params.queryDomain = queryDomain; - return this; - }; + this.params.queryDomain = queryDomain + return this + } queryBuilder.addCriteria = function(operator, field, value) { - var criteria = {}; - criteria[operator] = {}; - criteria[operator][field] = value; - this.params.query = this.params.query || []; - this.params.query.push(criteria); - return this; - }; + var criteria = {} + criteria[operator] = {} + criteria[operator][field] = value + this.params.query = this.params.query || [] + this.params.query.push(criteria) + return this + } - return queryBuilder; + return queryBuilder + })() - })(); + module.exports = queryBuilder var pageBuilder = (function() { - - var pageBuilder = {}; + var pageBuilder = {} /** * Sets the page number of the page param @@ -3847,10 +3801,10 @@ * @return {RequestParamsBuilder} RequestParamsBuilder */ pageBuilder.page = function(page) { - this.params.pagination = this.params.pagination || {}; - this.params.pagination.page = page; - return this; - }; + this.params.pagination = this.params.pagination || {} + this.params.pagination.page = page + return this + } /** * Sets the page size of the page param @@ -3858,10 +3812,10 @@ * @return {RequestParamsBuilder} RequestParamsBuilder */ pageBuilder.pageSize = function(pageSize) { - this.params.pagination = this.params.pagination || {}; - this.params.pagination.pageSize = pageSize; - return this; - }; + this.params.pagination = this.params.pagination || {} + this.params.pagination.pageSize = pageSize + return this + } /** * Sets the page number and page size of the page param @@ -3869,51 +3823,54 @@ * @return {RequestParamsBuilder} RequestParamsBuilder */ pageBuilder.pageParam = function(page, pageSize) { - this.params.pagination = this.params.pagination || {}; - this.params.pagination.page = page; - this.params.pagination.pageSize = pageSize; - return this; - }; - - return pageBuilder; - + this.params.pagination = this.params.pagination || {} + this.params.pagination.page = page + this.params.pagination.pageSize = pageSize + return this + } - })(); + return pageBuilder + })() + module.exports = pageBuilder + /* global corbel */ var sortBuilder = (function() { - - var sortBuilder = {}; + var sortBuilder = {} /** * Sets ascending direction to sort param * @return {RequestParamsBuilder} RequestParamsBuilder */ sortBuilder.asc = function(field) { - this.params.sort = this.params.sort || {}; - this.params.sort[field] = corbel.Resources.sort.ASC; - return this; - }; + this.params.sort = this.params.sort || {} + this.params.sort[field] = corbel.Resources.sort.ASC + return this + } /** * Sets descending direction to sort param * @return {RequestParamsBuilder} RequestParamsBuilder */ sortBuilder.desc = function(field) { - this.params.sort = this.params.sort || {}; - this.params.sort[field] = corbel.Resources.sort.DESC; - return this; - }; - - return sortBuilder; - })(); - + this.params.sort = this.params.sort || {} + this.params.sort[field] = corbel.Resources.sort.DESC + return this + } - (function(aggregationBuilder, queryBuilder, sortBuilder, pageBuilder) { + return sortBuilder + })() + module.exports = sortBuilder + var aggregationBuilder = require('./aggregationBuilder') + var pageBuilder = require('./pageBuilder') + var queryBuilder = require('./queryBuilder') + var sortBuilder = require('./sortBuilder') + ; + (function(aggregationBuilder, queryBuilder, sortBuilder, pageBuilder) { /** * A module to build Request Params * @exports requestParamsBuilder @@ -3922,25 +3879,26 @@ */ corbel.requestParamsBuilder = corbel.Object.inherit({ constructor: function() { - this.params = {}; + this.params = {} }, /** * Returns the JSON representation of the params * @return {JSON} representation of the params */ build: function() { - return this.params; + return this.params } - }); + }) + corbel.utils.extend(corbel.requestParamsBuilder.prototype, queryBuilder, sortBuilder, aggregationBuilder, pageBuilder) - corbel.utils.extend(corbel.requestParamsBuilder.prototype, queryBuilder, sortBuilder, aggregationBuilder, pageBuilder); + return corbel.requestParamsBuilder + })(aggregationBuilder, queryBuilder, sortBuilder, pageBuilder) - return corbel.requestParamsBuilder; + /* global corbel */ - })(aggregationBuilder, queryBuilder, sortBuilder, pageBuilder); + ; (function() { - /** * An assets API factory * @exports corbel.Assets @@ -3949,7 +3907,6 @@ * @memberof corbel */ corbel.Assets = corbel.Object.inherit({ - /** * Creates a new AssetsBuilder * @memberof corbel.Assets.prototype @@ -3957,15 +3914,14 @@ * @return {corbel.Assets.AssetsBuilder} */ constructor: function(driver) { - this.driver = driver; + this.driver = driver }, asset: function(id) { - return new corbel.Assets.AssetsBuilder(this.driver, id); + return new corbel.Assets.AssetsBuilder(this.driver, id) } }, { - /** * moduleName constant * @constant @@ -3991,18 +3947,18 @@ * @return {corbel.Assets.AssetsBuilder} */ create: function(driver) { - return new corbel.Assets(driver); + return new corbel.Assets(driver) } - }); - - return corbel.Assets; + }) - })(); + return corbel.Assets + })() + /* global corbel */ + ; (function() { - /** * Module for organize user assets * @exports AssetsBuilder @@ -4011,7 +3967,6 @@ * @memberof corbel.Assets */ var AssetsBuilder = corbel.Assets.AssetsBuilder = corbel.Services.inherit({ - /** * Creates a new AssetsBuilder * @memberof corbel.Assets.AssetsBuilder.prototype @@ -4019,9 +3974,9 @@ * @return {corbel.Assets.AssetsBuilder} */ constructor: function(driver, id) { - this.driver = driver; - this.uri = 'asset'; - this.id = id; + this.driver = driver + this.uri = 'asset' + this.id = id }, /** @@ -4031,17 +3986,15 @@ * @return {Promise} Promise that resolves with an Asset or rejects with a {@link CorbelError} */ get: function(params) { - - var options = params ? corbel.utils.clone(params) : {}; + var options = params ? corbel.utils.clone(params) : {} var args = corbel.utils.extend(options, { url: this._buildUri(this.uri, this.id), method: corbel.request.method.GET, query: params ? corbel.utils.serializeParams(params) : null - }); - - return this.request(args); + }) + return this.request(args) }, /** @@ -4051,14 +4004,14 @@ * @return {Promise} Promise that resolves with an Asset or rejects with a {@link CorbelError} */ getAll: function(params) { - var options = params ? corbel.utils.clone(params) : {}; + var options = params ? corbel.utils.clone(params) : {} var args = corbel.utils.extend(options, { url: this._buildUri(this.uri, 'all'), method: corbel.request.method.GET, query: params ? corbel.utils.serializeParams(params) : null - }); - return this.request(args); + }) + return this.request(args) }, /** @@ -4067,11 +4020,11 @@ * @return {Promise} Promise that resolves to undefined (void) or rejects with a {@link CorbelError} */ delete: function() { - corbel.validate.value('id', this.id); + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id), method: corbel.request.method.DELETE - }); + }) }, /** @@ -4090,10 +4043,9 @@ url: this._buildUri(this.uri), method: corbel.request.method.POST, data: data - }). - then(function(res) { - return corbel.Services.getLocationId(res); - }); + }).then(function(res) { + return corbel.Services.getLocationId(res) + }) }, /** @@ -4102,42 +4054,40 @@ * @return {Promise} Promise that resolves to a redirection to iam/oauth/token/upgrade or rejects with a {@link CorbelError} */ access: function(params) { - var args = params ? corbel.utils.clone(params) : {}; - args.url = this._buildUri(this.uri + '/access'); - args.method = corbel.request.method.GET; - args.noRedirect = true; + var args = params ? corbel.utils.clone(params) : {} + args.url = this._buildUri(this.uri + '/access') + args.method = corbel.request.method.GET + args.noRedirect = true - var that = this; + var that = this - return this.request(args). - then(function(response) { + return this.request(args).then(function(response) { return that.request({ noRetry: args.noRetry, method: corbel.request.method.POST, contentType: 'application/x-www-form-urlencoded; charset=UTF-8', data: response.data, url: response.headers.location - }); - }); + }) + }) }, _buildUri: function(path, id) { - var uri = ''; - var urlBase = this.driver.config.getCurrentEndpoint(corbel.Assets.moduleName, this._buildPort(this.driver.config)); + var uri = '' + var urlBase = this.driver.config.getCurrentEndpoint(corbel.Assets.moduleName, this._buildPort(this.driver.config)) - uri = urlBase + path; + uri = urlBase + path if (id) { - uri += '/' + id; + uri += '/' + id } - return uri; + return uri }, _buildPort: function(config) { - return config.get('assetsPort', null) || corbel.Assets.defaultPort; + return config.get('assetsPort', null) || corbel.Assets.defaultPort } }, { - /** * GET constant * @constant @@ -4154,152 +4104,145 @@ * @default */ create: function(driver) { - return new corbel.Assets.AssetsBuilder(driver); + return new corbel.Assets.AssetsBuilder(driver) } - }); + }) - return AssetsBuilder; - - })(); + return AssetsBuilder + })() + ; (function() { corbel.Scheduler = corbel.Object.inherit({ - /** * Create a new SchedulerBuilder * @param {String} type String * @return {Scheduler} */ constructor: function(driver) { - this.driver = driver; + this.driver = driver }, task: function(id) { - return new corbel.Scheduler.TaskBuilder(this.driver, id); + return new corbel.Scheduler.TaskBuilder(this.driver, id) } }, { - moduleName: 'scheduler', defaultPort: 8098, create: function(driver) { - return new corbel.Scheduler(driver); + return new corbel.Scheduler(driver) } - }); + }) - return corbel.Scheduler; - })(); + return corbel.Scheduler + })() + /*globals corbel */ + ; (function() { - var TaskBuilder = corbel.Scheduler.TaskBuilder = corbel.Services.inherit({ - constructor: function(driver, id) { - this.uri = 'tasks'; - this.driver = driver; - this.id = id; + this.uri = 'tasks' + this.driver = driver + this.id = id }, create: function(task) { - console.log('schedulerInterface.task.create', task); + console.log('schedulerInterface.task.create', task) return this.request({ url: this._buildUri(this.uri), method: corbel.request.method.POST, data: task - }). - then(function(res) { - return corbel.Services.getLocationId(res); - }); + }).then(function(res) { + return corbel.Services.getLocationId(res) + }) }, get: function(params) { - console.log('schedulerInterface.task.get', params); - corbel.validate.value('id', this.id); + console.log('schedulerInterface.task.get', params) + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id), method: corbel.request.method.GET, query: params ? corbel.utils.serializeParams(params) : null - }); + }) }, update: function(task) { - console.log('schedulerInterface.task.update', task); - corbel.validate.value('id', this.id); + console.log('schedulerInterface.task.update', task) + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id), method: corbel.request.method.PUT, data: task - }); + }) }, delete: function() { - console.log('schedulerInterface.task.delete'); - corbel.validate.value('id', this.id); + console.log('schedulerInterface.task.delete') + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id), method: corbel.request.method.DELETE - }); + }) }, _buildUri: function(path, id) { - var uri = ''; - var urlBase = this.driver.config.getCurrentEndpoint(corbel.Scheduler.moduleName, this._buildPort(this.driver.config)); + var uri = '' + var urlBase = this.driver.config.getCurrentEndpoint(corbel.Scheduler.moduleName, this._buildPort(this.driver.config)) - uri = urlBase + path; + uri = urlBase + path if (id) { - uri += '/' + id; + uri += '/' + id } - return uri; + return uri }, _buildPort: function(config) { - return config.get('schedulerPort', null) || corbel.Notifications.defaultPort; + return config.get('schedulerPort', null) || corbel.Notifications.defaultPort } }, { - moduleName: 'tasks', create: function(driver) { - return new corbel.TaskBuilder(driver); + return new corbel.TaskBuilder(driver) } - }); - - return TaskBuilder; + }) - })(); + return TaskBuilder + })() + ; (function() { corbel.Resources = corbel.Object.inherit({ - constructor: function(driver) { - this.driver = driver; + this.driver = driver }, collection: function(type) { - return new corbel.Resources.Collection(type, this.driver); + return new corbel.Resources.Collection(type, this.driver) }, resource: function(type, id) { - return new corbel.Resources.Resource(type, id, this.driver); + return new corbel.Resources.Resource(type, id, this.driver) }, relation: function(srcType, srcId, destType) { - return new corbel.Resources.Relation(srcType, srcId, destType, this.driver); + return new corbel.Resources.Relation(srcType, srcId, destType, this.driver) } }, { - moduleName: 'resources', defaultPort: 8080, sort: { - /** * Ascending sort * @type {String} @@ -4325,19 +4268,19 @@ ALL: '_', create: function(driver) { - return new corbel.Resources(driver); + return new corbel.Resources(driver) } - }); + }) - return corbel.Resources; + return corbel.Resources + })() - })(); + /* global corbel */ + ; (function() { - corbel.Resources.BaseResource = corbel.Services.inherit({ - /** * Helper function to build the request uri * @param {String} srcType Type of the resource @@ -4347,63 +4290,62 @@ * @return {String} Uri to perform the request */ buildUri: function(srcType, srcId, destType, destId) { + var urlBase = this.driver.config.getCurrentEndpoint(corbel.Resources.moduleName, this._buildPort(this.driver.config)) - var urlBase = this.driver.config.getCurrentEndpoint(corbel.Resources.moduleName, this._buildPort(this.driver.config)); - - var domain = this.driver.config.get(corbel.Iam.IAM_DOMAIN, 'unauthenticated'); - var customDomain = this.driver.config.get(corbel.Domain.CUSTOM_DOMAIN, domain); + var domain = this.driver.config.get(corbel.Iam.IAM_DOMAIN, 'unauthenticated') + var customDomain = this.driver.config.get(corbel.Domain.CUSTOM_DOMAIN, domain) - this.driver.config.set(corbel.Domain.CUSTOM_DOMAIN, undefined); + this.driver.config.set(corbel.Domain.CUSTOM_DOMAIN, undefined) - var uri = urlBase + customDomain + '/resource/' + srcType; + var uri = urlBase + customDomain + '/resource/' + srcType if (srcId) { - uri += '/' + srcId; + uri += '/' + srcId if (destType) { - uri += '/' + destType; + uri += '/' + destType if (destId) { - uri += ';r=' + destType + '/' + destId; + uri += ';r=' + destType + '/' + destId } } } - return uri; + return uri }, _buildPort: function(config) { - return config.get('resourcesPort', null) || corbel.Resources.defaultPort; + return config.get('resourcesPort', null) || corbel.Resources.defaultPort }, request: function(args) { - var params = corbel.utils.extend(this.params, args); + var params = corbel.utils.extend(this.params, args) - this.params = {}; //reset instance params + this.params = {} // reset instance params - args.query = corbel.utils.serializeParams(params); + args.query = corbel.utils.serializeParams(params) - //call service request implementation - return corbel.Services.prototype.request.apply(this, [args].concat(Array.prototype.slice.call(arguments, 1))); + // call service request implementation + return corbel.Services.prototype.request.apply(this, [args].concat(Array.prototype.slice.call(arguments, 1))) }, getURL: function(params) { - return this.buildUri(this.type, this.srcId, this.destType) + (params ? '?' + corbel.utils.serializeParams(params) : ''); + return this.buildUri(this.type, this.srcId, this.destType) + (params ? '?' + corbel.utils.serializeParams(params) : '') }, getDefaultOptions: function(options) { - var defaultOptions = options ? corbel.utils.clone(options) : {}; + var defaultOptions = options ? corbel.utils.clone(options) : {} - return defaultOptions; + return defaultOptions } - }); + }) // extend for inherit requestParamsBuilder methods extensible for all Resources object - corbel.utils.extend(corbel.Resources.BaseResource.prototype, corbel.requestParamsBuilder.prototype); - - return corbel.Resources.BaseResource; + corbel.utils.extend(corbel.Resources.BaseResource.prototype, corbel.requestParamsBuilder.prototype) - })(); + return corbel.Resources.BaseResource + })() + ; (function() { /** @@ -4415,14 +4357,13 @@ * @param {String} destType The destination resource type */ corbel.Resources.Relation = corbel.Resources.BaseResource.inherit({ - constructor: function(srcType, srcId, destType, driver, params) { - this.type = srcType; - this.srcId = srcId; - this.destType = destType; - corbel.validate.values(['type', 'srcId', 'destType'], this); - this.driver = driver; - this.params = params || {}; + this.type = srcType + this.srcId = srcId + this.destType = destType + corbel.validate.values(['type', 'srcId', 'destType'], this) + this.driver = driver + this.params = params || {} }, /** @@ -4436,14 +4377,14 @@ * @see {@link corbel.util.serializeParams} to see a example of the params */ get: function(destId, options) { - options = this.getDefaultOptions(options); + options = this.getDefaultOptions(options) var args = corbel.utils.extend(options, { url: this.buildUri(this.type, this.srcId, this.destType, destId), method: corbel.request.method.GET, Accept: options.dataType - }); + }) - return this.request(args); + return this.request(args) }, /** @@ -4456,17 +4397,17 @@ * @example uri = '555' */ add: function(destId, relationData, options) { - options = this.getDefaultOptions(options); - corbel.validate.value('destId', destId); + options = this.getDefaultOptions(options) + corbel.validate.value('destId', destId) var args = corbel.utils.extend(options, { url: this.buildUri(this.type, this.srcId, this.destType, destId), contentType: 'application/json', data: relationData, method: corbel.request.method.PUT - }); + }) - return this.request(args); + return this.request(args) }, /** @@ -4478,16 +4419,16 @@ * @example uri = '555' */ addAnonymous: function(relationData, options) { - options = this.getDefaultOptions(options); + options = this.getDefaultOptions(options) var args = corbel.utils.extend(options, { url: this.buildUri(this.type, this.srcId, this.destType), contentType: 'application/json', data: relationData, method: corbel.request.method.POST - }); + }) - return this.request(args); + return this.request(args) }, /** @@ -4498,13 +4439,13 @@ * @return {Promise} ES6 promise that resolves to undefined (void) or rejects with a {@link CorbelError} */ move: function(destId, pos, options) { - corbel.validate.value('destId', destId); - var positionStartId = destId.indexOf('/'); + corbel.validate.value('destId', destId) + var positionStartId = destId.indexOf('/') if (positionStartId !== -1) { - destId = destId.substring(positionStartId + 1); + destId = destId.substring(positionStartId + 1) } - options = this.getDefaultOptions(options); + options = this.getDefaultOptions(options) var args = corbel.utils.extend(options, { url: this.buildUri(this.type, this.srcId, this.destType, destId), @@ -4513,9 +4454,9 @@ '_order': '$pos(' + pos + ')' }, method: corbel.request.method.PUT - }); + }) - return this.request(args); + return this.request(args) }, /** @@ -4528,24 +4469,23 @@ * destId = 'music:Track/555' */ delete: function(destId, options) { - options = this.getDefaultOptions(options); + options = this.getDefaultOptions(options) var args = corbel.utils.extend(options, { url: this.buildUri(this.type, this.srcId, this.destType, destId), method: corbel.request.method.DELETE - }); + }) - return this.request(args); + return this.request(args) } - }); + }) - return corbel.Resources.Relation; + return corbel.Resources.Relation + })() - })(); + ; (function() { - - /** * Collection requests * @class @@ -4554,12 +4494,11 @@ * @param {CorbelDriver} corbel instance */ corbel.Resources.Collection = corbel.Resources.BaseResource.inherit({ - constructor: function(type, driver, params) { - this.type = type; - corbel.validate.value('type', this.type); - this.driver = driver; - this.params = params || {}; + this.type = type + corbel.validate.value('type', this.type) + this.driver = driver + this.params = params || {} }, /** @@ -4571,15 +4510,15 @@ * @see {@link corbel.util.serializeParams} to see a example of the params */ get: function(options) { - options = this.getDefaultOptions(options); + options = this.getDefaultOptions(options) var args = corbel.utils.extend(options, { url: this.buildUri(this.type), method: corbel.request.method.GET, Accept: options.dataType - }); + }) - return this.request(args); + return this.request(args) }, /** @@ -4591,7 +4530,7 @@ * @return {Promise} ES6 promise that resolves to the new resource id or rejects with a {@link CorbelError} */ add: function(data, options) { - options = this.getDefaultOptions(options); + options = this.getDefaultOptions(options) var args = corbel.utils.extend(options, { url: this.buildUri(this.type), @@ -4599,11 +4538,11 @@ contentType: options.dataType, Accept: options.dataType, data: data - }); + }) return this.request(args).then(function(res) { - return corbel.Services.getLocationId(res); - }); + return corbel.Services.getLocationId(res) + }) }, /** @@ -4615,7 +4554,7 @@ * @return {Promise} ES6 promise that resolves to an {Array} of resources or rejects with a {@link CorbelError} */ update: function(data, options) { - options = this.getDefaultOptions(options); + options = this.getDefaultOptions(options) var args = corbel.utils.extend(options, { url: this.buildUri(this.type), @@ -4623,9 +4562,9 @@ contentType: options.dataType, Accept: options.dataType, data: data - }); + }) - return this.request(args); + return this.request(args) }, /** @@ -4636,24 +4575,24 @@ * @return {Promise} ES6 promise that resolves to the new resource id or rejects with a {@link CorbelError} */ delete: function(options) { - options = this.getDefaultOptions(options); + options = this.getDefaultOptions(options) var args = corbel.utils.extend(options, { url: this.buildUri(this.type), method: corbel.request.method.DELETE, contentType: options.dataType, Accept: options.dataType - }); + }) - return this.request(args); + return this.request(args) } - }); - - return corbel.Resources.Collection; + }) - })(); + return corbel.Resources.Collection + })() + ; (function() { /** @@ -4664,14 +4603,13 @@ * @param {String} id The resource id */ corbel.Resources.Resource = corbel.Resources.BaseResource.inherit({ - constructor: function(type, id, driver, params) { - this.type = type; - this.id = id; - corbel.validate.values(['type', 'id'], this); + this.type = type + this.id = id + corbel.validate.values(['type', 'id'], this) - this.driver = driver; - this.params = params || {}; + this.driver = driver + this.params = params || {} }, /** @@ -4685,20 +4623,18 @@ * @see {@link services.request} to see a example of the params */ get: function(options) { - options = this.getDefaultOptions(options); - + options = this.getDefaultOptions(options) var args = corbel.utils.extend(options, { url: this.buildUri(this.type, this.id), method: corbel.request.method.GET, contentType: options.dataType, Accept: options.dataType - }); + }) - return this.request(args); + return this.request(args) }, - /** * Updates a resource * @method @@ -4711,7 +4647,7 @@ * @see {@link services.request} to see a example of the params */ update: function(data, options) { - options = this.getDefaultOptions(options); + options = this.getDefaultOptions(options) var args = corbel.utils.extend(options, { url: this.buildUri(this.type, this.id), @@ -4719,12 +4655,11 @@ data: data, contentType: options.dataType, Accept: options.dataType - }); + }) - return this.request(args); + return this.request(args) }, - /** * Updates the ACL of a resource * @method @@ -4738,9 +4673,9 @@ method: corbel.request.method.PUT, data: acl, Accept: 'application/corbel.acl+json' - }; + } - return this.request(args); + return this.request(args) }, /** @@ -4752,26 +4687,26 @@ * @return {Promise} ES6 promise that resolves to undefined (void) or rejects with a {@link CorbelError} */ delete: function(options) { - options = this.getDefaultOptions(options); + options = this.getDefaultOptions(options) var args = corbel.utils.extend(options, { url: this.buildUri(this.type, this.id), method: corbel.request.method.DELETE, contentType: options.dataType, Accept: options.dataType - }); + }) - return this.request(args); + return this.request(args) } - }); - - return corbel.Resources.Resource; + }) - })(); + return corbel.Resources.Resource + })() + /* global corbel */ + ; (function() { - /** * A module to make Oauth requests. * @exports Oauth @@ -4780,83 +4715,83 @@ */ var Oauth = corbel.Oauth = function(driver) { - this.driver = driver; - }; + this.driver = driver + } - Oauth.moduleName = 'oauth'; - Oauth.defaultPort = 8084; + Oauth.moduleName = 'oauth' + Oauth.defaultPort = 8084 Oauth.create = function(driver) { - return new Oauth(driver); - }; - /** - * Private method to build a string uri - * @private - * @param {String} uri - * @return {String} - */ + return new Oauth(driver) + } + /** + * Private method to build a string uri + * @private + * @param {String} uri + * @return {String} + */ Oauth._buildUri = function(uri) { + var urlBase = this.driver.config.getCurrentEndpoint(Oauth.moduleName, corbel.Oauth._buildPort(this.driver.config)) - var urlBase = this.driver.config.getCurrentEndpoint(Oauth.moduleName, corbel.Oauth._buildPort(this.driver.config)); - - return urlBase + uri; - }; + return urlBase + uri + } Oauth._buildPort = function(config) { - return config.get('oauthPort', null) || corbel.Oauth.defaultPort; - }; + return config.get('oauthPort', null) || corbel.Oauth.defaultPort + } /** * Default encoding * @type {String} * @default application/x-www-form-urlencoded; charset=UTF-8 */ - Oauth._URL_ENCODED = 'application/x-www-form-urlencoded; charset=UTF-8'; + Oauth._URL_ENCODED = 'application/x-www-form-urlencoded; charset=UTF-8' Oauth._checkProp = function(dict, keys, excep) { - var error = excep ? excep : 'Error validating arguments'; + var error = !excep ? 'Error validating arguments' : excep if (!dict) { - throw new Error(error); + throw new Error(error) } for (var i in keys) { if (!(keys[i] in dict)) { - throw new Error(error); + throw new Error(error) } } - }; + } Oauth._validateResponseType = function(responseType) { if (['code', 'token'].indexOf(responseType) < 0) { - throw new Error('Only "code" or "token" response type allowed'); + throw new Error('Only "code" or "token" response type allowed') } - }; + } Oauth._validateGrantType = function(grantType) { if (grantType !== 'authorization_code') { - throw new Error('Only "authorization_code" grant type is allowed'); + throw new Error('Only "authorization_code" grant type is allowed') } - }; + } Oauth._trasformParams = function(clientParams) { - for (var key in clientParams) { - var keyWithUnderscores = this._toUnderscore(key); + var keyWithUnderscores = this._toUnderscore(key) if (key !== keyWithUnderscores) { - clientParams[keyWithUnderscores] = clientParams[key]; - delete clientParams[key]; + clientParams[keyWithUnderscores] = clientParams[key] + delete clientParams[key] } } - return clientParams; - }; + return clientParams + } Oauth._toUnderscore = function(string) { return string.replace(/([A-Z])/g, function($1) { - return '_' + $1.toLowerCase(); - }); - }; - })(); + return '_' + $1.toLowerCase() + }) + } + })() + /* global corbel */ + ; (function() { /** * Create a AuthorizationBuilder for resource managing requests. @@ -4866,25 +4801,25 @@ * @return {corbel.Oauth.AuthorizationBuilder} */ corbel.Oauth.prototype.authorization = function(clientParams) { - console.log('oauthInterface.authorization', clientParams); + console.log('oauthInterface.authorization', clientParams) - corbel.Oauth._checkProp(clientParams, ['responseType'], 'Invalid client parameters'); - clientParams.responseType = clientParams.responseType.toLowerCase(); - corbel.Oauth._validateResponseType(clientParams.responseType); + corbel.Oauth._checkProp(clientParams, ['responseType'], 'Invalid client parameters') + clientParams.responseType = clientParams.responseType.toLowerCase() + corbel.Oauth._validateResponseType(clientParams.responseType) if (clientParams.responseType.toLowerCase() === 'code') { - corbel.Oauth._checkProp(clientParams, ['redirectUri'], 'Invalid client parameters'); + corbel.Oauth._checkProp(clientParams, ['redirectUri'], 'Invalid client parameters') } - clientParams.clientId = clientParams.clientId || corbel.Config.get('oauthClientId'); + clientParams.clientId = clientParams.clientId || corbel.Config.get('oauthClientId') var params = { contentType: corbel.Oauth._URL_ENCODED, data: corbel.Oauth._trasformParams(clientParams), // http://stackoverflow.com/questions/1557602/jquery-and-ajax-response-header noRedirect: true - }; - var authorization = new AuthorizationBuilder(params); - authorization.driver = this.driver; - return authorization; - }; + } + var authorization = new AuthorizationBuilder(params) + authorization.driver = this.driver + return authorization + } /** * A builder for authorization management requests. @@ -4895,10 +4830,9 @@ * @memberOf corbel.Oauth.AuthorizationBuilder */ var AuthorizationBuilder = corbel.Oauth.AuthorizationBuilder = corbel.Services.inherit({ - constructor: function(params) { - this.params = params; - this.uri = 'oauth'; + this.params = params + this.uri = 'oauth' }, /** @@ -4908,8 +4842,8 @@ * @return {Promise} Q promise that resolves to a redirection to redirectUri or rejects with a 404 {@link CorbelError} */ loginWithCookie: function() { - console.log('oauthInterface.authorization.dialog'); - // make request, generate oauth cookie, then redirect manually + console.log('oauthInterface.authorization.dialog') + // make request, generate oauth cookie, then redirect manually return this.request({ url: this._buildUri(this.uri + '/authorize'), method: corbel.request.method.GET, @@ -4918,8 +4852,8 @@ data: this.params, query: this.params.data ? corbel.utils.serializeParams(this.params.data) : null }).then(function(res) { - return corbel.Services.getLocationId(res); - }); + return corbel.Services.getLocationId(res) + }) }, /** * Does a login in oauth server @@ -4930,12 +4864,12 @@ * @return {Promise} Q promise that resolves to a redirection to redirectUri or rejects with a {@link CorbelError} */ login: function(username, password, setCookie) { - console.log('oauthInterface.authorization.login', username + ':' + password); + console.log('oauthInterface.authorization.login', username + ':' + password) - this.params.data.username = username; - this.params.data.password = password; - this.params.withCredentials = true; - // make request, generate oauth cookie, then redirect manually + this.params.data.username = username + this.params.data.password = password + this.params.withCredentials = true + // make request, generate oauth cookie, then redirect manually return this.request({ url: this._buildUri(this.uri + '/authorize'), method: corbel.request.method.POST, @@ -4945,20 +4879,20 @@ if (res.jqXHR.getResponseHeader('Location')) { var params = { url: corbel.Services.getLocationId(res) - }; + } if (setCookie) { params.headers = { RequestCookie: 'true' - }; - params.withCredentials = true; + } + params.withCredentials = true } - return this.request(params); + return this.request(params) } else { - return res.data; + return res.data } - }); + }) }, /** @@ -4968,23 +4902,24 @@ * @return {Promise} promise that resolves empty when the sign out process completes or rejects with a {@link CorbelError} */ signout: function() { - console.log('oauthInterface.authorization.signOut'); - delete this.params.data; + console.log('oauthInterface.authorization.signOut') + delete this.params.data return this.request({ url: this._buildUri(this.uri + '/signout'), method: corbel.request.method.GET, withCredentials: true }).then(function(res) { - return corbel.Services.getLocationId(res); - }); + return corbel.Services.getLocationId(res) + }) }, _buildUri: corbel.Oauth._buildUri - }); - - })(); + }) + })() + /* global corbel */ + ; (function() { /** * Create a TokenBuilder for token managing requests. @@ -4997,58 +4932,55 @@ * @return {corbel.Oauth.TokenBuilder} */ corbel.Oauth.prototype.token = function(clientParams) { - console.log('oauthInterface.token'); + console.log('oauthInterface.token') - corbel.Oauth._checkProp(clientParams, ['grantType'], 'Invalid client parameters'); - corbel.Oauth._validateGrantType(clientParams.grantType); - clientParams.clientId = clientParams.clientId || corbel.Config.get('oauthClientId'); - clientParams.clientSecret = clientParams.clientSecret || corbel.Config.get('oauthSecret'); - var params = { - contentType: corbel.Oauth._URL_ENCODED, - data: corbel.Oauth._trasformParams(clientParams) - }; - var token = new TokenBuilder(params); - token.driver = this.driver; - return token; - }; - /** - * A builder for a token management requests. - * @class - * - * @param {Object} params Initial params - * - * @memberOf corbel.Oauth.TokenBuilder - */ + corbel.Oauth._checkProp(clientParams, ['grantType'], 'Invalid client parameters') + corbel.Oauth._validateGrantType(clientParams.grantType) + clientParams.clientId = clientParams.clientId || corbel.Config.get('oauthClientId') + clientParams.clientSecret = clientParams.clientSecret || corbel.Config.get('oauthSecret') + var params = { + contentType: corbel.Oauth._URL_ENCODED, + data: corbel.Oauth._trasformParams(clientParams) + } + var token = new TokenBuilder(params) + token.driver = this.driver + return token + } + /** + * A builder for a token management requests. + * @class + * @param {Object} params Initial params + * @memberOf corbel.Oauth.TokenBuilder + */ var TokenBuilder = corbel.Oauth.TokenBuilder = corbel.Services.inherit({ - constructor: function(params) { - this.params = params; - this.uri = 'oauth/token'; + this.params = params + this.uri = 'oauth/token' }, /** * Get an access token * @method * @memberOf corbel.Oauth.TokenBuilder - * * @param {String} code The code to exchange for the token - * * @return {Promise} promise that resolves to an access token {Object} or rejects with a {@link CorbelError} */ get: function(code) { - console.log('oauthInterface.token.get'); - this.params.data.code = code; + console.log('oauthInterface.token.get') + this.params.data.code = code return this.request({ url: this._buildUri(this.uri), method: corbel.request.method.POST, data: this.params - }); + }) }, _buildUri: corbel.Oauth._buildUri - }); - })(); + }) + })() + /* global corbel btoa */ + ; (function() { /** * Create a UserBuilder for user managing requests. @@ -5061,41 +4993,38 @@ * @return {corbel.Oauth.UserBuilder} */ corbel.Oauth.prototype.user = function(clientParams, accessToken) { - console.log('oauthInterface.user'); + console.log('oauthInterface.user') - var params = {}; + var params = {} - if (accessToken) { - params.accessToken = accessToken; - params.headers = {}; - params.headers.Accept = 'application/json'; - } + if (accessToken) { + params.accessToken = accessToken + params.headers = {} + params.headers.Accept = 'application/json' + } - clientParams = clientParams || {}; - var clientId = clientParams.clientId || corbel.Config.get('oauthClientId'); - var clientSecret = clientParams.clientSecret || corbel.Config.get('oauthSecret'); + clientParams = clientParams || {} + var clientId = clientParams.clientId || corbel.Config.get('oauthClientId') + var clientSecret = clientParams.clientSecret || corbel.Config.get('oauthSecret') - var user = new UserBuilder(params, clientId, clientSecret); - user.driver = this.driver; - return user; - }; - /** - * A builder for a user management requests. - * @class - * - * @param {Object} params Parameters for initializing the builder - * @param {String} [clientId] Application client Id (required for creating user) - * @param {String} [clientSecret] Application client secret (required for creating user) - * - * @memberOf corbel.Oauth.UserBuilder - */ + var user = new UserBuilder(params, clientId, clientSecret) + user.driver = this.driver + return user + } + /** + * A builder for a user management requests. + * @class + * @param {Object} params Parameters for initializing the builder + * @param {String} [clientId] Application client Id (required for creating user) + * @param {String} [clientSecret] Application client secret (required for creating user) + * @memberOf corbel.Oauth.UserBuilder + */ var UserBuilder = corbel.Oauth.UserBuilder = corbel.Services.inherit({ - constructor: function(params, clientId, clientSecret) { - this.params = params; - this.clientSecret = clientSecret; - this.clientId = clientId; - this.uri = 'user'; + this.params = params + this.clientSecret = clientSecret + this.clientId = clientId + this.uri = 'user' }, _buildUri: corbel.Oauth._buildUri, /** @@ -5113,7 +5042,7 @@ * with a {@link corbelError}. */ create: function(user) { - console.log('oauthInterface.user.create', user); + console.log('oauthInterface.user.create', user) return this.request({ url: this._buildUri(this.uri), @@ -5124,75 +5053,69 @@ dataType: 'text', data: user }).then(function(res) { - return corbel.Services.getLocationId(res); - }); + return corbel.Services.getLocationId(res) + }) }, /** * Gets the user or the logged user * @method * @memberOf corbel.Oauth.UserBuilder - * - * @param {Object} id The user id/me - * + * @param {Object} id The user id/me * @return {Promise} Q promise that resolves to a User {Object} or rejects with a {@link corbelError} */ get: function(id) { - console.log('oauthInterface.user.get'); - this.uri += '/' + id; + console.log('oauthInterface.user.get') + this.uri += '/' + id return this.request({ url: this._buildUri(this.uri, this.uri), method: corbel.request.method.GET - }); + }) }, /** * Get profile of some user or the logged user * @method * @memberOf corbel.Oauth.UserBuilder - * @param {Object} id The user id/me + * @param {Object} id The user id/me * @return {Promise} Q promise that resolves to the profile from User {Object} or rejects with a {@link corbelError} */ getProfile: function(id) { - console.log('oauthInterface.user.getProfile'); - this.uri += '/' + id + '/profile'; + console.log('oauthInterface.user.getProfile') + this.uri += '/' + id + '/profile' return this.request({ url: this._buildUri(this.uri), method: corbel.request.method.GET - }); + }) }, /** * Updates the user or the logged user * @method * @memberOf corbel.Oauth.UserBuilder - * * @param {Object} id The user id or me * @param {Object} modification Json object with the modificacion of the user - * * @return {Promise} Q promise that resolves to undefined (void) or rejects with a {@link corbelError} */ update: function(id, modification) { - console.log('oauthInterface.user.update', modification); - this.uri += '/' + id; + console.log('oauthInterface.user.update', modification) + this.uri += '/' + id return this.request({ url: this._buildUri(this.uri), method: corbel.request.method.PUT, data: modification - }); + }) }, /** * Deletes the user or the logged user * @memberOf corbel.Oauth.UserBuilder - * * @param {Object} id The user id or me - * * @return {Promise} Q promise that resolves to undefined (void) or rejects with a {@link corbelError} */ delete: function(id) { - console.log('oauthInterface.user.delete'); - this.uri += '/' + id; + console.log('oauthInterface.user.delete') + this.uri += '/' + id return this.request({ url: this._buildUri(this.uri), method: corbel.request.method.DELETE - }); + }) }, /** * Sends a reset password email to the email address recived. @@ -5202,7 +5125,7 @@ * @return {Promise} Q promise that resolves to undefined (void) or rejects with a {@link CorbelError} */ sendResetPasswordEmail: function(userEmailToReset) { - console.log('oauthInterface.user.SendResetPasswordEmail', userEmailToReset); + console.log('oauthInterface.user.SendResetPasswordEmail', userEmailToReset) return this.request({ url: this._buildUri(this.uri + '/resetPassword'), method: corbel.request.method.GET, @@ -5212,102 +5135,96 @@ }, noRetry: true }).then(function(res) { - return corbel.Services.getLocationId(res); - }); + return corbel.Services.getLocationId(res) + }) }, /** * Sends a email to the logged user or user to validate his email address * @method * @memberOf corbel.Oauth.UsersBuilder - * * @param {Object} id The user id or me - * * @return {Promise} Q promise that resolves to undefined (void) or rejects with a {@link CorbelError} */ sendValidateEmail: function(id) { - console.log('oauthInterface.user.sendValidateEmail'); - this.uri += '/' + id + '/validate'; + console.log('oauthInterface.user.sendValidateEmail') + this.uri += '/' + id + '/validate' return this.request({ url: this._buildUri(this.uri), method: corbel.request.method.GET, withAuth: true - }); + }) }, /** * Validates the email of a user or the logged user * @method * @memberOf corbel.Oauth.UsersBuilder - * * @param {Object} id The user id or me - * * @return {Promise} Q promise that resolves to undefined (void) or rejects with a {@link CorbelError} */ emailConfirmation: function(id) { - console.log('oauthInterface.user.emailConfirmation'); - this.uri += '/' + id + '/emailConfirmation'; + console.log('oauthInterface.user.emailConfirmation') + this.uri += '/' + id + '/emailConfirmation' return this.request({ url: this._buildUri(this.uri, id), method: corbel.request.method.PUT, noRetry: true - }); + }) }, getSerializer: function() { if (corbel.Config.isNode) { - return require('btoa'); + return require('btoa') } else { - return btoa; + return btoa } } - }); - })(); + }) + })() + ; (function() { corbel.Notifications = corbel.Object.inherit({ - /** * Creates a new NotificationsBuilder * @param {String} id String with the asset id or 'all' key * @return {Notifications} */ constructor: function(driver) { - this.driver = driver; + this.driver = driver }, notification: function(id) { - return new corbel.Notifications.NotificationsBuilder(this.driver, id); + return new corbel.Notifications.NotificationsBuilder(this.driver, id) } }, { - moduleName: 'notifications', defaultPort: 8094, create: function(driver) { - return new corbel.Notifications(driver); + return new corbel.Notifications(driver) } - }); + }) - return corbel.Notifications; - - })(); + return corbel.Notifications + })() + /* global corbel */ + ; (function() { - var NotificationsBuilder = corbel.Notifications.NotificationsBuilder = corbel.Services.inherit({ - /** * Creates a new NotificationsBuilder * @param {String} id String with the asset id or 'all' key * @return {Assets} */ constructor: function(driver, id) { - this.driver = driver; - this.uri = 'notification'; - this.id = id; + this.driver = driver + this.uri = 'notification' + this.id = id }, /* * Creates a new notification @@ -5322,15 +5239,14 @@ * @return {Promise} Promise that resolves in the new notification id or rejects with a {@link CorbelError} */ create: function(notification) { - console.log('notificationsInterface.notification.create', notification); + console.log('notificationsInterface.notification.create', notification) return this.request({ url: this._buildUri(this.uri), method: corbel.request.method.POST, data: notification - }). - then(function(res) { - return corbel.Services.getLocationId(res); - }); + }).then(function(res) { + return corbel.Services.getLocationId(res) + }) }, /** * Gets a notification @@ -5340,12 +5256,12 @@ * @return {Promise} Promise that resolves to a Notification {Object} or rejects with a {@link CorbelError} */ get: function(params) { - console.log('notificationsInterface.notification.get', params); + console.log('notificationsInterface.notification.get', params) return this.request({ url: this._buildUri(this.uri, this.id), method: corbel.request.method.GET, query: params ? corbel.utils.serializeParams(params) : null - }); + }) }, /** * Updates a notification @@ -5356,13 +5272,13 @@ * @return {Promise} Promise that resolves to undefined (void) or rejects with a {@link CorbelError} */ update: function(data) { - console.log('notificationsInterface.notification.update', data); - corbel.validate.value('id', this.id); + console.log('notificationsInterface.notification.update', data) + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id), method: corbel.request.method.PUT, data: data - }); + }) }, /** * Deletes a notification @@ -5371,12 +5287,12 @@ * @return {Promise} Promise that resolves to undefined (void) or rejects with a {@link CorbelError} */ delete: function() { - console.log('notificationsInterface.notification.delete'); - corbel.validate.value('id', this.id); + console.log('notificationsInterface.notification.delete') + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id), method: corbel.request.method.DELETE - }); + }) }, /** * Send a notification @@ -5389,47 +5305,46 @@ * @return {Promise} Promise that resolves to undefined (void) or rejects with a {@link CorbelError} */ sendNotification: function(notification) { - console.log('notificationsInterface.notification.sendNotification', notification); - this.uri += '/send'; + console.log('notificationsInterface.notification.sendNotification', notification) + this.uri += '/send' return this.request({ url: this._buildUri(this.uri), method: corbel.request.method.POST, data: notification - }); + }) }, _buildUri: function(path, id) { - var uri = ''; - var urlBase = this.driver.config.getCurrentEndpoint(corbel.Notifications.moduleName, this._buildPort(this.driver.config)); + var uri = '' + var urlBase = this.driver.config.getCurrentEndpoint(corbel.Notifications.moduleName, this._buildPort(this.driver.config)) - uri = urlBase + path; + uri = urlBase + path if (id) { - uri += '/' + id; + uri += '/' + id } - return uri; + return uri }, _buildPort: function(config) { - return config.get('notificationsPort', null) || corbel.Notifications.defaultPort; + return config.get('notificationsPort', null) || corbel.Notifications.defaultPort } }, { - moduleName: 'notifications', create: function(driver) { - return new corbel.NotificationsBuilder(driver); + return new corbel.NotificationsBuilder(driver) } - }); - - return NotificationsBuilder; + }) - })(); + return NotificationsBuilder + })() + /* global corbel */ + ; (function() { - /** * A module to make Ec requests. * @exports Ec @@ -5438,15 +5353,15 @@ */ var Ec = corbel.Ec = function(driver) { - this.driver = driver; - }; + this.driver = driver + } - Ec.moduleName = 'ec'; - Ec.defaultPort = 8088; + Ec.moduleName = 'ec' + Ec.defaultPort = 8088 Ec.create = function(driver) { - return new Ec(driver); - }; + return new Ec(driver) + } Ec._ec = { /** @@ -5493,7 +5408,7 @@ */ CANCELLED: 'CANCELLED' } - }; + } /** * COMMON MIXINS @@ -5503,8 +5418,8 @@ // return { // name: data.name, // data: cse.encrypt(data.number, data.holderName, data.cvc, data.expiryMonth, data.expiryYear) - // }; - // }; + // } + // } /** * Private method to build a string uri @@ -5516,25 +5431,25 @@ */ Ec._buildUri = function(uri, id, extra) { if (id) { - uri += '/' + id; + uri += '/' + id } if (extra) { - uri += extra; + uri += extra } - var urlBase = this.driver.config.getCurrentEndpoint(Ec.moduleName, corbel.Ec._buildPort(this.driver.config)); + var urlBase = this.driver.config.getCurrentEndpoint(Ec.moduleName, corbel.Ec._buildPort(this.driver.config)) - return urlBase + uri; - }; + return urlBase + uri + } Ec._buildPort = function(config) { - return config.get('ecPort', null) || corbel.Ec.defaultPort; - }; - - })(); + return config.get('ecPort', null) || corbel.Ec.defaultPort + } + })() + /* global corbel */ + ; (function() { - /** * Create a OrderBuilder for order managing requests. * @@ -5543,10 +5458,10 @@ * @return {corbel.Ec.OrderBuilder} */ corbel.Ec.prototype.order = function(id) { - var order = new OrderBuilder(id); - order.driver = this.driver; - return order; - }; + var order = new OrderBuilder(id) + order.driver = this.driver + return order + } /** * A builder for order requests. @@ -5557,12 +5472,11 @@ * @memberOf corbel.Ec.OrderBuilder */ var OrderBuilder = corbel.Ec.OrderBuilder = corbel.Services.inherit({ - constructor: function(id) { if (id) { - this.id = id; + this.id = id } - this.uri = 'order'; + this.uri = 'order' }, /** @@ -5572,11 +5486,11 @@ * @return {Promise} Q promise that resolves to a Order {Object} or rejects with a {@link SilkRoadError} */ get: function() { - corbel.validate.value('id', this.id); + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id), method: corbel.request.method.GET - }); + }) }, /** @@ -5588,12 +5502,12 @@ * @return {Promise} Q promise that resolves to undefined (void) or rejects with a {@link SilkRoadError} */ update: function(order) { - corbel.validate.value('id', this.id); + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id), method: corbel.request.method.PUT, data: order - }); + }) }, /** @@ -5603,11 +5517,11 @@ * @return {Promise} Q promise that resolves to undefined (void) or rejects with a {@link SilkRoadError} */ delete: function() { - corbel.validate.value('id', this.id); + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id), method: corbel.request.method.DELETE - }); + }) }, /** @@ -5618,12 +5532,12 @@ * @return {Promise} Q promise that resolves to undefined (void) or rejects with a {@link SilkRoadError} */ prepare: function(couponIds) { - corbel.validate.value('id', this.id); + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id, '/prepare'), method: corbel.request.method.POST, data: couponIds - }); + }) }, /** @@ -5637,19 +5551,19 @@ */ checkout: function(data) { if (!data.paymentMethodIds) { - return Promise.reject(new Error('paymentMethodIds lists needed')); + return Promise.reject(new Error('paymentMethodIds lists needed')) } if (!data.paymentMethodIds.length) { - return Promise.reject(new Error('One payment method is needed at least')); + return Promise.reject(new Error('One payment method is needed at least')) } - corbel.validate.value('id', this.id); + corbel.validate.value('id', this.id) return this.request({ method: corbel.request.method.POST, url: this._buildUri(this.uri, this.id, '/checkout'), data: data }).then(function(res) { - return corbel.Services.getLocationId(res); - }); + return corbel.Services.getLocationId(res) + }) }, /** @@ -5660,13 +5574,13 @@ */ _buildUri: corbel.Ec._buildUri - }); - - })(); + }) + })() + /* global corbel */ + ; (function() { - /** * Create a ProductBuilder for product managing requests. * @@ -5675,25 +5589,24 @@ * @return {corbel.Ec.ProductBuilder} */ corbel.Ec.prototype.product = function(id) { - var product = new ProductBuilder(id); - product.driver = this.driver; - return product; - }; - /** - * A builder for products management requests. - * - * @param {String} id product ID. - * - * @class - * @memberOf corbel.Ec.ProductBuilder - */ + var product = new ProductBuilder(id) + product.driver = this.driver + return product + } + /** + * A builder for products management requests. + * + * @param {String} id product ID. + * + * @class + * @memberOf corbel.Ec.ProductBuilder + */ var ProductBuilder = corbel.Ec.ProductBuilder = corbel.Services.inherit({ - constructor: function(id) { if (id) { - this.id = id; + this.id = id } - this.uri = 'product'; + this.uri = 'product' }, /** @@ -5717,14 +5630,14 @@ * with a {@link corbelError}. */ create: function(product) { - console.log('ecInterface.product.create', product); + console.log('ecInterface.product.create', product) return this.request({ url: this._buildUri(this.uri), method: corbel.request.method.POST, data: product }).then(function(res) { - return corbel.Services.getLocationId(res); - }); + return corbel.Services.getLocationId(res) + }) }, /** @@ -5738,12 +5651,12 @@ * @return {Promise} A promise with product {Object} or fails with a {@link corbelError}. */ get: function(params) { - console.log('ecInterface.product.get'); + console.log('ecInterface.product.get') return this.request({ url: this._buildUri(this.uri, this.id), method: corbel.request.method.GET, query: params ? corbel.utils.serializeParams(params) : null - }); + }) }, /** @@ -5757,16 +5670,16 @@ * @return {Promise} A promise resolves to undefined (void) or fails with a {@link corbelError}. */ update: function(product) { - console.log('ecInterface.product.update'); - corbel.validate.value('id', this.id); + console.log('ecInterface.product.update') + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id), method: corbel.request.method.PUT, data: product - }); + }) }, - /**Delete a product. + /* Delete a product. * * @method * @memberOf corbel.Ec.EcBuilder @@ -5774,55 +5687,53 @@ * @return {Promise} A promise resolves to undefined (void) or fails with a {@link corbelError}. */ delete: function() { - console.log('ecInterface.product.delete'); - corbel.validate.value('id', this.id); + console.log('ecInterface.product.delete') + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id), method: corbel.request.method.DELETE - }); + }) }, _buildUri: corbel.Ec._buildUri - }); - - })(); + }) + })() + ; (function() { corbel.Evci = corbel.Object.inherit({ - /** * Create a new EventBuilder * @param {String} type String * @return {Events} */ constructor: function(driver) { - this.driver = driver; + this.driver = driver }, event: function(type) { - return new corbel.Evci.EventBuilder(type, this.driver); + return new corbel.Evci.EventBuilder(type, this.driver) } }, { - moduleName: 'evci', defaultPort: 8086, create: function(driver) { - return new corbel.Evci(driver); + return new corbel.Evci(driver) } - }); + }) - return corbel.Evci; - - })(); + return corbel.Evci + })() + /* global corbel */ + ; (function() { - var EventBuilder = corbel.Evci.EventBuilder = corbel.Services.inherit({ /** * Creates a new EventBuilder @@ -5830,9 +5741,9 @@ * @return {Events} */ constructor: function(type, driver) { - this.uri = 'event'; - this.eventType = type; - this.driver = driver; + this.uri = 'event' + this.eventType = type + this.driver = driver }, /** @@ -5848,51 +5759,51 @@ */ publish: function(eventData) { if (!eventData) { - throw new Error('Send event require data'); + throw new Error('Send event require data') } - console.log('evciInterface.publish', eventData); - corbel.validate.value('eventType', this.eventType); + console.log('evciInterface.publish', eventData) + corbel.validate.value('eventType', this.eventType) return this.request({ url: this._buildUri(this.uri, this.eventType), method: corbel.request.method.POST, data: eventData }).then(function(res) { - res.data = corbel.Services.getLocationId(res); - return res; - }); + res.data = corbel.Services.getLocationId(res) + return res + }) }, _buildUri: function(path, eventType) { - var uri = ''; - var urlBase = this.driver.config.getCurrentEndpoint(corbel.Evci.moduleName, this._buildPort(this.driver.config)); + var uri = '' + var urlBase = this.driver.config.getCurrentEndpoint(corbel.Evci.moduleName, this._buildPort(this.driver.config)) - uri = urlBase + path; + uri = urlBase + path if (eventType) { - uri += '/' + eventType; + uri += '/' + eventType } - return uri; + return uri }, _buildPort: function(config) { - return config.get('evciPort', null) || corbel.Evci.defaultPort; + return config.get('evciPort', null) || corbel.Evci.defaultPort } }, { - moduleName: 'evci', create: function(driver) { - return new corbel.EventBuilder(driver); + return new corbel.EventBuilder(driver) } - }); + }) - return EventBuilder; - })(); + return EventBuilder + })() + /* global corbel */ + ; (function() { - /** * A module to make Borrow requests. * @exports Borrow @@ -5901,13 +5812,10 @@ */ corbel.Borrow = corbel.Object.inherit({ - constructor: function(driver) { - this.driver = driver; + this.driver = driver }, - - /** * Create a BorrowBuilder for resource managing requests. * @@ -5916,9 +5824,9 @@ * @return {corbel.Borrow.BorrowBuilder} */ resource: function(id) { - var resource = new corbel.Borrow.BorrowBuilder(id); - resource.driver = this.driver; - return resource; + var resource = new corbel.Borrow.BorrowBuilder(id) + resource.driver = this.driver + return resource }, /** @@ -5929,9 +5837,9 @@ * @return {corbel.Borrow.LenderBuilder} */ lender: function(id) { - var lender = new corbel.Borrow.LenderBuilder(id); - lender.driver = this.driver; - return lender; + var lender = new corbel.Borrow.LenderBuilder(id) + lender.driver = this.driver + return lender }, /** @@ -5942,56 +5850,48 @@ * @return {corbel.Borrow.UserBuilder} */ user: function(id) { - var user = new corbel.Borrow.UserBuilder(id); - user.driver = this.driver; - return user; + var user = new corbel.Borrow.UserBuilder(id) + user.driver = this.driver + return user } - - - }, { moduleName: 'borrow', defaultPort: 8100, create: function(driver) { - return new corbel.Borrow(driver); + return new corbel.Borrow(driver) }, _buildUri: function() { - var uri = ''; + var uri = '' Array.prototype.slice.call(arguments).forEach(function(argument) { if (argument) { - uri += '/' + argument; + uri += '/' + argument } - }); + }) - var urlBase = this.driver.config.getCurrentEndpoint(corbel.Borrow.moduleName, corbel.Borrow._buildPort(this.driver.config)); + var urlBase = this.driver.config.getCurrentEndpoint(corbel.Borrow.moduleName, corbel.Borrow._buildPort(this.driver.config)) if (urlBase.slice(-1) === '/') { - urlBase = urlBase.substring(0, urlBase.length - 1); + urlBase = urlBase.substring(0, urlBase.length - 1) } - return urlBase + uri; + return urlBase + uri }, _buildPort: function(config) { - return config.get('borrowPort', null) || corbel.Borrow.defaultPort; + return config.get('borrowPort', null) || corbel.Borrow.defaultPort } - }); - - return corbel.Borrow; - + }) + return corbel.Borrow + })() + /* global corbel */ - - })(); - - + ; (function() { - - /** * A builder for borrowed management requests. * @@ -6001,10 +5901,9 @@ * @memberOf corbel.Borrow.BorrowBuilder */ corbel.Borrow.BorrowBuilder = corbel.Services.inherit({ - constructor: function(id) { - this.id = id; - this.uri = 'resource'; + this.id = id + this.uri = 'resource' }, /** * Adds the loanable resource. @@ -6027,14 +5926,14 @@ * with a {@link corbelError}. */ add: function(loanableResource) { - console.log('borrowInterface.resource.add', loanableResource); + console.log('borrowInterface.resource.add', loanableResource) return this.request({ url: this._buildUri(this.uri), method: corbel.request.method.POST, data: loanableResource }).then(function(res) { - return corbel.Services.getLocationId(res); - }); + return corbel.Services.getLocationId(res) + }) }, /** * Get a loanable resource. @@ -6045,12 +5944,12 @@ * @return {Promise} A promise with loanable resource {Object} or fails with a {@link corbelError}. */ get: function() { - console.log('borrowInterface.resource.get'); - corbel.validate.value('id', this.id); + console.log('borrowInterface.resource.get') + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id), method: corbel.request.method.GET - }); + }) }, /** * Delete a loanable resource. @@ -6061,41 +5960,41 @@ * @return {Promise} A promise resolves to undefined (void) or fails with a {@link corbelError}. */ delete: function() { - console.log('borrowInterface.resource.delete'); - corbel.validate.value('id', this.id); + console.log('borrowInterface.resource.delete') + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id), method: corbel.request.method.DELETE - }); - }, - /** - * Add license to loanable resource. - * - * @method - * @memberOf corbel.Borrow.BorrowBuilder - * - * @param {Object} data licenses data. - * @param {Object} license The license data. - * @param {String} license.resourceId Identifier of resource - * @param {number} licensee.availableUses Amount of uses that the resource is available - * @param {number} license.availableLoans Amount of concurrent loans are available for the resource - * @param {timestamp} license.expire Expire date - * @param {timestamp} licensee.start Start date - * @param {String} license.asset Asigned to the resource + }) + }, + /** + * Add license to loanable resource. + * + * @method + * @memberOf corbel.Borrow.BorrowBuilder + * + * @param {Object} data licenses data. + * @param {Object} license The license data. + * @param {String} license.resourceId Identifier of resource + * @param {number} licensee.availableUses Amount of uses that the resource is available + * @param {number} license.availableLoans Amount of concurrent loans are available for the resource + * @param {timestamp} license.expire Expire date + * @param {timestamp} licensee.start Start date + * @param {String} license.asset Asigned to the resource - * @return {Promise} A promise with the id of the created a license or fails - * with a {@link corbelError}. - */ + * @return {Promise} A promise with the id of the created a license or fails + * with a {@link corbelError}. + */ addLicense: function(license) { - console.log('borrowInterface.resource.addLicense', license); - corbel.validate.value('id', this.id); + console.log('borrowInterface.resource.addLicense', license) + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id, 'license'), method: corbel.request.method.POST, data: license }).then(function(res) { - return corbel.Services.getLocationId(res); - }); + return corbel.Services.getLocationId(res) + }) }, /** * Apply loan. @@ -6108,15 +6007,15 @@ * @return {Promise} A promise resolves to undefined (void) or fails with a {@link corbelError}. */ applyFor: function(userId) { - console.log('borrowInterface.resource.applyFor', userId); + console.log('borrowInterface.resource.applyFor', userId) corbel.validate.values(['id', 'userId'], { 'id': this.id, 'userId': userId - }); + }) return this.request({ url: this._buildUri(this.uri, this.id, 'loan/' + userId), method: corbel.request.method.PUT - }); + }) }, /** * Apply loan for user logged. @@ -6127,12 +6026,12 @@ * @return {Promise} A promise resolves to undefined (void) or fails with a {@link corbelError}. */ applyForMe: function() { - console.log('borrowInterface.resource.applyForMe'); - corbel.validate.value('id', this.id); + console.log('borrowInterface.resource.applyForMe') + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id, 'loan/me'), method: corbel.request.method.PUT - }); + }) }, /** * Get lent. @@ -6145,15 +6044,15 @@ * @return {Promise} A promise with user lents {Object} or fails with a {@link corbelError}. */ getLentOf: function(userId) { - console.log('borrowInterface.resource.getLentOf', userId); + console.log('borrowInterface.resource.getLentOf', userId) corbel.validate.values(['id', 'userId'], { 'id': this.id, 'userId': userId - }); + }) return this.request({ url: this._buildUri(this.uri, this.id, 'loan/' + userId), method: corbel.request.method.GET - }); + }) }, /** * Get lent of user logged. @@ -6163,12 +6062,12 @@ * @return {Promise} A promise with user logged lents {Object} or fails with a {@link corbelError}. */ getMyLent: function() { - console.log('borrowInterface.resource.getMyLent'); - corbel.validate.value('id', this.id); + console.log('borrowInterface.resource.getMyLent') + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id, 'loan/me'), method: corbel.request.method.GET - }); + }) }, /** * Return lent. @@ -6181,15 +6080,15 @@ * @return {Promise} A promise resolves to undefined (void) or fails with a {@link corbelError}. */ returnLoanOf: function(userId) { - console.log('borrowInterface.resource.returnLoanOf', userId); + console.log('borrowInterface.resource.returnLoanOf', userId) corbel.validate.values(['id', 'userId'], { 'id': this.id, 'userId': userId - }); + }) return this.request({ url: this._buildUri(this.uri, this.id, 'loan/' + userId), method: corbel.request.method.DELETE - }); + }) }, /** * Return loan of user logged. @@ -6200,12 +6099,12 @@ * @return {Promise} A promise resolves to undefined (void) or fails with a {@link corbelError}. */ returnMyLoan: function() { - console.log('borrowInterface.resource.returnMyLoan'); - corbel.validate.value('id', this.id); + console.log('borrowInterface.resource.returnMyLoan') + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id, 'loan/me'), method: corbel.request.method.DELETE - }); + }) }, /** * Renew loan. @@ -6218,15 +6117,15 @@ * @return {Promise} A promise resolves to undefined (void) or fails with a {@link corbelError}. */ renewFor: function(userId) { - console.log('borrowInterface.resource.renewFor', userId); + console.log('borrowInterface.resource.renewFor', userId) corbel.validate.values(['id', 'userId'], { 'id': this.id, 'userId': userId - }); + }) return this.request({ url: this._buildUri(this.uri, this.id, 'renewal/' + userId), method: corbel.request.method.PUT - }); + }) }, /** * Renew loan for user logged. @@ -6237,12 +6136,12 @@ * @return {Promise} A promise resolves to undefined (void) or fails with a {@link corbelError}. */ renewForMe: function() { - console.log('borrowInterface.resource.renewForMe'); - corbel.validate.value('id', this.id); + console.log('borrowInterface.resource.renewForMe') + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id, 'renewal/me'), method: corbel.request.method.PUT - }); + }) }, /** * Reserve a resource. @@ -6255,15 +6154,15 @@ * @return {Promise} A promise resolves to undefined (void) or fails with a {@link corbelError}. */ reserveFor: function(userId) { - console.log('borrowInterface.resource.reserveFor', userId); + console.log('borrowInterface.resource.reserveFor', userId) corbel.validate.values(['id', 'userId'], { 'id': this.id, 'userId': userId - }); + }) return this.request({ url: this._buildUri(this.uri, this.id, 'reservation/' + userId), method: corbel.request.method.PUT - }); + }) }, /** * Reserve a resource for user logged. @@ -6274,12 +6173,12 @@ * @return {Promise} A promise resolves to undefined (void) or fails with a {@link corbelError}. */ reserveForMe: function() { - console.log('borrowInterface.resource.reserveForMe'); - corbel.validate.value('id', this.id); + console.log('borrowInterface.resource.reserveForMe') + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id, 'reservation/me'), method: corbel.request.method.PUT - }); + }) }, /** * Cancel reservation. @@ -6292,15 +6191,15 @@ * @return {Promise} A promise resolves to undefined (void) or fails with a {@link corbelError}. */ cancelReservationFor: function(userId) { - console.log('borrowInterface.resource.cancelReservationFor', userId); + console.log('borrowInterface.resource.cancelReservationFor', userId) corbel.validate.values(['id', 'userId'], { 'id': this.id, 'userId': userId - }); + }) return this.request({ url: this._buildUri(this.uri, this.id, 'reservation/' + userId), method: corbel.request.method.DELETE - }); + }) }, /** * Cancel reservation for user logged. @@ -6311,12 +6210,12 @@ * @return {Promise} A promise resolves to undefined (void) or fails with a {@link corbelError}. */ cancelMyReservation: function() { - console.log('borrowInterface.resource.cancelMyReservation'); - corbel.validate.value('id', this.id); + console.log('borrowInterface.resource.cancelMyReservation') + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id, 'reservation/me'), method: corbel.request.method.DELETE - }); + }) }, /** * get the user borrowed history. @@ -6329,12 +6228,12 @@ * @return {Promise} A promise with user borowed {Object} history or fails with a {@link corbelError}. */ getHistoryOf: function(userId) { - console.log('borrowInterface.resource.getHistoryOf', userId); - corbel.validate.value('userId', userId); + console.log('borrowInterface.resource.getHistoryOf', userId) + corbel.validate.value('userId', userId) return this.request({ url: this._buildUri(this.uri, 'history/' + userId), method: corbel.request.method.GET - }); + }) }, /** * Get lent of user logged. @@ -6344,11 +6243,11 @@ * @return {Promise} A promise with user logged borrowed {Object} history or fails with a {@link corbelError}. */ getMyHistory: function() { - console.log('borrowInterface.resource.getMyHistory'); + console.log('borrowInterface.resource.getMyHistory') return this.request({ url: this._buildUri(this.uri, 'history/me'), method: corbel.request.method.GET - }); + }) }, /** * get full resources borrowed history. @@ -6359,22 +6258,22 @@ * @return {Promise} A promise with borowed full {Object} history or fails with a {@link corbelError}. */ getFullHistory: function(params) { - console.log('borrowInterface.resource.getFullHistory'); + console.log('borrowInterface.resource.getFullHistory') return this.request({ url: this._buildUri(this.uri, 'history/'), method: corbel.request.method.GET, query: params ? corbel.utils.serializeParams(params) : null - }); + }) }, _buildUri: corbel.Borrow._buildUri - }); - })(); + }) + })() + /* global corbel */ + ; (function() { - - /** * A builder for borrowed management requests. * @@ -6384,10 +6283,9 @@ * @memberOf corbel.Borrow.UserBuilder */ corbel.Borrow.UserBuilder = corbel.Services.inherit({ - constructor: function(id) { - this.id = id || 'me'; - this.uri = 'user'; + this.id = id || 'me' + this.uri = 'user' }, /** * Get all reservations of a user. @@ -6398,11 +6296,11 @@ * @return {Promise} A promise with all user reservations {Object} or fails with a {@link corbelError}. */ getAllReservations: function() { - console.log('borrowInterface.user.getAllReservations', this.id); + console.log('borrowInterface.user.getAllReservations', this.id) return this.request({ url: this._buildUri(this.uri, this.id, 'reservation'), method: corbel.request.method.GET - }); + }) }, /** * Get all loans of a user. @@ -6413,22 +6311,21 @@ * @return {Promise} A promise with all user loans {Object} or fails with a {@link corbelError}. */ getAllLoans: function() { - console.log('borrowInterface.user.getAllLoans', this.id); + console.log('borrowInterface.user.getAllLoans', this.id) return this.request({ url: this._buildUri(this.uri, this.id, 'loan'), method: corbel.request.method.GET - }); + }) }, - _buildUri: corbel.Borrow._buildUri - }); - })(); + }) + })() + /* global corbel */ + ; (function() { - - /** * A builder for borrowed management requests. * @@ -6438,10 +6335,9 @@ * @memberOf corbel.Borrow.LenderBuilder */ corbel.Borrow.LenderBuilder = corbel.Services.inherit({ - constructor: function(id) { - this.id = id; - this.uri = 'lender'; + this.id = id + this.uri = 'lender' }, /** * Create a new Lender @@ -6461,14 +6357,14 @@ * with a {@link corbelError}. */ create: function(lender) { - console.log('borrowInterface.lender.create', lender); + console.log('borrowInterface.lender.create', lender) return this.request({ url: this._buildUri(this.uri), method: corbel.request.method.POST, data: lender }).then(function(res) { - return corbel.Services.getLocationId(res); - }); + return corbel.Services.getLocationId(res) + }) }, /** * Update a Lender. @@ -6481,13 +6377,13 @@ * @return {Promise} A promise resolves to undefined (void) or fails with a {@link corbelError}. */ update: function(lender) { - console.log('borrowInterface.lender.update'); + console.log('borrowInterface.lender.update') return this.request({ url: this._buildUri(this.uri, this.id), method: corbel.request.method.PUT, data: lender - }); + }) }, /** * Delete a Lender. @@ -6498,12 +6394,12 @@ * @return {Promise} A promise resolves to undefined (void) or fails with a {@link corbelError}. */ delete: function() { - console.log('borrowInterface.lender.delete'); + console.log('borrowInterface.lender.delete') return this.request({ url: this._buildUri(this.uri, this.id), method: corbel.request.method.DELETE - }); + }) }, /** * Get Lender. @@ -6514,12 +6410,12 @@ * @return {Promise} A promise with lender {Object} or fails with a {@link corbelError}. */ get: function() { - console.log('borrowInterface.lender.get'); + console.log('borrowInterface.lender.get') return this.request({ url: this._buildUri(this.uri, this.id), method: corbel.request.method.GET - }); + }) }, /** * Get all Lenders. @@ -6530,12 +6426,12 @@ * @return {Promise} A promise with all lenders {Object} or fails with a {@link corbelError}. */ getAll: function(params) { - console.log('borrowInterface.lender.getAll'); + console.log('borrowInterface.lender.getAll') return this.request({ url: this._buildUri(this.uri, 'all'), method: corbel.request.method.GET, query: params ? corbel.utils.serializeParams(params) : null - }); + }) }, /** * Get all reservations by lender. @@ -6546,21 +6442,22 @@ * @return {Promise} A promise with all reservations {Object} by lender or fails with a {@link corbelError}. */ getAllReservations: function(params) { - console.log('borrowInterface.lender.getAllReservations'); + console.log('borrowInterface.lender.getAllReservations') return this.request({ url: this._buildUri(this.uri, 'reservation'), method: corbel.request.method.GET, query: params ? corbel.utils.serializeParams(params) : null - }); + }) }, _buildUri: corbel.Borrow._buildUri - }); - })(); + }) + })() + /* global corbel */ + ; (function() { - /** * A module to make CompoSR requests. * @exports CompoSR @@ -6569,9 +6466,8 @@ */ corbel.CompoSR = corbel.Object.inherit({ - constructor: function(driver) { - this.driver = driver; + this.driver = driver }, /** @@ -6582,9 +6478,9 @@ * @return {corbel.CompoSR.PhraseBuilder} */ phrase: function(id) { - var phraseBuilder = new corbel.CompoSR.PhraseBuilder(id); - phraseBuilder.driver = this.driver; - return phraseBuilder; + var phraseBuilder = new corbel.CompoSR.PhraseBuilder(id) + phraseBuilder.driver = this.driver + return phraseBuilder }, /** @@ -6598,51 +6494,48 @@ * @return {corbel.CompoSR.RequestBuilder} */ request: function() { - var requestBuilder = new corbel.CompoSR.RequestBuilder(Array.prototype.slice.call(arguments)); - requestBuilder.driver = this.driver; - return requestBuilder; + var requestBuilder = new corbel.CompoSR.RequestBuilder(Array.prototype.slice.call(arguments)) + requestBuilder.driver = this.driver + return requestBuilder } - }, { - moduleName: 'composr', defaultPort: 3000, create: function(driver) { - return new corbel.CompoSR(driver); + return new corbel.CompoSR(driver) }, _buildPort: function(config) { - return config.get('composrPort', null) || corbel.CompoSR.defaultPort; + return config.get('composrPort', null) || corbel.CompoSR.defaultPort }, _buildUri: function() { - var urlBase = this.driver.config.getCurrentEndpoint(corbel.CompoSR.moduleName, corbel.CompoSR._buildPort(this.driver.config)); + var urlBase = this.driver.config.getCurrentEndpoint(corbel.CompoSR.moduleName, corbel.CompoSR._buildPort(this.driver.config)) if (urlBase.slice(-1) === '/') { - urlBase = urlBase.substring(0, urlBase.length - 1); + urlBase = urlBase.substring(0, urlBase.length - 1) } - var uri = ''; + var uri = '' Array.prototype.slice.call(arguments).forEach(function(argument) { if (argument) { - uri += '/' + argument; + uri += '/' + argument } - }); - return urlBase + uri; + }) + return urlBase + uri } - }); - - return corbel.CompoSR; + }) - })(); + return corbel.CompoSR + })() + /* global corbel */ + ; (function() { - - /** * A builder for composr phrase crud. * @@ -6652,58 +6545,57 @@ * @memberOf corbel.CompoSR.PhraseBuilder */ corbel.CompoSR.PhraseBuilder = corbel.Services.inherit({ - constructor: function(id) { - this.id = id; + this.id = id }, put: function(body) { - console.log('composrInterface.phrase.add'); + console.log('composrInterface.phrase.add') return this.request({ url: this._buildUri('phrase', this.id), method: corbel.request.method.PUT, data: body - }); + }) }, get: function() { - console.log('composrInterface.phrase.get'); - corbel.validate.value('id', this.id); + console.log('composrInterface.phrase.get') + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri('phrase', this.id), method: corbel.request.method.GET - }); + }) }, getAll: function() { - console.log('composrInterface.phrase.getAll'); + console.log('composrInterface.phrase.getAll') return this.request({ url: this._buildUri('phrase'), method: corbel.request.method.GET - }); + }) }, delete: function() { - console.log('composrInterface.phrase.delete'); - corbel.validate.value('id', this.id); + console.log('composrInterface.phrase.delete') + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri('phrase', this.id), method: corbel.request.method.DELETE - }); + }) }, _buildUri: corbel.CompoSR._buildUri - }); - })(); + }) + })() + /* global corbel */ + ; (function() { - - /** * A builder for composr requests. * @@ -6712,86 +6604,87 @@ * @memberOf corbel.CompoSR.RequestBuilder */ corbel.CompoSR.RequestBuilder = corbel.Services.inherit({ - constructor: function(pathsArray) { - this.path = this.buildPath(pathsArray); + this.path = this.buildPath(pathsArray) }, post: function(data, options) { - console.log('composrInterface.request.post'); - this.options = options || {}; + console.log('composrInterface.request.post') + this.options = options || {} return this.request({ url: this._buildUri(this.path), method: corbel.request.method.POST, headers: this.options.headers, data: data, query: this.buildQueryPath(this.options.queryParams) - }); + }) }, get: function(options) { - console.log('composrInterface.request.get'); - this.options = options || {}; + console.log('composrInterface.request.get') + this.options = options || {} return this.request({ url: this._buildUri(this.path), method: corbel.request.method.GET, headers: this.options.headers, query: this.buildQueryPath(this.options.queryParams) - }); + }) }, put: function(data, options) { - console.log('composrInterface.request.put'); - this.options = options || {}; + console.log('composrInterface.request.put') + this.options = options || {} return this.request({ url: this._buildUri(this.path), method: corbel.request.method.PUT, data: data, headers: this.options.headers, query: this.buildQueryPath(this.options.queryParams) - }); + }) }, delete: function(options) { - console.log('composrInterface.request.delete'); - this.options = options || {}; + console.log('composrInterface.request.delete') + this.options = options || {} return this.request({ url: this._buildUri(this.path), method: corbel.request.method.DELETE, headers: this.options.headers, query: this.buildQueryPath(this.options.queryParams) - }); + }) }, buildPath: function(pathArray) { - var path = ''; - path += pathArray.shift(); + var path = '' + path += pathArray.shift() pathArray.forEach(function(entryPath) { - path += '/' + entryPath; - }); - return path; + path += '/' + entryPath + }) + return path }, buildQueryPath: function(dict) { - var query = ''; + var query = '' if (dict) { - var queries = []; + var queries = [] Object.keys(dict).forEach(function(key) { - queries.push(key + '=' + dict[key]); - }); + queries.push(key + '=' + dict[key]) + }) if (queries.length > 0) { - query = queries.join('&'); + query = queries.join('&') } } - return query; + return query }, _buildUri: corbel.CompoSR._buildUri - }); - })(); + }) + })() - (function() { + /*globals corbel */ + ; + (function() { /** * A webfs API factory * @exports corbel.Webfs @@ -6800,23 +6693,21 @@ * @memberof corbel */ corbel.Webfs = corbel.Object.inherit({ - - /** + /* * Creates a new WebfsBuilder * @memberof corbel.Webfs.prototype - * @param {string} id String with the resource id + * @param {string} id String with the resource id * @return {corbel.Webfs.WebfsBuilder} */ constructor: function(driver) { - this.driver = driver; + this.driver = driver }, webfs: function(id) { - return new corbel.Webfs.WebfsBuilder(this.driver, id); + return new corbel.Webfs.WebfsBuilder(this.driver, id) } }, { - /** * moduleName constant * @constant @@ -6842,18 +6733,18 @@ * @return {corbel.Webfs.WebfsBuilder} */ create: function(driver) { - return new corbel.Webfs(driver); + return new corbel.Webfs(driver) } - }); + }) - return corbel.Webfs; - - })(); + return corbel.Webfs + })() + /*globals corbel */ + ; (function() { - /** * Module for retrieve content of S3 * @exports WebfsBuilder @@ -6862,15 +6753,14 @@ * @memberof corbel.Webfs */ var WebfsBuilder = corbel.Webfs.WebfsBuilder = corbel.Services.inherit({ - /** * Creates a new WebfsBuilder * @memberof corbel.Webfs.WebfsBuilder.prototype * @return {corbel.Webfs.WebfsBuilder} */ constructor: function(driver, id) { - this.driver = driver; - this.id = id; + this.driver = driver + this.id = id }, /** @@ -6880,33 +6770,30 @@ * @return {Promise} Promise that resolves with a resource or rejects with a {@link CorbelError} */ get: function(params) { + corbel.validate.value('id', this.id) - corbel.validate.value('id', this.id); - - var options = params ? corbel.utils.clone(params) : {}; + var options = params ? corbel.utils.clone(params) : {} var args = corbel.utils.extend(options, { url: this._buildUri(this.id), method: corbel.request.method.GET, query: params ? corbel.utils.serializeParams(params) : null - }); - - return this.request(args); + }) + return this.request(args) }, _buildUri: function(id) { - var urlBase = this.driver.config.getCurrentEndpoint(corbel.Webfs.moduleName, this._buildPort(this.driver.config)); + var urlBase = this.driver.config.getCurrentEndpoint(corbel.Webfs.moduleName, this._buildPort(this.driver.config)) - return urlBase + id; + return urlBase + id }, _buildPort: function(config) { - return config.get('webfsPort', null) || corbel.Webfs.defaultPort; + return config.get('webfsPort', null) || corbel.Webfs.defaultPort } }, { - /** * GET constant * @constant @@ -6923,17 +6810,18 @@ * @default */ create: function(driver) { - return new corbel.Webfs.WebfsBuilder(driver); + return new corbel.Webfs.WebfsBuilder(driver) } - }); + }) - return WebfsBuilder; + return WebfsBuilder + })() - })(); + /* global corbel */ + ; (function() { - /** * A custom domain configuration * @exports corbel.Domain @@ -6942,7 +6830,6 @@ * @memberof corbel */ corbel.Domain = corbel.Object.inherit({ - /** * Creates a new instance of corbelDriver with a custom domain * @memberof corbel.Domain.prototype @@ -6950,18 +6837,16 @@ * @return {corbelDriver} */ constructor: function(driver) { - this.driver = driver; + this.driver = driver return function(id) { - driver.config.set(corbel.Domain.CUSTOM_DOMAIN, id); + driver.config.set(corbel.Domain.CUSTOM_DOMAIN, id) - return driver; - }; + return driver + } } - }, { - /** * moduleName constant * @constant @@ -6987,15 +6872,14 @@ * @return {function} */ create: function(driver) { - return new corbel.Domain(driver); + return new corbel.Domain(driver) } - }); - - return corbel.Domain; + }) - })(); + return corbel.Domain + })() - return corbel; -}); + return corbel +}) diff --git a/dist/corbel.with-polyfills.js b/dist/corbel.with-polyfills.js index cfee186..5e1b76d 100644 --- a/dist/corbel.with-polyfills.js +++ b/dist/corbel.with-polyfills.js @@ -1,27 +1,25 @@ -(function(root, factory) { - 'use strict'; - /* jshint unused: false */ +'use strict' +/* jshint unused: false */ +/* global define */ +; +(function(root, factory) { if (typeof define === 'function' && define.amd) { define(['es6-promise'], function(promise) { - promise.polyfill(); - return factory(root); - }); + promise.polyfill() + return factory(root) + }) } else if (typeof module !== 'undefined' && module.exports) { - var Promise = require('es6-promise').polyfill(); - module.exports = factory.call(root); + var Promise = require('es6-promise') + Promise = Promise.polyfill() + module.exports = factory.call(root) } else if (window !== undefined) { if (root.ES6Promise !== undefined && typeof root.ES6Promise.polyfill === 'function') { - root.ES6Promise.polyfill(); + root.ES6Promise.polyfill() } - root.corbel = factory(root); + root.corbel = factory(root) } - - })(this, function(root) { - 'use strict'; - /* jshint unused: false */ - /*! * @overview es6-promise - a tiny implementation of Promises/A+. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) @@ -1017,13 +1015,14 @@ * @exports corbel * @namespace */ - var corbel = {}; + var corbel = {} - //-----------Utils and libraries (exports into corbel namespace)--------------------------- + // -----------Utils and libraries (exports into corbel namespace)--------------------------- + /* global corbel */ + ; (function() { - /** * @namespace * @memberOf corbel @@ -1031,37 +1030,36 @@ * @return {CorbelDriver} */ function CorbelDriver(config, events) { - if (events && typeof events === 'object') { - this._events = corbel.utils.clone(events); + this._events = corbel.utils.clone(events) } else { - this._events = {}; + this._events = {} } // create instance config - this.guid = corbel.utils.guid(); - this.config = corbel.Config.create(config); + this.guid = corbel.utils.guid() + this.config = corbel.Config.create(config) // create isntance modules with injected driver - this.iam = corbel.Iam.create(this); - this.resources = corbel.Resources.create(this); - this.assets = corbel.Assets.create(this); - this.oauth = corbel.Oauth.create(this); - this.notifications = corbel.Notifications.create(this); - this.ec = corbel.Ec.create(this); - this.evci = corbel.Evci.create(this); - this.borrow = corbel.Borrow.create(this); - this.composr = corbel.CompoSR.create(this); - this.scheduler = corbel.Scheduler.create(this); - this.webfs = corbel.Webfs.create(this); - this.domain = corbel.Domain.create(this); + this.iam = corbel.Iam.create(this) + this.resources = corbel.Resources.create(this) + this.assets = corbel.Assets.create(this) + this.oauth = corbel.Oauth.create(this) + this.notifications = corbel.Notifications.create(this) + this.ec = corbel.Ec.create(this) + this.evci = corbel.Evci.create(this) + this.borrow = corbel.Borrow.create(this) + this.composr = corbel.CompoSR.create(this) + this.scheduler = corbel.Scheduler.create(this) + this.webfs = corbel.Webfs.create(this) + this.domain = corbel.Domain.create(this) } /** * @return {CorbelDriver} A new instance of corbel driver with the same config */ CorbelDriver.prototype.clone = function() { - return new CorbelDriver(this.config.getConfig(), this._events); - }; + return new CorbelDriver(this.config.getConfig(), this._events) + } /** * Adds an event handler for especific event @@ -1070,13 +1068,13 @@ */ CorbelDriver.prototype.addEventListener = function(name, fn) { if (typeof fn !== 'function') { - throw new Error('corbel:error:invalid:type'); + throw new Error('corbel:error:invalid:type') } - this._events[name] = this._events[name] || []; + this._events[name] = this._events[name] || [] if (this._events[name].indexOf(fn) === -1) { - this._events[name].push(fn); + this._events[name].push(fn) } - }; + } /** * Removes the handler from event list @@ -1085,12 +1083,12 @@ */ CorbelDriver.prototype.removeEventListener = function(name, fn) { if (this._events[name]) { - var index = this._events[name].indexOf(fn); + var index = this._events[name].indexOf(fn) if (index !== -1) { - this._events[name].splice(index, 1); + this._events[name].splice(index, 1) } } - }; + } /** * Fires all events handlers for an specific event name @@ -1100,10 +1098,10 @@ CorbelDriver.prototype.dispatch = function(name, options) { if (this._events[name] && this._events[name].length) { this._events[name].forEach(function(fn) { - fn(options); - }); + fn(options) + }) } - }; + } /** * Adds an event handler for especific event @@ -1111,7 +1109,7 @@ * @param {string} name Event name * @param {Function} fn Function to call */ - CorbelDriver.prototype.on = CorbelDriver.prototype.addEventListener; + CorbelDriver.prototype.on = CorbelDriver.prototype.addEventListener /** * Removes the handler from event list @@ -1119,7 +1117,7 @@ * @param {string} name Event name * @param {Function} fn Function to remove */ - CorbelDriver.prototype.off = CorbelDriver.prototype.removeEventListener; + CorbelDriver.prototype.off = CorbelDriver.prototype.removeEventListener /** * Fires all events handlers for an specific event name @@ -1127,9 +1125,9 @@ * @param {string} name Event name * @param {Mixed} options Data for event handlers */ - CorbelDriver.prototype.trigger = CorbelDriver.prototype.dispatch; + CorbelDriver.prototype.trigger = CorbelDriver.prototype.dispatch - corbel.CorbelDriver = CorbelDriver; + corbel.CorbelDriver = CorbelDriver /** * Instanciates new corbel driver @@ -1142,28 +1140,28 @@ * @return {corbel.CorbelDriver} */ corbel.getDriver = function(config) { - config = config || {}; + config = config || {} if (!config.urlBase) { - throw new Error('error:undefined:urlbase'); + throw new Error('error:undefined:urlbase') } - return new CorbelDriver(config); - }; - - })(); + return new CorbelDriver(config) + } + })() + /*globals corbel */ + ; (function() { - /** * A module to some library corbel.utils * @exports utils * @namespace * @memberof corbel */ - var utils = corbel.utils = {}; + var utils = corbel.utils = {} /** * Extend a given object with all the properties in passed-in object(s). @@ -1171,17 +1169,16 @@ * @return {Object} */ utils.extend = function(obj) { - Array.prototype.slice.call(arguments, 1).forEach(function(source) { if (source) { for (var prop in source) { - obj[prop] = source[prop]; + obj[prop] = source[prop] } } - }); + }) - return obj; - }; + return obj + } /** * Set up the prototype chain, for subclasses. Uses a hash of prototype properties and class properties to be extended. @@ -1190,61 +1187,57 @@ * @return {Object} Return a new object that inherit from the context object */ utils.inherit = function(prototypeProperties, staticProperties) { - var parent = this, - child; - + var parent = this + var child if (prototypeProperties && prototypeProperties.hasOwnProperty('constructor')) { - child = prototypeProperties.constructor; + child = prototypeProperties.constructor } else { child = function() { - return parent.apply(this, arguments); - }; + return parent.apply(this, arguments) + } } - utils.extend(child, parent, staticProperties); + utils.extend(child, parent, staticProperties) var Surrogate = function() { - this.constructor = child; - }; + this.constructor = child + } - Surrogate.prototype = parent.prototype; - child.prototype = new Surrogate; // jshint ignore:line + Surrogate.prototype = parent.prototype + child.prototype = new Surrogate() if (prototypeProperties) { - utils.extend(child.prototype, prototypeProperties); + utils.extend(child.prototype, prototypeProperties) } - child.__super__ = parent.prototype; - - return child; - - }; + child.__super__ = parent.prototype + return child + } /** * Generate a uniq random GUID */ utils.guid = function() { - function s4() { return Math.floor((1 + Math.random()) * 0x10000) .toString(16) - .substring(1); + .substring(1) } return s4() + s4() + '-' + s4() + '-' + s4() + '-' + - s4() + '-' + s4() + s4() + s4(); - }; + s4() + '-' + s4() + s4() + s4() + } /** * Reload browser */ utils.reload = function() { if (window !== undefined) { - window.location.reload(); + window.location.reload() } - }; + } /** * Serialize a plain object to query string @@ -1252,25 +1245,24 @@ * @return {String} */ utils.param = function(obj) { - var str = []; + var str = [] for (var p in obj) { if (obj.hasOwnProperty(p)) { - str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p])); + str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p])) } } - return str.join('&'); - }; - + return str.join('&') + } utils.toURLEncoded = function(obj) { - var str = []; + var str = [] for (var p in obj) { if (obj.hasOwnProperty(p)) { - str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p])); + str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p])) } } - return str.join('&'); - }; + return str.join('&') + } /** * Translate this full exampe query to a Corbel Compliant QueryString @@ -1337,175 +1329,175 @@ * aggregation: { * '$count': '*' * } - * }; + * } */ utils.serializeParams = function(params) { - var result = ''; + var result = '' if (params === undefined || params === null) { - return result; + return result } if (!(params instanceof Object) && (typeof params !== 'object')) { - throw new Error('expected params to be an Object type, but got ' + typeof params); + throw new Error('expected params to be an Object type, but got ' + typeof params) } function getJsonEncodedStringify(param) { - return encodeURIComponent(JSON.stringify(param)); + return encodeURIComponent(JSON.stringify(param)) } if (params.aggregation) { - result = 'api:aggregation=' + getJsonEncodedStringify(params.aggregation); + result = 'api:aggregation=' + getJsonEncodedStringify(params.aggregation) } function queryObjectToString(params, key) { - var result = ''; - var query; - params.queryDomain = params.queryDomain || 'api'; - result += params.queryDomain + ':' + key + '='; + var result = '' + var query + params.queryDomain = params.queryDomain || 'api' + result += params.queryDomain + ':' + key + '=' try { if (typeof params[key] === 'string') { - query = JSON.parse(params[key]); + query = JSON.parse(params[key]) } else { - //Clone the object we don't want to modify the original query object - query = JSON.parse(JSON.stringify(params[key])); + // Clone the object we don't want to modify the original query object + query = JSON.parse(JSON.stringify(params[key])) } - result += getJsonEncodedStringify(query); + result += getJsonEncodedStringify(query) - return result; + return result } catch (e) { - //Return the query even if it is not a valid object - return result + params[key]; + // Return the query even if it is not a valid object + return result + params[key] } } if (params.query) { - params.queryDomain = params.queryDomain || 'api'; - result += result ? '&' : ''; - result += queryObjectToString(params, 'query'); + params.queryDomain = params.queryDomain || 'api' + result += result ? '&' : '' + result += queryObjectToString(params, 'query') } if (params.queries) { params.queries.forEach(function(query) { - result += result ? '&' : ''; - result += queryObjectToString(query, 'query'); - }); + result += result ? '&' : '' + result += queryObjectToString(query, 'query') + }) } if (params.condition) { - params.queryDomain = params.queryDomain || 'api'; - result += result ? '&' : ''; - result += queryObjectToString(params, 'condition'); + params.queryDomain = params.queryDomain || 'api' + result += result ? '&' : '' + result += queryObjectToString(params, 'condition') } if (params.conditions) { params.conditions.forEach(function(condition) { - result += result ? '&' : ''; - result += queryObjectToString(condition, 'condition'); - }); + result += result ? '&' : '' + result += queryObjectToString(condition, 'condition') + }) } if (params.search) { - result += result ? '&' : ''; + result += result ? '&' : '' - result += 'api:search='; + result += 'api:search=' if (params.search instanceof Object) { - result += getJsonEncodedStringify(params.search); + result += getJsonEncodedStringify(params.search) } else { - result += encodeURIComponent(params.search); + result += encodeURIComponent(params.search) } if (params.hasOwnProperty('indexFieldsOnly')) { - result += '&api:indexFieldsOnly=' + getJsonEncodedStringify(params.indexFieldsOnly); + result += '&api:indexFieldsOnly=' + getJsonEncodedStringify(params.indexFieldsOnly) } } if (params.distinct) { - result += result ? '&' : ''; - result += 'api:distinct=' + encodeURIComponent((params.distinct instanceof Array ? params.distinct.join(',') : params.distinct)); + result += result ? '&' : '' + result += 'api:distinct=' + encodeURIComponent((params.distinct instanceof Array ? params.distinct.join(',') : params.distinct)) } if (params.sort) { - result += result ? '&' : ''; - result += 'api:sort=' + getJsonEncodedStringify(params.sort); + result += result ? '&' : '' + result += 'api:sort=' + getJsonEncodedStringify(params.sort) } if (params.pagination) { if (params.pagination.page || params.pagination.page === 0) { - result += result ? '&' : ''; - result += 'api:page=' + params.pagination.page; + result += result ? '&' : '' + result += 'api:page=' + params.pagination.page } if (params.pagination.pageSize || params.pagination.pageSize === 0) { - result += result ? '&' : ''; - result += 'api:pageSize=' + params.pagination.pageSize; + result += result ? '&' : '' + result += 'api:pageSize=' + params.pagination.pageSize } } if (params.customQueryParams) { Object.keys(params.customQueryParams).forEach(function(param) { - result += result ? '&' : ''; - result += param + '=' + encodeURIComponent(params.customQueryParams[param]); - }); + result += result ? '&' : '' + result += param + '=' + encodeURIComponent(params.customQueryParams[param]) + }) } - return result; - }; + return result + } utils.defaults = function(destiny, defaults) { Object.keys(defaults).forEach(function(key) { if (typeof(destiny[key]) === 'undefined') { - destiny[key] = defaults[key]; + destiny[key] = defaults[key] } - }); + }) - return destiny; - }; + return destiny + } utils.pick = function(object, keys) { - var destiny = {}; + var destiny = {} keys.forEach(function(key) { - destiny[key] = object[key]; - }); + destiny[key] = object[key] + }) - return destiny; - }; + return destiny + } utils.clone = function clone(item) { if (!item) { - return item; + return item } // null, undefined values check - var types = [Number, String, Boolean], - result; + var types = [Number, String, Boolean] + var result - // normalizing primitives if someone did new String('aaa'), or new Number('444'); + // normalizing primitives if someone did new String('aaa'), or new Number('444') types.forEach(function(type) { if (item instanceof type) { - result = type(item); + result = type(item) } - }); + }) if (typeof result === 'undefined') { if (Object.prototype.toString.call(item) === '[object Array]') { - result = []; + result = [] item.forEach(function(child, index) { - result[index] = clone(child); - }); + result[index] = clone(child) + }) } else if (typeof item === 'object') { // testing that this is DOM if (item.nodeType && typeof item.cloneNode === 'function') { - result = item.cloneNode(true); + result = item.cloneNode(true) } else if (!item.prototype) { // check that this is a literal if (item instanceof Date) { - result = new Date(item); + result = new Date(item) } else { // it is an object literal - result = {}; + result = {} for (var i in item) { - result[i] = clone(item[i]); + result[i] = clone(item[i]) } } } else { @@ -1513,18 +1505,18 @@ // just keep the reference, or create new object if (false && item.constructor) { // would not advice to do that, reason? Read below - result = new item.constructor(); + result = new item.constructor() } else { - result = item; + result = item } } } else { - result = item; + result = item } } - return result; - }; + return result + } /** * Change the keys of the object to lowercase due to @@ -1534,45 +1526,45 @@ */ utils.keysToLowerCase = function(obj) { if (obj === undefined || obj === null) { - return obj; + return obj } else { - var key; - var keys = Object.keys(obj); - var n = keys.length; - var newobj = {}; + var key + var keys = Object.keys(obj) + var n = keys.length + var newobj = {} while (n--) { - key = keys[n]; - newobj[key.toLowerCase()] = obj[key]; + key = keys[n] + newobj[key.toLowerCase()] = obj[key] } - return newobj; + return newobj } - }; + } utils.isJSON = function(string) { try { - JSON.parse(string); + JSON.parse(string) } catch (e) { - return false; + return false } - return true; - }; + return true + } utils.isStream = function(data) { if (data.pipe && typeof data.pipe === 'function') { - return true; + return true } else { - return false; + return false } - }; + } utils.arrayToObject = function(array) { - var object = {}; + var object = {} array.map(function(element, index) { - object[index] = element; - }); - return object; - }; + object[index] = element + }) + return object + } /** * Creates a copy of Array with the same inner elements @@ -1580,13 +1572,13 @@ * @return {Array} A copy version of the array */ utils.copyArray = function(list) { - var newList = new Array(list.length); - var i = list.length; + var newList = new Array(list.length) + var i = list.length while (i--) { - newList[i] = list[i]; + newList[i] = list[i] } - return newList; - }; + return newList + } /** * Convert data URI to Blob. @@ -1595,15 +1587,14 @@ * @return {Blob} */ utils.dataURItoBlob = function(dataURI) { - - var serialize; + var serialize if (corbel.Config.isNode) { - console.log('NODE'); - // node environment - serialize = require('atob'); + console.log('NODE') + // node environment + serialize = require('atob') } else { - console.log('BROWSER'); - serialize = root.atob; + console.log('BROWSER') + serialize = root.atob } /* @@ -1614,71 +1605,68 @@ * Phrantom has ton Blob() constructor support, * use BlobBuilder instead. */ - var BlobBuilder; - var BlobConstructor; + var BlobBuilder + var BlobConstructor if (corbel.Config.isBrowser) { BlobBuilder = window.BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || - window.MSBlobBuilder; - BlobConstructor = window.Blob; + window.MSBlobBuilder + BlobConstructor = window.Blob } // convert base64 to raw binary data held in a string - var byteString = serialize(dataURI.split(',')[1]); + var byteString = serialize(dataURI.split(',')[1]) // separate out the mime component - var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]; + var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0] // write the bytes of the string to an ArrayBuffer - var arrayBuffer = new ArrayBuffer(byteString.length); - var _ia = new Uint8Array(arrayBuffer); + var arrayBuffer = new ArrayBuffer(byteString.length) + var _ia = new Uint8Array(arrayBuffer) for (var i = 0; i < byteString.length; i++) { - _ia[i] = byteString.charCodeAt(i); + _ia[i] = byteString.charCodeAt(i) } - var blob; + var blob if (BlobBuilder) { - blob = new BlobBuilder(); - blob.append(arrayBuffer); - blob = blob.getBlob(mimeString); + blob = new BlobBuilder() + blob.append(arrayBuffer) + blob = blob.getBlob(mimeString) } else { blob = new BlobConstructor([_ia], { type: mimeString - }); + }) } - return blob; - }; - - return utils; + return blob + } - })(); + return utils + })() + /*globals corbel */ + ; (function() { - - - /** * A module to make values validation. * @exports validate * @namespace * @memberof app */ - corbel.validate = {}; + corbel.validate = {} corbel.validate.values = function(keys, obj) { - var that = this; + var that = this keys.forEach(function(key) { - that.value(key, obj[key]); - }); - return true; - }; + that.value(key, obj[key]) + }) + return true + } corbel.validate.value = function(key, value) { - return this.isDefined(value, key + ' value is mandatory and cannot be undefined'); - }; - + return this.isDefined(value, key + ' value is mandatory and cannot be undefined') + } /** * Checks if some value is not undefined @@ -1688,13 +1676,13 @@ * @return {Boolean} */ corbel.validate.isDefined = function(value, message) { - var isUndefined = value === undefined; + var isUndefined = value === undefined if (isUndefined && message) { - throw new Error(message); + throw new Error(message) } - return !isUndefined; - }; + return !isUndefined + } /** * Checks if some value is defined and throw error @@ -1705,13 +1693,13 @@ */ corbel.validate.failIfIsDefined = function(value, message) { - var isDefined = value !== undefined; + var isDefined = value !== undefined if (isDefined && message) { - throw new Error(message); + throw new Error(message) } - return !isDefined; - }; + return !isDefined + } /** * Checks whenever value are null or not @@ -1721,13 +1709,13 @@ * @return {Boolean} */ corbel.validate.isNotNull = function(value, message) { - var isNull = value === null; + var isNull = value === null if (isNull && message) { - throw new Error(message); + throw new Error(message) } - return !isNull; - }; + return !isNull + } /** * Checks whenever a value is not null and not undefined @@ -1737,8 +1725,8 @@ * @return {Boolean} */ corbel.validate.isValue = function(value, message) { - return this.isDefined(value, message) && this.isNotNull(value, message); - }; + return this.isDefined(value, message) && this.isNotNull(value, message) + } /** * Checks if a variable is a type of object @@ -1746,8 +1734,8 @@ * @return {Boolean} */ corbel.validate.isObject = function(obj) { - return typeof obj === 'object'; - }; + return typeof obj === 'object' + } /** * Checks whenever a value is greater than other @@ -1758,13 +1746,13 @@ * @return {Boolean} */ corbel.validate.isGreaterThan = function(value, greaterThan, message) { - var gt = this.isValue(value) && value > greaterThan; + var gt = this.isValue(value) && value > greaterThan if (!gt && message) { - throw new Error(message); + throw new Error(message) } - return gt; - }; + return gt + } /** * Checks whenever a value is greater or equal than other @@ -1775,19 +1763,20 @@ * @return {Boolean} */ corbel.validate.isGreaterThanOrEqual = function(value, isGreaterThanOrEqual, message) { - var gte = this.isValue(value) && value >= isGreaterThanOrEqual; + var gte = this.isValue(value) && value >= isGreaterThanOrEqual if (!gte && message) { - throw new Error(message); + throw new Error(message) } - return gte; - }; + return gte + } + })() - })(); + /* global corbel */ + ; (function() { - /** * Base object with * @class @@ -1796,8 +1785,8 @@ * @memberof corbel */ corbel.Object = function() { - return this; - }; + return this + } /** * Gets my user assets @@ -1805,15 +1794,15 @@ * @see corbel.utils.inherit * @return {Object} */ - corbel.Object.inherit = corbel.utils.inherit; + corbel.Object.inherit = corbel.utils.inherit - return corbel.Object; + return corbel.Object + })() - })(); + ; (function() { - /* jshint camelcase:false */ corbel.cryptography = (function() { /* @@ -1830,31 +1819,31 @@ * Configurable variables. You may need to tweak these to be compatible with * the server-side, but the defaults work in most cases. */ - var hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase */ - var b64pad = ''; /* base-64 pad character. "=" for strict RFC compliance */ + // var hexcase = 0 hex output format. 0 - lowercase; 1 - uppercase + var b64pad = '' /* base-64 pad character. "=" for strict RFC compliance */ function b64_hmac_sha256(k, d) { - return rstr2b64(rstr_hmac_sha256(str2rstr_utf8(k), str2rstr_utf8(d))); + return rstr2b64(rstr_hmac_sha256(str2rstr_utf8(k), str2rstr_utf8(d))) } /* * Calculate the HMAC-sha256 of a key and some data (raw strings) */ function rstr_hmac_sha256(key, data) { - var bkey = rstr2binb(key); + var bkey = rstr2binb(key) if (bkey.length > 16) { - bkey = binb_sha256(bkey, key.length * 8); + bkey = binb_sha256(bkey, key.length * 8) } - var ipad = Array(16), - opad = Array(16); + var ipad = Array(16) + var opad = Array(16) for (var i = 0; i < 16; i++) { - ipad[i] = bkey[i] ^ 0x36363636; - opad[i] = bkey[i] ^ 0x5C5C5C5C; + ipad[i] = bkey[i] ^ 0x36363636 + opad[i] = bkey[i] ^ 0x5C5C5C5C } - var hash = binb_sha256(ipad.concat(rstr2binb(data)), 512 + data.length * 8); - return binb2rstr(binb_sha256(opad.concat(hash), 512 + 256)); + var hash = binb_sha256(ipad.concat(rstr2binb(data)), 512 + data.length * 8) + return binb2rstr(binb_sha256(opad.concat(hash), 512 + 256)) } /* @@ -1864,19 +1853,19 @@ try { b64pad } catch (e) { - b64pad = ''; + b64pad = '' } - var tab = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; - var output = ''; - var len = input.length; + var tab = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' + var output = '' + var len = input.length for (var i = 0; i < len; i += 3) { - var triplet = (input.charCodeAt(i) << 16) | (i + 1 < len ? input.charCodeAt(i + 1) << 8 : 0) | (i + 2 < len ? input.charCodeAt(i + 2) : 0); + var triplet = (input.charCodeAt(i) << 16) | (i + 1 < len ? input.charCodeAt(i + 1) << 8 : 0) | (i + 2 < len ? input.charCodeAt(i + 2) : 0) for (var j = 0; j < 4; j++) { - if (i * 8 + j * 6 > input.length * 8) output += b64pad; - else output += tab.charAt((triplet >>> 6 * (3 - j)) & 0x3F); + if (i * 8 + j * 6 > input.length * 8) output += b64pad + else output += tab.charAt((triplet >>> 6 * (3 - j)) & 0x3F) } } - return output; + return output } /* @@ -1884,36 +1873,36 @@ * For efficiency, this assumes the input is valid utf-16. */ function str2rstr_utf8(input) { - var output = ''; - var i = -1; - var x, y; + var output = '' + var i = -1 + var x, y while (++i < input.length) { /* Decode utf-16 surrogate pairs */ - x = input.charCodeAt(i); - y = i + 1 < input.length ? input.charCodeAt(i + 1) : 0; - if (0xD800 <= x && x <= 0xDBFF && 0xDC00 <= y && y <= 0xDFFF) { - x = 0x10000 + ((x & 0x03FF) << 10) + (y & 0x03FF); - i++; + x = input.charCodeAt(i) + y = i + 1 < input.length ? input.charCodeAt(i + 1) : 0 + if (x > 0xD800 && x <= 0xDBFF && y > 0xDC00 && y <= 0xDFFF) { + x = 0x10000 + ((x & 0x03FF) << 10) + (y & 0x03FF) + i++ } /* Encode output as utf-8 */ - if (x <= 0x7F) - output += String.fromCharCode(x); - else if (x <= 0x7FF) - output += String.fromCharCode(0xC0 | ((x >>> 6) & 0x1F), - 0x80 | (x & 0x3F)); - else if (x <= 0xFFFF) + if (x <= 0x7F) { + output += String.fromCharCode(x) + } else if (x <= 0x7FF) { + output += String.fromCharCode(0xC0 | ((x >>> 6) & 0x1F), 0x80 | (x & 0x3F)) + } else if (x <= 0xFFFF) { output += String.fromCharCode(0xE0 | ((x >>> 12) & 0x0F), 0x80 | ((x >>> 6) & 0x3F), - 0x80 | (x & 0x3F)); - else if (x <= 0x1FFFFF) + 0x80 | (x & 0x3F)) + } else if (x <= 0x1FFFFF) { output += String.fromCharCode(0xF0 | ((x >>> 18) & 0x07), 0x80 | ((x >>> 12) & 0x3F), 0x80 | ((x >>> 6) & 0x3F), - 0x80 | (x & 0x3F)); + 0x80 | (x & 0x3F)) + } } - return output; + return output } /* @@ -1921,60 +1910,63 @@ * Characters >255 have their high-byte silently ignored. */ function rstr2binb(input) { - var output = Array(input.length >> 2); - for (var i = 0; i < output.length; i++) - output[i] = 0; - for (var i = 0; i < input.length * 8; i += 8) - output[i >> 5] |= (input.charCodeAt(i / 8) & 0xFF) << (24 - i % 32); - return output; + var output = Array(input.length >> 2) + for (var i = 0; i < output.length; i++) { + output[i] = 0 + } + for (var j = 0; j < input.length * 8; j += 8) { + output[j >> 5] |= (input.charCodeAt(j / 8) & 0xFF) << (24 - j % 32) + } + return output } /* * Convert an array of big-endian words to a string */ function binb2rstr(input) { - var output = ''; - for (var i = 0; i < input.length * 32; i += 8) - output += String.fromCharCode((input[i >> 5] >>> (24 - i % 32)) & 0xFF); - return output; + var output = '' + for (var i = 0; i < input.length * 32; i += 8) { + output += String.fromCharCode((input[i >> 5] >>> (24 - i % 32)) & 0xFF) + } + return output } /* * Main sha256 function, with its support functions */ function sha256_S(X, n) { - return (X >>> n) | (X << (32 - n)); + return (X >>> n) | (X << (32 - n)) } function sha256_R(X, n) { - return (X >>> n); + return (X >>> n) } function sha256_Ch(x, y, z) { - return ((x & y) ^ ((~x) & z)); + return ((x & y) ^ ((~x) & z)) } function sha256_Maj(x, y, z) { - return ((x & y) ^ (x & z) ^ (y & z)); + return ((x & y) ^ (x & z) ^ (y & z)) } function sha256_Sigma0256(x) { - return (sha256_S(x, 2) ^ sha256_S(x, 13) ^ sha256_S(x, 22)); + return (sha256_S(x, 2) ^ sha256_S(x, 13) ^ sha256_S(x, 22)) } function sha256_Sigma1256(x) { - return (sha256_S(x, 6) ^ sha256_S(x, 11) ^ sha256_S(x, 25)); + return (sha256_S(x, 6) ^ sha256_S(x, 11) ^ sha256_S(x, 25)) } function sha256_Gamma0256(x) { - return (sha256_S(x, 7) ^ sha256_S(x, 18) ^ sha256_R(x, 3)); + return (sha256_S(x, 7) ^ sha256_S(x, 18) ^ sha256_R(x, 3)) } function sha256_Gamma1256(x) { - return (sha256_S(x, 17) ^ sha256_S(x, 19) ^ sha256_R(x, 10)); + return (sha256_S(x, 17) ^ sha256_S(x, 19) ^ sha256_R(x, 10)) } - var sha256_K = new Array( + var sha256_K = [ 1116352408, 1899447441, -1245643825, -373957723, 961987163, 1508970993, -1841331548, -1424204075, -670586216, 310598401, 607225278, 1426881987, 1925078388, -2132889090, -1680079193, -1046744716, -459576895, -272742522, 264347078, 604807628, 770255983, 1249150122, 1555081692, 1996064986, -1740746414, -1473132947, -1341970488, -1084653625, -958395405, -710438585, @@ -1982,63 +1974,67 @@ 1695183700, 1986661051, -2117940946, -1838011259, -1564481375, -1474664885, -1035236496, -949202525, -778901479, -694614492, -200395387, 275423344, 430227734, 506948616, 659060556, 883997877, 958139571, 1322822218, 1537002063, 1747873779, 1955562222, 2024104815, -2067236844, -1933114872, -1866530822, -1538233109, -1090935817, -965641998 - ); + ] function binb_sha256(m, l) { - var HASH = new Array(1779033703, -1150833019, 1013904242, -1521486534, - 1359893119, -1694144372, 528734635, 1541459225); - var W = new Array(64); - var a, b, c, d, e, f, g, h; - var i, j, T1, T2; + var HASH = [1779033703, -1150833019, 1013904242, -1521486534, + 1359893119, -1694144372, 528734635, 1541459225 + ] + var W = new Array(64) + var a, b, c, d, e, f, g, h + var i, j, T1, T2 /* append padding */ - m[l >> 5] |= 0x80 << (24 - l % 32); - m[((l + 64 >> 9) << 4) + 15] = l; + m[l >> 5] |= 0x80 << (24 - l % 32) + m[((l + 64 >> 9) << 4) + 15] = l for (i = 0; i < m.length; i += 16) { - a = HASH[0]; - b = HASH[1]; - c = HASH[2]; - d = HASH[3]; - e = HASH[4]; - f = HASH[5]; - g = HASH[6]; - h = HASH[7]; + a = HASH[0] + b = HASH[1] + c = HASH[2] + d = HASH[3] + e = HASH[4] + f = HASH[5] + g = HASH[6] + h = HASH[7] for (j = 0; j < 64; j++) { - if (j < 16) W[j] = m[j + i]; - else W[j] = safe_add(safe_add(safe_add(sha256_Gamma1256(W[j - 2]), W[j - 7]), - sha256_Gamma0256(W[j - 15])), W[j - 16]); + if (j < 16) { + W[j] = m[j + i] + } else { + W[j] = safe_add(safe_add(safe_add(sha256_Gamma1256(W[j - 2]), W[j - 7]), + sha256_Gamma0256(W[j - 15])), W[j - 16]) + } T1 = safe_add(safe_add(safe_add(safe_add(h, sha256_Sigma1256(e)), sha256_Ch(e, f, g)), - sha256_K[j]), W[j]); - T2 = safe_add(sha256_Sigma0256(a), sha256_Maj(a, b, c)); - h = g; - g = f; - f = e; - e = safe_add(d, T1); - d = c; - c = b; - b = a; - a = safe_add(T1, T2); + sha256_K[j]), W[j]) + T2 = safe_add(sha256_Sigma0256(a), sha256_Maj(a, b, c)) + h = g + g = f + f = e + e = safe_add(d, T1) + d = c + c = b + b = a + a = safe_add(T1, T2) } - HASH[0] = safe_add(a, HASH[0]); - HASH[1] = safe_add(b, HASH[1]); - HASH[2] = safe_add(c, HASH[2]); - HASH[3] = safe_add(d, HASH[3]); - HASH[4] = safe_add(e, HASH[4]); - HASH[5] = safe_add(f, HASH[5]); - HASH[6] = safe_add(g, HASH[6]); - HASH[7] = safe_add(h, HASH[7]); + HASH[0] = safe_add(a, HASH[0]) + HASH[1] = safe_add(b, HASH[1]) + HASH[2] = safe_add(c, HASH[2]) + HASH[3] = safe_add(d, HASH[3]) + HASH[4] = safe_add(e, HASH[4]) + HASH[5] = safe_add(f, HASH[5]) + HASH[6] = safe_add(g, HASH[6]) + HASH[7] = safe_add(h, HASH[7]) } - return HASH; + return HASH } function safe_add(x, y) { - var lsw = (x & 0xFFFF) + (y & 0xFFFF); - var msw = (x >> 16) + (y >> 16) + (lsw >> 16); - return (msw << 16) | (lsw & 0xFFFF); + var lsw = (x & 0xFFFF) + (y & 0xFFFF) + var msw = (x >> 16) + (y >> 16) + (lsw >> 16) + return (msw << 16) | (lsw & 0xFFFF) } /*! base64x-1.1.3 (c) 2012-2014 Kenji Urushima | kjur.github.com/jsjws/license @@ -2084,7 +2080,8 @@ * @see 'jwjws'(JWS JavaScript Library) home page http://kjur.github.com/jsjws/ * @see 'jwrsasign'(RSA Sign JavaScript Library) home page http://kjur.github.com/jsrsasign/ */ - function Base64x() {} + + // function Base64x () {} // ==== base64 / base64url ================================ /** @@ -2094,13 +2091,14 @@ * @return {String} Base64URL encoded string */ function b64tob64u(s) { - s = s.replace(/\=/g, ''); - s = s.replace(/\+/g, '-'); - s = s.replace(/\//g, '_'); - return s; + s = s.replace(/\=/g, '') + s = s.replace(/\+/g, '-') + s = s.replace(/\//g, '_') + return s } - var utf8tob64u, b64utoutf8; + // var utf8tob64u + // var b64utoutf8 return { rstr2b64: rstr2b64, @@ -2108,17 +2106,16 @@ b64_hmac_sha256: b64_hmac_sha256, b64tob64u: b64tob64u } - })(); - - })(); + })() + })() /* jshint camelcase:false */ + /* global corbel */ + ; (function() { - var jwt = corbel.jwt = { - EXPIRATION: 3500, ALGORITHM: 'HS256', TYP: 'JWT', @@ -2133,21 +2130,21 @@ * @return {String} jwt JWT string */ generate: function(claims, secret, alg) { - claims = claims || {}; - claims.exp = claims.exp || jwt._generateExp(); + claims = claims || {} + claims.exp = claims.exp || jwt._generateExp() if (!claims.iss) { - throw new Error('jwt:undefined:iss'); + throw new Error('jwt:undefined:iss') } if (!claims.aud) { - throw new Error('jwt:undefined:aud'); + throw new Error('jwt:undefined:aud') } - return jwt._generate(claims, secret, alg); + return jwt._generate(claims, secret, alg) }, _generate: function(claims, secret, alg) { - alg = alg || jwt.ALGORITHM; + alg = alg || jwt.ALGORITHM // Ensure claims specific order var claimsKeys = [ @@ -2164,81 +2161,82 @@ 'basic_auth.password', 'device_id' - ]; + ] - var finalClaims = {}; + var finalClaims = {} claimsKeys.forEach(function(key) { if (claims[key]) { - finalClaims[key] = claims[key]; + finalClaims[key] = claims[key] } - }); + }) - corbel.utils.extend(finalClaims, claims); + corbel.utils.extend(finalClaims, claims) if (Array.isArray(finalClaims.scope)) { - finalClaims.scope = finalClaims.scope.join(' '); + finalClaims.scope = finalClaims.scope.join(' ') } var bAlg = corbel.cryptography.rstr2b64(corbel.cryptography.str2rstr_utf8(JSON.stringify({ - typ: jwt.TYP, - alg: alg - }))), - bClaims = corbel.cryptography.rstr2b64(corbel.cryptography.str2rstr_utf8(JSON.stringify(finalClaims))), - segment = bAlg + '.' + bClaims, - assertion = corbel.cryptography.b64tob64u(corbel.cryptography.b64_hmac_sha256(secret, segment)); + typ: jwt.TYP, + alg: alg + }))) + var bClaims = corbel.cryptography.rstr2b64(corbel.cryptography.str2rstr_utf8(JSON.stringify(finalClaims))) + var segment = bAlg + '.' + bClaims + var assertion = corbel.cryptography.b64tob64u(corbel.cryptography.b64_hmac_sha256(secret, segment)) - return segment + '.' + assertion; + return segment + '.' + assertion }, _generateExp: function() { - return Math.round((new Date().getTime() / 1000)) + jwt.EXPIRATION; + return Math.round((new Date().getTime() / 1000)) + jwt.EXPIRATION }, decode: function(assertion) { - var serialize; + var serialize if (corbel.Config.isNode) { // node environment - serialize = require('atob'); + serialize = require('atob') } else { - serialize = root.atob; + serialize = root.atob } - var decoded = assertion.split('.'); + var decoded = assertion.split('.') try { - decoded[0] = JSON.parse(serialize(decoded[0])); + decoded[0] = JSON.parse(serialize(decoded[0])) } catch (e) { - decoded[0] = false; + decoded[0] = false } try { - decoded[1] = JSON.parse(serialize(decoded[1])); + decoded[1] = JSON.parse(serialize(decoded[1])) } catch (e) { - decoded[1] = false; + decoded[1] = false } if (!decoded[0] && !decoded[1]) { - throw new Error('corbel:jwt:decode:invalid_assertion'); + throw new Error('corbel:jwt:decode:invalid_assertion') } - decoded[0] = decoded[0] || {}; - decoded[1] = decoded[1] || {}; + decoded[0] = decoded[0] || {} + decoded[1] = decoded[1] || {} Object.keys(decoded[1]).forEach(function(key) { - decoded[0][key] = decoded[1][key]; - }); + decoded[0][key] = decoded[1][key] + }) - return decoded[0]; + return decoded[0] } - }; + } - return jwt; + return jwt + })() - })(); + /* global corbel XMLHttpRequest*/ + ; (function() { - /** * Request object available for brwoser and node environment * @exports request @@ -2251,7 +2249,6 @@ * @namespace */ method: { - /** * GET constant * @constant @@ -2296,7 +2293,7 @@ */ HEAD: 'HEAD' } - }; + } /** * Serialize handlers @@ -2310,9 +2307,9 @@ */ json: function(data, cb) { if (typeof data !== 'string') { - cb(JSON.stringify(data)); + cb(JSON.stringify(data)) } else { - cb(data); + cb(data) } }, /** @@ -2321,7 +2318,7 @@ * @return {string} */ 'form-urlencoded': function(data, cb) { - cb(corbel.utils.toURLEncoded(data)); + cb(corbel.utils.toURLEncoded(data)) }, /** * dataURI serialize handler @@ -2331,10 +2328,10 @@ dataURI: function(data, cb) { if (corbel.Config.isNode) { // in node transform to stream - cb(corbel.utils.toURLEncoded(data)); + cb(corbel.utils.toURLEncoded(data)) } else { // in browser transform to blob - cb(corbel.utils.dataURItoBlob(data)); + cb(corbel.utils.dataURItoBlob(data)) } }, /** @@ -2345,9 +2342,9 @@ */ blob: function(data, cb) { if (data instanceof ArrayBuffer) { - throw new Error('ArrayBuffer is not supported, please use Blob'); + throw new Error('ArrayBuffer is not supported, please use Blob') } else { - cb(data); + cb(data) } }, /** @@ -2357,12 +2354,12 @@ */ stream: function(data, cb) { if (data instanceof ArrayBuffer) { - throw new Error('ArrayBuffer is not supported, please use Blob, File, Stream or ArrayBufferView'); + throw new Error('ArrayBuffer is not supported, please use Blob, File, Stream or ArrayBufferView') } else { - cb(data); + cb(data) } } - }; + } /** * Serialize hada with according contentType handler @@ -2374,16 +2371,16 @@ request.serialize = function(data, contentType, cb) { var contentTypeSerializable = Object.keys(request.serializeHandlers).filter(function(type) { if (contentType.indexOf(type) !== -1) { - return type; + return type } - }); + }) if (contentTypeSerializable.length > 0) { - request.serializeHandlers[contentTypeSerializable[0]](data, cb); + request.serializeHandlers[contentTypeSerializable[0]](data, cb) } else { - cb(data); + cb(data) } - }; + } /** * Parse handlers @@ -2396,15 +2393,15 @@ * @return {mixed} */ json: function(data) { - data = data || '{}'; + data = data || '{}' if (typeof data === 'string') { - data = JSON.parse(data); + data = JSON.parse(data) } - return data; + return data } // 'blob' type do not require any process // @todo: xml - }; + } /** * Process the server response data to the specified object/array/blob/byteArray/text @@ -2414,23 +2411,23 @@ * @return {mixed} Processed data */ request.parse = function(data, responseType, dataType) { - var parsed; + var parsed Object.keys(request.parseHandlers).forEach(function(type) { if (responseType && responseType.indexOf(type) !== -1) { - parsed = request.parseHandlers[type](data, dataType); + parsed = request.parseHandlers[type](data, dataType) } - }); - parsed = parsed || data; - return parsed; - }; + }) + parsed = parsed || data + return parsed + } function doRequest(module, params, resolver) { if (corbel.Config.isBrowser) { - //browser - request._browserAjax.call(module, params, resolver); + // browser + request._browserAjax.call(module, params, resolver) } else { - //nodejs - request._nodeAjax.call(module, params, resolver); + // nodejs + request._nodeAjax.call(module, params, resolver) } } @@ -2449,15 +2446,15 @@ * @return {Promise} Promise about the request status and response */ request.send = function(options, driver) { - options = options || {}; - var module = this; + options = options || {} + var module = this if (!options.url) { - throw new Error('undefined:url'); + throw new Error('undefined:url') } if (typeof(options.url) !== 'string') { - throw new Error('invalid:url', options.url); + throw new Error('invalid:url', options.url) } var params = { @@ -2469,38 +2466,38 @@ responseType: options.responseType, withCredentials: options.withCredentials || true, useCookies: options.useCookies || false - }; + } - params = rewriteRequestToPostIfUrlLengthIsTooLarge(options, params); + params = rewriteRequestToPostIfUrlLengthIsTooLarge(options, params) // default content-type - params.headers['content-type'] = options.contentType || 'application/json'; + params.headers['content-type'] = options.contentType || 'application/json' - var dataMethods = [request.method.PUT, request.method.POST, request.method.PATCH]; + var dataMethods = [request.method.PUT, request.method.POST, request.method.PATCH] - var resolver; + var resolver var promise = new Promise(function(resolve, reject) { resolver = { resolve: resolve, reject: reject - }; + } if (driver) { - driver.trigger('request', params); + driver.trigger('request', params) } - }); + }) if (dataMethods.indexOf(params.method) !== -1) { request.serialize(options.data, params.headers['content-type'], function(serialized) { - params.data = serialized; - doRequest(module, params, resolver); - }); + params.data = serialized + doRequest(module, params, resolver) + }) } else { - doRequest(module, params, resolver); + doRequest(module, params, resolver) } - return promise; - }; + return promise + } var xhrSuccessStatus = { // file protocol always yields status code 0, assume 200 @@ -2508,7 +2505,7 @@ // Support: IE9 // #1450: sometimes IE returns 1223 when it should be 204 1223: 204 - }; + } /** * Process server response @@ -2518,45 +2515,42 @@ * @param {function} callbackError */ var processResponse = function(response, resolver, callbackSuccess, callbackError) { + // xhr = xhr.target || xhr || {} + var statusCode = xhrSuccessStatus[response.status] || response.status + var statusType = Number(response.status.toString()[0]) + var promiseResponse - //xhr = xhr.target || xhr || {}; - var statusCode = xhrSuccessStatus[response.status] || response.status, - statusType = Number(response.status.toString()[0]), - promiseResponse; - - var data = response.response; - var headers = corbel.utils.keysToLowerCase(response.headers); + var data = response.response + var headers = corbel.utils.keysToLowerCase(response.headers) if (statusType <= 3 && !response.error) { - if (response.response) { - data = request.parse(response.response, response.responseType, response.dataType); + data = request.parse(response.response, response.responseType, response.dataType) } if (callbackSuccess) { - callbackSuccess.call(this, data, statusCode, response.responseObject, headers); + callbackSuccess.call(this, data, statusCode, response.responseObject, headers) } promiseResponse = { data: data, status: statusCode, headers: headers - }; + } - promiseResponse[response.responseObjectType] = response.responseObject; + promiseResponse[response.responseObjectType] = response.responseObject - resolver.resolve(promiseResponse); + resolver.resolve(promiseResponse) } else { - - var disconnected = response.error && response.status === 0; - statusCode = disconnected ? 0 : statusCode; + var disconnected = response.error && response.status === 0 + statusCode = disconnected ? 0 : statusCode if (callbackError) { - callbackError.call(this, response.error, statusCode, response.responseObject, headers); + callbackError.call(this, response.error, statusCode, response.responseObject, headers) } if (response.response) { - data = request.parse(response.response, response.responseType, response.dataType); + data = request.parse(response.response, response.responseType, response.dataType) } promiseResponse = { @@ -2564,61 +2558,61 @@ status: statusCode, error: response.error, headers: headers - }; + } - promiseResponse[response.responseObjectType] = response.responseObject; + promiseResponse[response.responseObjectType] = response.responseObject - resolver.reject(promiseResponse); + resolver.reject(promiseResponse) } - }; + } var rewriteRequestToPostIfUrlLengthIsTooLarge = function(options, params) { - var AUTOMATIC_HTTP_METHOD_OVERRIDE = corbel.Config.AUTOMATIC_HTTP_METHOD_OVERRIDE || true; - var HTTP_METHOD_OVERRIDE_WITH_URL_SIZE_BIGGER_THAN = corbel.Config.HTTP_METHOD_OVERRIDE_WITH_URL_SIZE_BIGGER_THAN || 2048; + var AUTOMATIC_HTTP_METHOD_OVERRIDE = corbel.Config.AUTOMATIC_HTTP_METHOD_OVERRIDE || true + var HTTP_METHOD_OVERRIDE_WITH_URL_SIZE_BIGGER_THAN = corbel.Config.HTTP_METHOD_OVERRIDE_WITH_URL_SIZE_BIGGER_THAN || 2048 if (AUTOMATIC_HTTP_METHOD_OVERRIDE && params.method === request.method.GET && params.url.length > HTTP_METHOD_OVERRIDE_WITH_URL_SIZE_BIGGER_THAN) { - var url = params.url.split('?'); - params.method = request.method.POST; - params.headers['X-HTTP-Method-Override'] = request.method.GET; - params.url = url[0]; - options.data = encodeUrlToForm(url[1]); - options.contentType = 'application/x-www-form-urlencoded'; - } - return params; - }; + var url = params.url.split('?') + params.method = request.method.POST + params.headers['X-HTTP-Method-Override'] = request.method.GET + params.url = url[0] + options.data = encodeUrlToForm(url[1]) + options.contentType = 'application/x-www-form-urlencoded' + } + return params + } var encodeUrlToForm = function(url) { - var form = {}; + var form = {} url.split('&').forEach(function(formEntry) { - var formPair = formEntry.split('='); - //value require double encode in Override Method Filter - form[formPair[0]] = formPair[1]; - }); - return form; - }; + var formPair = formEntry.split('=') + // value require double encode in Override Method Filter + form[formPair[0]] = formPair[1] + }) + return form + } request._getNodeRequestAjax = function(params) { - var requestAjax = require('request'); + var requestAjax = require('request') if (request.isCrossDomain(params.url) && params.withCredentials && params.useCookies) { requestAjax = requestAjax.defaults({ jar: true - }); + }) } - return requestAjax; - }; + return requestAjax + } request._getNodeRequestCallback = function(context, params, resolver) { return function(error, response, body) { - var responseType; - var status; + var responseType + var status if (error) { - responseType = undefined; - status = 0; + responseType = undefined + status = 0 } else { - responseType = response.responseType || response.headers['content-type']; - status = response.statusCode; + responseType = response.responseType || response.headers['content-type'] + status = response.statusCode } processResponse.call(context, { @@ -2630,33 +2624,30 @@ headers: response ? response.headers : {}, responseObjectType: 'response', error: error - }, resolver, params.callbackSuccess, params.callbackError); - - }; - }; + }, resolver, params.callbackSuccess, params.callbackError) + } + } request._nodeAjax = function(params, resolver) { - var requestAjax = request._getNodeRequestAjax(params); + var requestAjax = request._getNodeRequestAjax(params) var requestOptions = { method: params.method, url: params.url, - headers: params.headers, - }; + headers: params.headers + } - var data = params.data || ''; + var data = params.data || '' - var callbackRequest = request._getNodeRequestCallback(this, params, resolver); + var callbackRequest = request._getNodeRequestCallback(this, params, resolver) if (corbel.utils.isStream(data)) { - data.pipe(requestAjax(requestOptions, callbackRequest)); + data.pipe(requestAjax(requestOptions, callbackRequest)) } else { - requestOptions.body = data; - requestAjax(requestOptions, callbackRequest); + requestOptions.body = data + requestAjax(requestOptions, callbackRequest) } - - - }; + } /** * Check if an url should be process as a crossdomain resource. @@ -2665,11 +2656,11 @@ */ request.isCrossDomain = function(url) { if (url && typeof(url) === 'string' && url.indexOf('http') !== -1) { - return true; + return true } else { - return false; + return false } - }; + } /** * https://gist.github.com/monsur/706839 @@ -2677,46 +2668,46 @@ * @return {Object} */ request._parseResponseHeaders = function(headerStr) { - var headers = {}; + var headers = {} if (!headerStr) { - return headers; + return headers } - var headerPairs = headerStr.split('\u000d\u000a'); + var headerPairs = headerStr.split('\u000d\u000a') for (var i = 0; i < headerPairs.length; i++) { - var headerPair = headerPairs[i]; - // Can't use split() here because it does the wrong thing - // if the header value has the string ": " in it. - var index = headerPair.indexOf('\u003a\u0020'); + var headerPair = headerPairs[i] + // Can't use split() here because it does the wrong thing + // if the header value has the string ": " in it. + var index = headerPair.indexOf('\u003a\u0020') if (index > 0) { - var key = headerPair.substring(0, index); - var val = headerPair.substring(index + 2); - headers[key] = val; + var key = headerPair.substring(0, index) + var val = headerPair.substring(index + 2) + headers[key] = val } } - return headers; - }; + return headers + } request._browserAjax = function(params, resolver) { - var httpReq = new XMLHttpRequest(); + var httpReq = new XMLHttpRequest() // jshint ignore:line - httpReq.open(params.method, params.url, true); + httpReq.open(params.method, params.url, true) if (request.isCrossDomain(params.url) && params.withCredentials) { - httpReq.withCredentials = true; + httpReq.withCredentials = true } /* add request headers */ for (var header in params.headers) { if (params.headers.hasOwnProperty(header)) { - httpReq.setRequestHeader(header, params.headers[header]); + httpReq.setRequestHeader(header, params.headers[header]) } } // 'blob' support - httpReq.responseType = params.responseType || httpReq.responseType; + httpReq.responseType = params.responseType || httpReq.responseType httpReq.onload = function(xhr) { - xhr = xhr.target || xhr; // only for mock testing purpose + xhr = xhr.target || xhr // only for mock testing purpose processResponse.call(this, { responseObject: xhr, @@ -2727,17 +2718,16 @@ headers: request._parseResponseHeaders(xhr.getAllResponseHeaders()), responseObjectType: 'xhr', error: xhr.error - }, resolver, params.callbackSuccess, params.callbackError); + }, resolver, params.callbackSuccess, params.callbackError) - //delete callbacks - }.bind(this); + // delete callbacks + }.bind(this) - //response fail () + // response fail () httpReq.onerror = function(xhr) { + xhr = xhr.target || xhr // only for fake sinon response xhr - xhr = xhr.target || xhr; // only for fake sinon response xhr - - var error = xhr.error ? xhr.error : true; + var error = xhr.error ? xhr.error : true processResponse.call(this, { responseObject: xhr, @@ -2747,26 +2737,25 @@ status: xhr.status, responseObjectType: 'xhr', error: error - }, resolver, params.callbackSuccess, params.callbackError); - - }.bind(this); - + }, resolver, params.callbackSuccess, params.callbackError) + }.bind(this) if (params.data) { - httpReq.send(params.data); + httpReq.send(params.data) } else { - //IE fix, send nothing (not null or undefined) - httpReq.send(); + // IE fix, send nothing (not null or undefined) + httpReq.send() } - }; + } - return request; + return request + })() - })(); + /*globals corbel */ + ; (function() { - /** * A base object to inherit from for make corbel-js requests with custom behavior. * @exports Services @@ -2774,8 +2763,7 @@ * @extends corbel.Object * @memberof corbel */ - var Services = corbel.Services = corbel.Object.inherit({ //instance props - + var Services = corbel.Services = corbel.Object.inherit({ // instance props /** * Creates a new Services * @memberof corbel.Services.prototype @@ -2783,13 +2771,13 @@ * @return {corbel.Services} */ constructor: function(driver) { - this.driver = driver; + this.driver = driver }, extractLocationId: function(res) { - console.log('corbel-js:service:extractLocationId', res); - var uri = res.jqXHR.getResponseHeader('Location'); - return uri ? uri.substr(uri.lastIndexOf('/') + 1) : undefined; + console.log('corbel-js:service:extractLocationId', res) + var uri = res.jqXHR.getResponseHeader('Location') + return uri ? uri.substr(uri.lastIndexOf('/') + 1) : undefined }, /** @@ -2803,58 +2791,52 @@ * @param {object} args The request arguments. */ request: function(args) { + this.driver.trigger('service:request:before', args) - this.driver.trigger('service:request:before', args); - - var that = this; + var that = this return this._requestWithRetries(args).then(function(response) { - that.driver.trigger('service:request:after', response); - that.driver.config.set(corbel.Services._UNAUTHORIZED_NUM_RETRIES, 0); - return response; + that.driver.trigger('service:request:after', response) + that.driver.config.set(corbel.Services._UNAUTHORIZED_NUM_RETRIES, 0) + return response }).catch(function(error) { - that.driver.trigger('service:request:after', error); - that.driver.config.set(corbel.Services._UNAUTHORIZED_NUM_RETRIES, 0); - throw error; - }); - + that.driver.trigger('service:request:after', error) + that.driver.config.set(corbel.Services._UNAUTHORIZED_NUM_RETRIES, 0) + throw error + }) }, _requestWithRetries: function(args) { - var that = this; - var maxRetries = corbel.Services._UNAUTHORIZED_MAX_RETRIES; - var requestParameters = that._buildParams(args); + var that = this + var maxRetries = corbel.Services._UNAUTHORIZED_MAX_RETRIES + var requestParameters = that._buildParams(args) return that._doRequest(requestParameters) .catch(function(response) { - - var retries = that.driver.config.get(corbel.Services._UNAUTHORIZED_NUM_RETRIES, 0); + var retries = that.driver.config.get(corbel.Services._UNAUTHORIZED_NUM_RETRIES, 0) if (retries < maxRetries && response.status === corbel.Services._UNAUTHORIZED_STATUS_CODE) { - - //A 401 request within, refresh the token and retry the request. + // A 401 request within, refresh the token and retry the request. return that._refreshToken() .then(function() { - - that.driver.config.set(corbel.Services._UNAUTHORIZED_NUM_RETRIES, retries + 1); - //@TODO: see if we need to upgrade the token to access assets. + that.driver.config.set(corbel.Services._UNAUTHORIZED_NUM_RETRIES, retries + 1) + // @TODO: see if we need to upgrade the token to access assets. return that._requestWithRetries(args).catch(function(retryResponse) { // rejects whole promise with the retry response - response = retryResponse; - throw response; - }); - }).catch(function() { - //Has failed refreshing, reject request - console.log('corbeljs:services:token:refresh:fail'); - - throw response; - }); - + response = retryResponse + throw response + }) + }) + .catch(function() { + // Has failed refreshing, reject request + console.log('corbeljs:services:token:refresh:fail') + + throw response + }) } else { - console.log('corbeljs:services:token:no_refresh', response.status); - throw response; + console.log('corbeljs:services:token:no_refresh', response.status) + throw response } - - }); + }) }, /** @@ -2864,42 +2846,37 @@ * @return {Promise} */ _doRequest: function(params) { - var that = this; + var that = this return corbel.request.send(params, that.driver).then(function(response) { + that.driver.config.set(corbel.Services._FORCE_UPDATE_STATUS, 0) + that.driver.config.set(corbel.Services._UNAUTHORIZED_NUM_RETRIES, 0) - that.driver.config.set(corbel.Services._FORCE_UPDATE_STATUS, 0); - that.driver.config.set(corbel.Services._UNAUTHORIZED_NUM_RETRIES, 0); - - return response; - + return response }).catch(function(response) { // Force update if (response.status === corbel.Services._FORCE_UPDATE_STATUS_CODE && response.textStatus === corbel.Services._FORCE_UPDATE_TEXT) { - - var retries = that.driver.config.get(corbel.Services._FORCE_UPDATE_STATUS, 0); + var retries = that.driver.config.get(corbel.Services._FORCE_UPDATE_STATUS, 0) if (retries < corbel.Services._FORCE_UPDATE_MAX_RETRIES) { - retries++; - that.driver.config.set(corbel.Services._FORCE_UPDATE_STATUS, retries); + retries++ + that.driver.config.set(corbel.Services._FORCE_UPDATE_STATUS, retries) - that.driver.trigger('force:update', response); + that.driver.trigger('force:update', response) - throw response; + throw response } else { - throw response; + throw response } } else { - throw response; + throw response } - - }); + }) }, - _refreshToken: function() { - var tokenObject = this.driver.config.get(corbel.Iam.IAM_TOKEN, {}); + var tokenObject = this.driver.config.get(corbel.Iam.IAM_TOKEN, {}) - return this._refreshHandler(tokenObject); + return this._refreshHandler(tokenObject) }, /** * Default token refresh handler @@ -2907,33 +2884,32 @@ * @return {Promise} */ _refreshHandler: function(tokenObject) { - var that = this; + var that = this if (this.driver._refreshHandlerPromise) { - return this.driver._refreshHandlerPromise; + return this.driver._refreshHandlerPromise } if (tokenObject.refreshToken) { - console.log('corbeljs:services:token:refresh'); + console.log('corbeljs:services:token:refresh') this.driver._refreshHandlerPromise = this.driver.iam.token().refresh( tokenObject.refreshToken, - this.driver.config.get(corbel.Iam.IAM_TOKEN_SCOPES, '') - ); - + this.driver.config.get(corbel.Iam.IAM_TOKEN_SCOPES, '')) } else { - console.log('corbeljs:services:token:create'); - this.driver._refreshHandlerPromise = this.driver.iam.token().create(); + console.log('corbeljs:services:token:create') + this.driver._refreshHandlerPromise = this.driver.iam.token().create() } return this.driver._refreshHandlerPromise .then(function(response) { - that.driver.trigger('token:refresh', response.data); - that.driver._refreshHandlerPromise = null; - return response; - }).catch(function(err) { - that.driver._refreshHandlerPromise = null; - throw err; - }); + that.driver.trigger('token:refresh', response.data) + that.driver._refreshHandlerPromise = null + return response + }) + .catch(function(err) { + that.driver._refreshHandlerPromise = null + throw err + }) }, /** @@ -2942,14 +2918,14 @@ */ _addAuthorization: function(params) { // @todo: support to oauth token and custom handlers - var accessToken = this.driver.config.get(corbel.Iam.IAM_TOKEN, {}).accessToken; + var accessToken = this.driver.config.get(corbel.Iam.IAM_TOKEN, {}).accessToken // Use access access token if exists if (accessToken) { - params.headers.Authorization = 'Bearer ' + accessToken; - params.withCredentials = true; + params.headers.Authorization = 'Bearer ' + accessToken + params.withCredentials = true } - return params; + return params }, /** @@ -2963,7 +2939,6 @@ * @return {object} */ _buildParams: function(args) { - // Default values var defaults = { dataType: 'json', @@ -2973,42 +2948,42 @@ Accept: 'application/json' }, method: corbel.request.method.GET - }; + } // do not modify args object - var params = corbel.utils.defaults({}, args); - params = corbel.utils.defaults(params, defaults); + var params = corbel.utils.defaults({}, args) + params = corbel.utils.defaults(params, defaults) if (!params.url) { - throw new Error('You must define an url'); + throw new Error('You must define an url') } if (params.query) { - params.url += '?' + params.query; + params.url += '?' + params.query } if (params.noRedirect) { - params.headers['No-Redirect'] = true; + params.headers['No-Redirect'] = true } if (params.Accept) { - params.headers.Accept = params.Accept; - params.dataType = undefined; // Accept & dataType are incompatibles + params.headers.Accept = params.Accept + params.dataType = undefined // Accept & dataType are incompatibles } // set correct accept & contentType in case of blob // @todo: remove contentType+accept same-type constraint if (params.dataType === 'blob') { if (corbel.Config.isBrowser) { - params.headers.Accept = params.data.type; - params.contentType = params.data.type; - params.dataType = undefined; // Accept & dataType are incompatibles + params.headers.Accept = params.data.type + params.contentType = params.data.type + params.dataType = undefined // Accept & dataType are incompatibles } } - params = this._addAuthorization(params); + params = this._addAuthorization(params) - return corbel.utils.pick(params, ['url', 'dataType', 'contentType', 'method', 'headers', 'data', 'dataFilter', 'responseType', 'withCredentials', 'success', 'error']); + return corbel.utils.pick(params, ['url', 'dataType', 'contentType', 'method', 'headers', 'data', 'dataFilter', 'responseType', 'withCredentials', 'success', 'error']) }, /** @@ -3016,26 +2991,24 @@ * @return {string} */ _buildUri: function() { - - var uri = ''; + var uri = '' if (this.urlBase.slice(-1) !== '/') { - uri += '/'; + uri += '/' } Array.prototype.slice.call(arguments).forEach(function(argument) { if (argument) { - uri += argument + '/'; + uri += argument + '/' } - }); + }) // remove last '/' - uri = uri.slice(0, -1); + uri = uri.slice(0, -1) - return this.urlBase + uri; + return this.urlBase + uri } }, { - /** * _FORCE_UPDATE_TEXT constant * @constant @@ -3105,15 +3078,15 @@ * @return {String} id from the Location */ getLocationId: function(responseObject) { - responseObject = responseObject || {}; - var location; + responseObject = responseObject || {} + var location if (responseObject.xhr) { - location = responseObject.xhr.getResponseHeader('location'); + location = responseObject.xhr.getResponseHeader('location') } else if (responseObject.response && responseObject.response.headers.location) { - location = responseObject.response.headers.location; + location = responseObject.response.headers.location } - return location ? location.substr(location.lastIndexOf('/') + 1) : undefined; + return location ? location.substr(location.lastIndexOf('/') + 1) : undefined }, /** @@ -3124,60 +3097,57 @@ */ addEmptyJson: function(response, type) { if (!response && type === 'json') { - response = '{}'; + response = '{}' } - return response; + return response } - }); - - return Services; + }) - })(); + return Services + })() - //----------corbel modules---------------- + // ----------corbel modules---------------- function Config(config) { - config = config || {}; - // config default values - this.config = {}; + config = config || {} + // config default values + this.config = {} - corbel.utils.extend(this.config, config); + corbel.utils.extend(this.config, config) } - Config.URL_BASE_PLACEHOLDER = '{{module}}'; - Config.URL_BASE_PORT_PLACEHOLDER = '{{modulePort}}'; + Config.URL_BASE_PLACEHOLDER = '{{module}}' + Config.URL_BASE_PORT_PLACEHOLDER = '{{modulePort}}' - corbel.Config = Config; + corbel.Config = Config var processExist = function() { - return typeof(process) !== 'undefined' || {}.toString.call(process) === '[object process]'; - }; - + return typeof(process) !== 'undefined' || {}.toString.call(process) === '[object process]' + } if (typeof module !== 'undefined' && module.exports && processExist() && typeof window === 'undefined') { - Config.__env__ = process.env.NODE_ENV === 'browser' ? 'browser' : 'node'; + Config.__env__ = process.env.NODE_ENV === 'browser' ? 'browser' : 'node' } else { - Config.__env__ = 'browser'; + Config.__env__ = 'browser' } + Config.isNode = Config.__env__ === 'node' - Config.isNode = Config.__env__ === 'node'; - - Config.isBrowser = Config.__env__ === 'browser'; + Config.isBrowser = Config.__env__ === 'browser' /** * Client type * @type {String} * @default */ - Config.clientType = Config.isNode ? 'NODE' : 'WEB'; + Config.clientType = Config.isNode ? 'NODE' : 'WEB' if (Config.isNode) { - Config.wwwRoot = 'localhost'; + Config.wwwRoot = 'localhost' } else { - Config.wwwRoot = window.location.protocol + '//' + window.location.host + window.location.pathname; + Config.wwwRoot = window.location.protocol + '//' + window.location.host + window.location.pathname } /** @@ -3185,25 +3155,25 @@ * @return {Object} */ Config.create = function(config) { - return new Config(config); - }; + return new Config(config) + } /** * Returns all application config params * @return {Object} */ Config.prototype.getConfig = function() { - return this.config; - }; + return this.config + } /** * Overrides current config with params object config * @param {Object} config An object with params to set as new config */ Config.prototype.setConfig = function(config) { - this.config = corbel.utils.extend(this.config, config); - return this; - }; + this.config = corbel.utils.extend(this.config, config) + return this + } /** * Gets a specific config param @@ -3214,27 +3184,24 @@ Config.prototype.get = function(field, defaultValue) { if (this.config[field] === undefined) { if (defaultValue === undefined) { - throw new Error('config:undefined:' + field + ''); + throw new Error('config:undefined:' + field + '') } else { - return defaultValue; + return defaultValue } } - return this.config[field]; - }; + return this.config[field] + } Config.prototype.getCurrentEndpoint = function(moduleName, port) { - var moduleEndpoint = moduleName + 'Endpoint'; - var endpoint = this.get(moduleEndpoint, null) ? - this.get(moduleEndpoint) : - this.get('urlBase'); - endpoint = endpoint.replace(corbel.Config.URL_BASE_PLACEHOLDER, moduleName); + var moduleEndpoint = moduleName + 'Endpoint' + var endpoint = this.get(moduleEndpoint, null) ? this.get(moduleEndpoint) : this.get('urlBase') + endpoint = endpoint.replace(corbel.Config.URL_BASE_PLACEHOLDER, moduleName) if (port) { - endpoint = endpoint.replace(corbel.Config.URL_BASE_PORT_PLACEHOLDER, port); + endpoint = endpoint.replace(corbel.Config.URL_BASE_PORT_PLACEHOLDER, port) } - return endpoint; - }; - + return endpoint + } /** * Sets a new value for specific config param @@ -3242,12 +3209,13 @@ * @param {Mixed} value Config param value */ Config.prototype.set = function(field, value) { - this.config[field] = value; - }; + this.config[field] = value + } + /* global corbel */ + ; (function() { - /** * A module to make iam requests. * @exports iam @@ -3256,21 +3224,21 @@ */ var Iam = corbel.Iam = function(driver) { - this.driver = driver; - }; + this.driver = driver + } - Iam.moduleName = 'iam'; - Iam.defaultPort = 8082; + Iam.moduleName = 'iam' + Iam.defaultPort = 8082 Iam.create = function(driver) { - return new Iam(driver); - }; + return new Iam(driver) + } - Iam.GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:jwt-bearer'; - Iam.AUD = 'http://iam.bqws.io'; - Iam.IAM_TOKEN = 'iamToken'; - Iam.IAM_TOKEN_SCOPES = 'iamScopes'; - Iam.IAM_DOMAIN = 'domain'; + Iam.GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:jwt-bearer' + Iam.AUD = 'http://iam.bqws.io' + Iam.IAM_TOKEN = 'iamToken' + Iam.IAM_TOKEN_SCOPES = 'iamScopes' + Iam.IAM_DOMAIN = 'domain' /** * COMMON MIXINS @@ -3285,23 +3253,23 @@ */ Iam._buildUri = function(uri, id) { if (id) { - uri += '/' + id; + uri += '/' + id } - var urlBase = this.driver.config.getCurrentEndpoint(Iam.moduleName, corbel.Iam._buildPort(this.driver.config)); + var urlBase = this.driver.config.getCurrentEndpoint(Iam.moduleName, corbel.Iam._buildPort(this.driver.config)) - return urlBase + uri; - }; + return urlBase + uri + } Iam._buildPort = function(config) { - return config.get('iamPort', null) || corbel.Iam.defaultPort; - }; - - })(); + return config.get('iamPort', null) || corbel.Iam.defaultPort + } + })() + /* global corbel */ + ; (function() { - /** * Creates a ClientBuilder for client managing requests. * @@ -3311,10 +3279,10 @@ * @return {corbel.Iam.ClientBuilder} */ corbel.Iam.prototype.client = function(domainId, clientId) { - var client = new ClientBuilder(domainId, clientId); - client.driver = this.driver; - return client; - }; + var client = new ClientBuilder(domainId, clientId) + client.driver = this.driver + return client + } /** * A builder for client management requests. @@ -3326,11 +3294,10 @@ * @memberOf iam */ var ClientBuilder = corbel.Iam.ClientBuilder = corbel.Services.inherit({ - constructor: function(domainId, clientId) { - this.domainId = domainId; - this.clientId = clientId; - this.uri = 'domain'; + this.domainId = domainId + this.clientId = clientId + this.uri = 'domain' }, /** @@ -3354,15 +3321,15 @@ * with a {@link corbelError}. */ create: function(client) { - console.log('iamInterface.domain.create', client); - corbel.validate.value('domainId', this.domainId); + console.log('iamInterface.domain.create', client) + corbel.validate.value('domainId', this.domainId) return this.request({ url: this._buildUri(this.uri + '/' + this.domainId + '/client'), method: corbel.request.method.POST, data: client }).then(function(res) { - return corbel.Services.getLocationId(res); - }); + return corbel.Services.getLocationId(res) + }) }, /** @@ -3376,12 +3343,12 @@ * @return {Promise} A promise with the client or fails with a {@link corbelError}. */ get: function() { - console.log('iamInterface.domain.get', this.clientId); - corbel.validate.values(['domainId', 'clientId'], this); + console.log('iamInterface.domain.get', this.clientId) + corbel.validate.values(['domainId', 'clientId'], this) return this.request({ url: this._buildUri(this.uri + '/' + this.domainId + '/client/' + this.clientId), method: corbel.request.method.GET - }); + }) }, /** @@ -3394,14 +3361,14 @@ * @see {@link corbel.util.serializeParams} to see a example of the params */ getAll: function(params) { - corbel.validate.failIfIsDefined(this.clientId, 'This function not allowed client identifier'); - corbel.validate.value('domainId', this.domainId); - console.log('iamInterface.domain.getAll'); + corbel.validate.failIfIsDefined(this.clientId, 'This function not allowed client identifier') + corbel.validate.value('domainId', this.domainId) + console.log('iamInterface.domain.getAll') return this.request({ url: this._buildUri(this.uri + '/' + this.domainId + '/client'), method: corbel.request.method.GET, query: params ? corbel.utils.serializeParams(params) : null - }); + }) }, /** @@ -3423,13 +3390,13 @@ * @return {Promise} A promise or fails with a {@link corbelError}. */ update: function(client) { - console.log('iamInterface.domain.update', client); - corbel.validate.values(['domainId', 'clientId'], this); + console.log('iamInterface.domain.update', client) + corbel.validate.values(['domainId', 'clientId'], this) return this.request({ url: this._buildUri(this.uri + '/' + this.domainId + '/client/' + this.clientId), method: corbel.request.method.PUT, data: client - }); + }) }, /** @@ -3443,24 +3410,24 @@ * @return {Promise} A promise or fails with a {@link corbelError}. */ remove: function() { - console.log('iamInterface.domain.remove', this.domainId, this.clientId); - corbel.validate.values(['domainId', 'clientId'], this); + console.log('iamInterface.domain.remove', this.domainId, this.clientId) + corbel.validate.values(['domainId', 'clientId'], this) return this.request({ url: this._buildUri(this.uri + '/' + this.domainId + '/client/' + this.clientId), method: corbel.request.method.DELETE - }); + }) }, _buildUri: corbel.Iam._buildUri - }); - - })(); + }) + })() + /* global corbel */ + ; (function() { - /** * Creates a DomainBuilder for domain managing requests. * @@ -3469,10 +3436,10 @@ * @return {corbel.Iam.DomainBuilder} */ corbel.Iam.prototype.domain = function(domainId) { - var domain = new DomainBuilder(domainId); - domain.driver = this.driver; - return domain; - }; + var domain = new DomainBuilder(domainId) + domain.driver = this.driver + return domain + } /** * A builder for domain management requests. @@ -3483,10 +3450,9 @@ * @memberOf iam */ var DomainBuilder = corbel.Iam.DomainBuilder = corbel.Services.inherit({ - constructor: function(domainId) { - this.domainId = domainId; - this.uri = 'domain'; + this.domainId = domainId + this.uri = 'domain' }, _buildUri: corbel.Iam._buildUri, @@ -3510,14 +3476,14 @@ * with a {@link corbelError}. */ create: function(domain) { - console.log('iamInterface.domain.create', domain); + console.log('iamInterface.domain.create', domain) return this.request({ url: this._buildUri(this.uri), method: corbel.request.method.POST, data: domain }).then(function(res) { - return corbel.Services.getLocationId(res); - }); + return corbel.Services.getLocationId(res) + }) }, /** @@ -3529,16 +3495,15 @@ * @return {Promise} A promise with the domain or fails with a {@link corbelError}. */ get: function() { - console.log('iamInterface.domain.get', this.domainId); - corbel.validate.value('domainId', this.domainId); + console.log('iamInterface.domain.get', this.domainId) + corbel.validate.value('domainId', this.domainId) return this.request({ url: this._buildUri(this.uri + '/' + this.domainId), method: corbel.request.method.GET - }); + }) }, - /** * Gets all domains. * @@ -3549,13 +3514,13 @@ * @see {@link corbel.util.serializeParams} to see a example of the params */ getAll: function(params) { - corbel.validate.failIfIsDefined(this.domainId, 'This function not allowed domain identifier'); - console.log('iamInterface.domain.getAll'); + corbel.validate.failIfIsDefined(this.domainId, 'This function not allowed domain identifier') + console.log('iamInterface.domain.getAll') return this.request({ url: this._buildUri(this.uri), method: corbel.request.method.GET, query: params ? corbel.utils.serializeParams(params) : null - }); + }) }, /** @@ -3576,14 +3541,14 @@ * @return {Promise} A promise or fails with a {@link corbelError}. */ update: function(domain) { - console.log('iamInterface.domain.update', domain); - corbel.validate.value('domainId', this.domainId); + console.log('iamInterface.domain.update', domain) + corbel.validate.value('domainId', this.domainId) return this.request({ url: this._buildUri(this.uri + '/' + this.domainId), method: corbel.request.method.PUT, data: domain - }); + }) }, /** @@ -3597,31 +3562,31 @@ * @return {Promise} A promise or fails with a {@link corbelError}. */ remove: function() { - console.log('iamInterface.domain.remove', this.domainId); - corbel.validate.value('domainId', this.domainId); + console.log('iamInterface.domain.remove', this.domainId) + corbel.validate.value('domainId', this.domainId) return this.request({ url: this._buildUri(this.uri + '/' + this.domainId), method: corbel.request.method.DELETE - }); + }) } - }); - - })(); + }) + })() + /* global corbel */ + ; (function() { - /** * Creates a ScopeBuilder for scope managing requests. * @param {String} id Scope id. * @return {corbel.Iam.ScopeBuilder} */ corbel.Iam.prototype.scope = function(id) { - var scope = new ScopeBuilder(id); - scope.driver = this.driver; - return scope; - }; + var scope = new ScopeBuilder(id) + scope.driver = this.driver + return scope + } /** * A builder for scope management requests. @@ -3632,10 +3597,9 @@ * @memberOf iam */ var ScopeBuilder = corbel.Iam.ScopeBuilder = corbel.Services.inherit({ - constructor: function(id) { - this.id = id; - this.uri = 'scope'; + this.id = id + this.uri = 'scope' }, _buildUri: corbel.Iam._buildUri, @@ -3655,14 +3619,14 @@ * with a {@link corbelError}. */ create: function(scope) { - console.log('iamInterface.scope.create', scope); + console.log('iamInterface.scope.create', scope) return this.request({ url: this._buildUri(this.uri), method: corbel.request.method.POST, data: scope }).then(function(res) { - return corbel.Services.getLocationId(res); - }); + return corbel.Services.getLocationId(res) + }) }, /** @@ -3674,13 +3638,13 @@ * @return {Promise} A promise with the scope or fails with a {@link corbelError}. */ get: function() { - console.log('iamInterface.scope.get', this.id); - corbel.validate.value('id', this.id); + console.log('iamInterface.scope.get', this.id) + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri + '/' + this.id), method: corbel.request.method.GET - }); + }) }, /** @@ -3691,31 +3655,31 @@ * @return {Promise} A promise user or fails with a {@link corbelError}. */ remove: function() { - console.log('iamInterface.scope.remove', this.id); - corbel.validate.value('id', this.id); + console.log('iamInterface.scope.remove', this.id) + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri + '/' + this.id), method: corbel.request.method.DELETE - }); + }) } - }); - - })(); + }) + })() + /* global corbel */ + ; (function() { - /** * Creates a TokenBuilder for token requests * @return {corbel.Iam.TokenBuilder} */ corbel.Iam.prototype.token = function() { - var tokenBuilder = new TokenBuilder(this.driver); - tokenBuilder.driver = this.driver; - return tokenBuilder; - }; + var tokenBuilder = new TokenBuilder(this.driver) + tokenBuilder.driver = this.driver + return tokenBuilder + } /** * A builder for token requests @@ -3723,9 +3687,8 @@ * @memberOf Iam */ var TokenBuilder = corbel.Iam.TokenBuilder = corbel.Services.inherit({ - constructor: function() { - this.uri = 'oauth/token'; + this.uri = 'oauth/token' }, _buildUri: corbel.Iam._buildUri, @@ -3741,18 +3704,18 @@ * @return {String} JWT assertion */ _getJwt: function(params) { - params = params || {}; - params.claims = params.claims || {}; + params = params || {} + params.claims = params.claims || {} if (params.jwt) { - return params.jwt; + return params.jwt } - var secret = params.secret || this.driver.config.get('clientSecret'); - params.claims.iss = params.claims.iss || this.driver.config.get('clientId'); - params.claims.aud = params.claims.aud || this.driver.config.get('audience', corbel.Iam.AUD); - params.claims.scope = params.claims.scope || this.driver.config.get('scopes', ''); - return corbel.jwt.generate(params.claims, secret); + var secret = params.secret || this.driver.config.get('clientSecret') + params.claims.iss = params.claims.iss || this.driver.config.get('clientId') + params.claims.aud = params.claims.aud || this.driver.config.get('audience', corbel.Iam.AUD) + params.claims.scope = params.claims.scope || this.driver.config.get('scopes', '') + return corbel.jwt.generate(params.claims, secret) }, _doGetTokenRequest: function(uri, params, setCookie) { @@ -3764,15 +3727,15 @@ 'grant_type': corbel.Iam.GRANT_TYPE }, params.oauth)), withCredentials: true - }; + } if (setCookie) { args.headers = { RequestCookie: 'true' - }; + } } - return corbel.request.send(args); + return corbel.request.send(args) }, _doPostTokenRequest: function(uri, params, setCookie) { @@ -3785,14 +3748,14 @@ }, contentType: 'application/x-www-form-urlencoded; charset=UTF-8', withCredentials: true - }; + } if (setCookie) { args.headers = { RequestCookie: 'true' - }; + } } - return corbel.request.send(args); + return corbel.request.send(args) }, /** @@ -3806,47 +3769,45 @@ * * @param {string} params["oauth.service"] Service that will provide the authorization, e.g. facebook String * * @param {string} params["oauth.code"] Code used in OAuth2 for exanging for a token String only if OAuth2 - * @param {string} params["oauth.access_token"] Access token used in OAuth2 for authentication. WARNING!! It is not recommended to pass an access token directly from the client, the oauth.code claim should be used instead. String + * @param {string} params["oauth.access_token"] Access token used in OAuth2 for authentication. WARNING!! It is not recommended to pass an access token directly from the client, the oauth.code claim should be used instead String * @param {string} params["oauth.redirect_uri"] URI used by the client in OAuth2 to redirect the user when he does the login String only if OAuth2 * @param {string} params["oauth.token"] Token returned by OAuth1 server to the client when the user does the login String only if OAuth1 * @param {string} params["oauth.verifier"] Verifier returned by OAuth1 server to the client when the user does the login - * * @param {Boolean} [setCookie] Sends 'RequestCookie' to server * @return {Promise} Q promise that resolves to an AccessToken {Object} or rejects with a {@link corbelError} */ create: function(params, setCookie) { - params = params || {}; - // if there are oauth params this mean we should do use the GET verb - var promise; + params = params || {} + // if there are oauth params this mean we should do use the GET verb + var promise try { if (params.oauth) { - promise = this._doGetTokenRequest(this.uri, params, setCookie); + promise = this._doGetTokenRequest(this.uri, params, setCookie) } // otherwise we use the traditional POST verb. - promise = this._doPostTokenRequest(this.uri, params, setCookie); - + promise = this._doPostTokenRequest(this.uri, params, setCookie) } catch (e) { - console.log('error', e); - return Promise.reject(e); + console.log('error', e) + return Promise.reject(e) } - var that = this; + var that = this return promise.then(function(response) { - that.driver.config.set(corbel.Iam.IAM_TOKEN, response.data); - that.driver.config.set(corbel.Iam.IAM_DOMAIN, corbel.jwt.decode(response.data.accessToken).domainId); + that.driver.config.set(corbel.Iam.IAM_TOKEN, response.data) + that.driver.config.set(corbel.Iam.IAM_DOMAIN, corbel.jwt.decode(response.data.accessToken).domainId) if (params.jwt) { - that.driver.config.set(corbel.Iam.IAM_TOKEN_SCOPES, corbel.jwt.decode(params.jwt).scope); + that.driver.config.set(corbel.Iam.IAM_TOKEN_SCOPES, corbel.jwt.decode(params.jwt).scope) } if (params.claims) { if (params.claims.scope) { - that.driver.config.set(corbel.Iam.IAM_TOKEN_SCOPES, params.claims.scope); + that.driver.config.set(corbel.Iam.IAM_TOKEN_SCOPES, params.claims.scope) } else { - that.driver.config.set(corbel.Iam.IAM_TOKEN_SCOPES, that.driver.config.get('scopes', '')); + that.driver.config.set(corbel.Iam.IAM_TOKEN_SCOPES, that.driver.config.get('scopes', '')) } } - return response; - }); + return response + }) }, /** @@ -3858,48 +3819,45 @@ * @return {Promise} Q promise that resolves to an AccesToken {Object} or rejects with a {@link corbelError} */ refresh: function(refreshToken, scopes) { - // console.log('iamInterface.token.refresh', refreshToken); + // console.log('iamInterface.token.refresh', refreshToken) // we need refresh token to refresh access token - corbel.validate.isValue(refreshToken, 'Refresh access token request must contains refresh token'); - // we need create default claims to refresh access token + corbel.validate.isValue(refreshToken, 'Refresh access token request must contains refresh token') + // we need create default claims to refresh access token var params = { claims: { 'scope': scopes, 'refresh_token': refreshToken } - }; - var that = this; + } + var that = this try { - return this._doPostTokenRequest(this.uri, params) .then(function(response) { - that.driver.config.set(corbel.Iam.IAM_TOKEN, response.data); - return response; - }); - + that.driver.config.set(corbel.Iam.IAM_TOKEN, response.data) + return response + }) } catch (e) { - console.log('error', e); - return Promise.reject(e); + console.log('error', e) + return Promise.reject(e) } - } + }) + })() - }); - - })(); + /* global corbel */ + ; (function() { - /** * Starts a username request * @return {corbel.Iam.UsernameBuilder} The builder to create the request */ corbel.Iam.prototype.username = function() { - var username = new UsernameBuilder(); - username.driver = this.driver; - return username; - }; + var username = new UsernameBuilder() + username.driver = this.driver + return username + } /** * Builder for creating requests of users name @@ -3907,9 +3865,8 @@ * @memberOf iam */ var UsernameBuilder = corbel.Iam.UsernameBuilder = corbel.Services.inherit({ - constructor: function() { - this.uri = 'username'; + this.uri = 'username' }, _buildUri: corbel.Iam._buildUri, @@ -3922,20 +3879,20 @@ * @return {Promise} A promise which resolves into usename availability boolean state. */ availability: function(username) { - console.log('iamInterface.username.availability', username); - corbel.validate.value('username', username); + console.log('iamInterface.username.availability', username) + corbel.validate.value('username', username) return this.request({ url: this._buildUri(this.uri, username), method: corbel.request.method.HEAD }).then(function() { - return false; + return false }).catch(function(response) { if (response.status === 404) { - return true; + return true } else { - return Promise.reject(response); + return Promise.reject(response) } - }); + }) }, /** @@ -3949,50 +3906,50 @@ * @return {Promise} A promise with the user or fails with a {@link corbelError}. */ getUserId: function(username) { - console.log('iamInterface.username.getUserId', username); - corbel.validate.value('username', username); + console.log('iamInterface.username.getUserId', username) + corbel.validate.value('username', username) return this.request({ url: this._buildUri(this.uri, username), method: corbel.request.method.GET - }); + }) } - }); - - })(); + }) + })() + /* global corbel */ + ; (function() { - - /** + /* * Starts a user request * @param {string} [id=id|'me'] Id of the user to perform the request * @return {corbel.Iam.UserBuilder|corbel.Iam.UserMeBuilder} The builder to create the request */ corbel.Iam.prototype.user = function(id) { - var builder; + var builder if (id === 'me') { - builder = new UserBuilder('me'); + builder = new UserBuilder('me') } else if (id) { - builder = new UserBuilder(id); + builder = new UserBuilder(id) } else { - builder = new UserMeBuilder('me'); + builder = new UserMeBuilder('me') } - builder.driver = this.driver; - return builder; - }; + builder.driver = this.driver + return builder + } /** * Starts a users request * @return {corbel.Iam.UserBuilder|corbel.Iam.UsersBuilder} The builder to create the request */ corbel.Iam.prototype.users = function() { - var builder = new UsersBuilder(); + var builder = new UsersBuilder() - builder.driver = this.driver; - return builder; - }; + builder.driver = this.driver + return builder + } /** * getUser mixin for UserBuilder & UsersBuilder @@ -4002,12 +3959,12 @@ * @return {Promise} */ corbel.Iam._getUser = function(method, uri, id, postfix) { - var url = (postfix ? this._buildUri(uri, id) + postfix : this._buildUri(uri, id)); + var url = (postfix ? this._buildUri(uri, id) + postfix : this._buildUri(uri, id)) return this.request({ url: url, method: corbel.request.method.GET - }); - }; + }) + } /** * Builder for a specific user requests @@ -4016,10 +3973,9 @@ * @param {string} id The id of the user */ var CommonUserBuilder = corbel.Iam.CommonUserBuilder = corbel.Services.inherit({ - constructor: function(id) { - this.uri = 'user'; - this.id = id; + this.uri = 'user' + this.id = id }, _buildUri: corbel.Iam._buildUri, @@ -4032,27 +3988,27 @@ * @return {Promise} Q promise that resolves to a User {Object} or rejects with a {@link corbelError} */ get: function() { - console.log('iamInterface.user.get'); - corbel.validate.value('id', this.id); - return this._getUser(corbel.request.method.GET, this.uri, this.id); + console.log('iamInterface.user.get') + corbel.validate.value('id', this.id) + return this._getUser(corbel.request.method.GET, this.uri, this.id) }, /** * Updates the user * @method * @memberOf corbel.Iam.UserBuilder - * @param {Object} data The data to update - * @return {Promise} Q promise that resolves to undefined (void) or rejects with a {@link corbelError} + * @param {Object} The data to update + * @return {Promise} promise that resolves to undefined (void) or rejects with a {@link corbelError} */ _update: function(data) { - console.log('iamInterface.user.update', data); - corbel.validate.value('id', this.id); + console.log('iamInterface.user.update', data) + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id), method: corbel.request.method.PUT, data: data - }); + }) }, /** @@ -4062,31 +4018,31 @@ * @return {Promise} Q promise that resolves to undefined (void) or rejects with a {@link corbelError} */ _delete: function() { - console.log('iamInterface.user.delete'); - corbel.validate.value('id', this.id); + console.log('iamInterface.user.delete') + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id), method: corbel.request.method.DELETE - }); + }) }, /** * Sign Out the logged user. * @example - * iam().user('me').signOut(); + * iam().user('me').signOut() * @method * @memberOf corbel.Iam.UsersBuilder * @return {Promise} Q promise that resolves to a User {Object} or rejects with a {@link corbelError} */ _signOut: function() { - console.log('iamInterface.users.signOutMe'); - corbel.validate.value('id', this.id); + console.log('iamInterface.users.signOutMe') + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id) + '/signout', method: corbel.request.method.PUT - }); + }) }, /** @@ -4096,13 +4052,13 @@ * @return {Promise} Q promise that resolves to undefined (void) or rejects with a {@link corbelError} */ _disconnect: function() { - console.log('iamInterface.user.disconnect'); - corbel.validate.value('id', this.id); + console.log('iamInterface.user.disconnect') + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id) + '/disconnect', method: corbel.request.method.PUT - }); + }) }, /** @@ -4115,15 +4071,15 @@ * @return {Promise} Q promise that resolves to undefined (void) or rejects with a {@link corbelError} */ addIdentity: function(identity) { - // console.log('iamInterface.user.addIdentity', identity); - corbel.validate.isValue(identity, 'Missing identity'); - corbel.validate.value('id', this.id); + // console.log('iamInterface.user.addIdentity', identity) + corbel.validate.isValue(identity, 'Missing identity') + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id) + '/identity', method: corbel.request.method.POST, data: identity - }); + }) }, /** @@ -4133,13 +4089,13 @@ * @return {Promise} Q promise that resolves to {Array} of Identity or rejects with a {@link corbelError} */ _getIdentities: function() { - console.log('iamInterface.user.getIdentities'); - corbel.validate.value('id', this.id); + console.log('iamInterface.user.getIdentities') + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id) + '/identity', method: corbel.request.method.GET - }); + }) }, /** * User device register @@ -4152,16 +4108,16 @@ * @return {Promise} Q promise that resolves to a User {Object} or rejects with a {@link corbelError} */ _registerDevice: function(data) { - console.log('iamInterface.user.registerDevice'); - corbel.validate.value('id', this.id); + console.log('iamInterface.user.registerDevice') + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id) + '/devices', method: corbel.request.method.PUT, data: data }).then(function(res) { - return corbel.Services.getLocationId(res); - }); + return corbel.Services.getLocationId(res) + }) }, /** @@ -4172,16 +4128,16 @@ * @return {Promise} Q promise that resolves to a Device {Object} or rejects with a {@link corbelError} */ _getDevice: function(deviceId) { - console.log('iamInterface.user.getDevice'); + console.log('iamInterface.user.getDevice') corbel.validate.values(['id', 'deviceId'], { 'id': this.id, 'deviceId': deviceId - }); + }) return this.request({ url: this._buildUri(this.uri, this.id) + '/devices/' + deviceId, method: corbel.request.method.GET - }); + }) }, /** @@ -4191,12 +4147,12 @@ * @return {Promise} Q promise that resolves to a Device {Object} or rejects with a {@link corbelError} */ _getDevices: function() { - console.log('iamInterface.user.getDevices'); - corbel.validate.value('id', this.id); + console.log('iamInterface.user.getDevices') + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id) + '/devices/', method: corbel.request.method.GET - }); + }) }, /** @@ -4207,12 +4163,12 @@ * @return {Promise} Q promise that resolves to a Device {Object} or rejects with a {@link corbelError} */ _deleteDevice: function(deviceId) { - console.log('iamInterface.user.deleteDevice'); - corbel.validate.value('deviceId', deviceId); + console.log('iamInterface.user.deleteDevice') + corbel.validate.value('deviceId', deviceId) return this.request({ url: this._buildUri(this.uri, this.id) + '/devices/' + deviceId, method: corbel.request.method.DELETE - }); + }) }, /** * Get user profiles @@ -4221,13 +4177,13 @@ * @return {Promise} Q promise that resolves to a User Profile or rejects with a {@link corbelError} */ _getProfile: function() { - console.log('iamInterface.user.getProfile'); - corbel.validate.value('id', this.id); + console.log('iamInterface.user.getProfile') + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id) + '/profile', method: corbel.request.method.GET - }); + }) }, /** @@ -4238,14 +4194,14 @@ * @return {Promise} Q promise that resolves to undefined (void) or rejects with a {@link SilkRoadError} */ addGroups: function(groups) { - console.log('iamInterface.user.addGroups'); - corbel.validate.value('id', this.id); + console.log('iamInterface.user.addGroups') + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id) + '/groups', method: corbel.request.method.PUT, data: groups - }); + }) }, /** @@ -4256,90 +4212,90 @@ * @return {Promise} Q promise that resolves to undefined (void) or rejects with a {@link SilkRoadError} */ _deleteGroup: function(group) { - console.log('iamInterface.user.deleteGroup'); + console.log('iamInterface.user.deleteGroup') corbel.validate.values(['id', 'group'], { 'id': this.id, 'group': group - }); + }) return this.request({ url: this._buildUri(this.uri, this.id) + '/groups/' + group, method: corbel.request.method.DELETE - }); + }) } - }); + }) - var UserBuilder = corbel.Iam.CommonUserBuilder.inherit({ + var UserBuilder = CommonUserBuilder.inherit({ deleteGroup: function() { - return this._deleteGroup.apply(this, arguments); + return this._deleteGroup.apply(this, arguments) }, update: function() { - return this._update.apply(this, arguments); + return this._update.apply(this, arguments) }, delete: function() { - return this._delete.apply(this, arguments); + return this._delete.apply(this, arguments) }, registerDevice: function() { - return this._registerDevice.apply(this, arguments); + return this._registerDevice.apply(this, arguments) }, getDevices: function() { - return this._getDevices.apply(this, arguments); + return this._getDevices.apply(this, arguments) }, getDevice: function() { - return this._getDevice.apply(this, arguments); + return this._getDevice.apply(this, arguments) }, deleteDevice: function() { - return this._deleteDevice.apply(this, arguments); + return this._deleteDevice.apply(this, arguments) }, signOut: function() { - return this._signOut.apply(this, arguments); + return this._signOut.apply(this, arguments) }, disconnect: function() { - return this._disconnect.apply(this, arguments); + return this._disconnect.apply(this, arguments) }, getIdentities: function() { - return this._getIdentities.apply(this, arguments); + return this._getIdentities.apply(this, arguments) }, getProfile: function() { - return this._getProfile.apply(this, arguments); + return this._getProfile.apply(this, arguments) } - }); + }) - var UserMeBuilder = corbel.Iam.CommonUserBuilder.inherit({ + var UserMeBuilder = CommonUserBuilder.inherit({ deleteMyGroup: function() { - return this._deleteGroup.apply(this, arguments); + return this._deleteGroup.apply(this, arguments) }, updateMe: function() { - return this._update.apply(this, arguments); + return this._update.apply(this, arguments) }, deleteMe: function() { - return this._delete.apply(this, arguments); + return this._delete.apply(this, arguments) }, registerMyDevice: function() { - return this._registerDevice.apply(this, arguments); + return this._registerDevice.apply(this, arguments) }, getMyDevices: function() { - return this._getDevices.apply(this, arguments); + return this._getDevices.apply(this, arguments) }, getMyDevice: function() { - return this._getDevice.apply(this, arguments); + return this._getDevice.apply(this, arguments) }, deleteMyDevice: function() { - return this._deleteDevice.apply(this, arguments); + return this._deleteDevice.apply(this, arguments) }, signOutMe: function() { - return this._signOut.apply(this, arguments); + return this._signOut.apply(this, arguments) }, disconnectMe: function() { - return this._disconnect.apply(this, arguments); + return this._disconnect.apply(this, arguments) }, getMyIdentities: function() { - return this._getIdentities.apply(this, arguments); + return this._getIdentities.apply(this, arguments) }, getMyProfile: function() { - return this._getProfile.apply(this, arguments); + return this._getProfile.apply(this, arguments) } - }); + }) /** * Builder for creating requests of users collection @@ -4347,9 +4303,8 @@ * @memberOf iam */ var UsersBuilder = corbel.Iam.UsersBuilder = corbel.Services.inherit({ - constructor: function() { - this.uri = 'user'; + this.uri = 'user' }, _buildUri: corbel.Iam._buildUri, @@ -4362,15 +4317,15 @@ * @return {Promise} Q promise that resolves to undefined (void) or rejects with a {@link corbelError} */ sendResetPasswordEmail: function(userEmailToReset) { - console.log('iamInterface.users.sendResetPasswordEmail', userEmailToReset); - var query = 'email=' + userEmailToReset; + console.log('iamInterface.users.sendResetPasswordEmail', userEmailToReset) + var query = 'email=' + userEmailToReset return this.request({ url: this._buildUri(this.uri + '/resetPassword'), method: corbel.request.method.GET, query: query }).then(function(res) { - return corbel.Services.getLocationId(res); - }); + return corbel.Services.getLocationId(res) + }) }, /** @@ -4381,14 +4336,14 @@ * @return {Promise} A promise which resolves into the ID of the created user or fails with a {@link corbelError}. */ create: function(data) { - console.log('iamInterface.users.create', data); + console.log('iamInterface.users.create', data) return this.request({ url: this._buildUri(this.uri), method: corbel.request.method.POST, data: data }).then(function(res) { - return corbel.Services.getLocationId(res); - }); + return corbel.Services.getLocationId(res) + }) }, /** @@ -4398,45 +4353,46 @@ * @return {Promise} Q promise that resolves to an {Array} of Users or rejects with a {@link corbelError} */ get: function(params) { - console.log('iamInterface.users.get', params); + console.log('iamInterface.users.get', params) return this.request({ url: this._buildUri(this.uri), method: corbel.request.method.GET, query: params ? corbel.utils.serializeParams(params) : null - }); + }) }, getProfiles: function(params) { - console.log('iamInterface.users.getProfiles', params); + console.log('iamInterface.users.getProfiles', params) return this.request({ url: this._buildUri(this.uri) + '/profile', method: corbel.request.method.GET, - query: params ? corbel.utils.serializeParams(params) : null //TODO cambiar por util e implementar dicho metodo - }); + query: params ? corbel.utils.serializeParams(params) : null // TODO cambiar por util e implementar dicho metodo + }) } - }); - })(); + }) + })() + /* global corbel */ + ; (function() { - /** * Creates a GroupBuilder for group requests * * @return {iam.GroupBuilder | iam.GroupsBuilder} */ corbel.Iam.prototype.group = function(id) { - var builder; + var builder if (id) { - builder = new GroupBuilder(id); + builder = new GroupBuilder(id) } else { - builder = new GroupsBuilder(); + builder = new GroupsBuilder() } - builder.driver = this.driver; - return builder; - }; + builder.driver = this.driver + return builder + } /** * A builder for group requests without id (getAll and creation). @@ -4445,9 +4401,8 @@ * @memberOf iam */ var GroupsBuilder = corbel.Iam.GroupsBuilder = corbel.Services.inherit({ - constructor: function() { - this.uri = 'group'; + this.uri = 'group' }, _buildUri: corbel.Iam._buildUri, @@ -4463,13 +4418,13 @@ * @return {Promise} Q promise that resolves to an array of groups. */ getAll: function(params) { - console.log('iamInterface.groups.getAll'); + console.log('iamInterface.groups.getAll') return this.request({ url: this._buildUri(this.uri), method: corbel.request.method.GET, query: params ? corbel.utils.serializeParams(params) : null, withAuth: true - }); + }) }, /** @@ -4486,18 +4441,18 @@ * @return {Promise} A promise which resolves into the ID of the created group or fails with a {@link SilkRoadError}. */ create: function(data) { - console.log('iamInterface.groups.create', data); + console.log('iamInterface.groups.create', data) return this.request({ url: this._buildUri(this.uri), method: corbel.request.method.POST, data: data, withAuth: true }).then(function(res) { - return corbel.Services.getLocationId(res); - }); + return corbel.Services.getLocationId(res) + }) } - }); + }) /** * A builder for group requests. @@ -4507,10 +4462,9 @@ * @param {String} id The id of the group. */ var GroupBuilder = corbel.Iam.GroupBuilder = corbel.Services.inherit({ - constructor: function(id) { - this.uri = 'group'; - this.id = id; + this.uri = 'group' + this.id = id }, _buildUri: corbel.Iam._buildUri, @@ -4523,13 +4477,13 @@ * @return {Promise} Q promise that resolves to a group or rejects with a {@link SilkRoadError}. */ get: function() { - console.log('iamInterface.group.get'); - corbel.validate.value('id', this.id); + console.log('iamInterface.group.get') + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id), method: corbel.request.method.GET, withAuth: true - }); + }) }, /** @@ -4543,15 +4497,15 @@ * @return {Promise} A promise which resolves to undefined(void) or fails with a {@link SilkRoadError}. */ addScopes: function(scopes) { - console.log('iamInterface.group.addScopes', scopes); - corbel.validate.value('id', this.id); + console.log('iamInterface.group.addScopes', scopes) + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id) + '/scopes', method: corbel.request.method.PUT, data: scopes, withAuth: true - }); + }) }, /** @@ -4565,14 +4519,14 @@ * @return {Promise} A promise which resolves to undefined(void) or fails with a {@link SilkRoadError}. */ removeScope: function(scope) { - console.log('iamInterface.group.removeScope', scope); - corbel.validate.value('id', this.id); + console.log('iamInterface.group.removeScope', scope) + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id) + '/scopes/' + scope, method: corbel.request.method.DELETE, withAuth: true - }); + }) }, /** @@ -4583,33 +4537,33 @@ * @return {Promise} A promise which resolves to undefined(void) or fails with a {@link SilkRoadError}. */ delete: function() { - console.log('iamInterface.group.delete'); - corbel.validate.value('id', this.id); + console.log('iamInterface.group.delete') + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id), method: corbel.request.method.DELETE, withAuth: true - }); + }) } - }); - - })(); + }) + })() + /* global corbel */ + ; (function() { - /** * Creates a EmailBuilder for email requests * @return {corbel.Iam.EmailBuilder} */ corbel.Iam.prototype.email = function() { - var builder; - builder = new EmailBuilder(); - builder.driver = this.driver; - return builder; - }; + var builder + builder = new EmailBuilder() + builder.driver = this.driver + return builder + } /** * Builder for creating requests of email @@ -4617,9 +4571,8 @@ * @memberOf iam */ var EmailBuilder = corbel.Iam.EmailBuilder = corbel.Services.inherit({ - constructor: function() { - this.uri = 'email'; + this.uri = 'email' }, _buildUri: corbel.Iam._buildUri, @@ -4635,13 +4588,13 @@ * @return {Promise} A promise with the user or fails with a {@link corbelError}. */ getUserId: function(email) { - console.log('iamInterface.email.getUserId', email); - corbel.validate.value('email', email); + console.log('iamInterface.email.getUserId', email) + corbel.validate.value('email', email) return this.request({ url: this._buildUri(this.uri, email), method: corbel.request.method.GET - }); + }) }, /** @@ -4652,30 +4605,32 @@ * @return {Promise} A promise which resolves into email availability boolean state. */ availability: function(email) { - console.log('iamInterface.email.availability', email); - corbel.validate.value('email', email); + console.log('iamInterface.email.availability', email) + corbel.validate.value('email', email) return this.request({ url: this._buildUri(this.uri, email), method: corbel.request.method.HEAD }).then( function() { - return false; + return false }, function(response) { if (response.status === 404) { - return true; + return true } else { - return Promise.reject(response); + return Promise.reject(response) } } - ); + ) } - }); - })(); + }) + })() - (function() { + /* global corbel */ + ; + (function() { /** * An assets API factory * @exports corbel.Assets @@ -4684,7 +4639,6 @@ * @memberof corbel */ corbel.Assets = corbel.Object.inherit({ - /** * Creates a new AssetsBuilder * @memberof corbel.Assets.prototype @@ -4692,15 +4646,14 @@ * @return {corbel.Assets.AssetsBuilder} */ constructor: function(driver) { - this.driver = driver; + this.driver = driver }, asset: function(id) { - return new corbel.Assets.AssetsBuilder(this.driver, id); + return new corbel.Assets.AssetsBuilder(this.driver, id) } }, { - /** * moduleName constant * @constant @@ -4726,18 +4679,18 @@ * @return {corbel.Assets.AssetsBuilder} */ create: function(driver) { - return new corbel.Assets(driver); + return new corbel.Assets(driver) } - }); + }) - return corbel.Assets; - - })(); + return corbel.Assets + })() + /* global corbel */ + ; (function() { - /** * Module for organize user assets * @exports AssetsBuilder @@ -4746,7 +4699,6 @@ * @memberof corbel.Assets */ var AssetsBuilder = corbel.Assets.AssetsBuilder = corbel.Services.inherit({ - /** * Creates a new AssetsBuilder * @memberof corbel.Assets.AssetsBuilder.prototype @@ -4754,9 +4706,9 @@ * @return {corbel.Assets.AssetsBuilder} */ constructor: function(driver, id) { - this.driver = driver; - this.uri = 'asset'; - this.id = id; + this.driver = driver + this.uri = 'asset' + this.id = id }, /** @@ -4766,17 +4718,15 @@ * @return {Promise} Promise that resolves with an Asset or rejects with a {@link CorbelError} */ get: function(params) { - - var options = params ? corbel.utils.clone(params) : {}; + var options = params ? corbel.utils.clone(params) : {} var args = corbel.utils.extend(options, { url: this._buildUri(this.uri, this.id), method: corbel.request.method.GET, query: params ? corbel.utils.serializeParams(params) : null - }); - - return this.request(args); + }) + return this.request(args) }, /** @@ -4786,14 +4736,14 @@ * @return {Promise} Promise that resolves with an Asset or rejects with a {@link CorbelError} */ getAll: function(params) { - var options = params ? corbel.utils.clone(params) : {}; + var options = params ? corbel.utils.clone(params) : {} var args = corbel.utils.extend(options, { url: this._buildUri(this.uri, 'all'), method: corbel.request.method.GET, query: params ? corbel.utils.serializeParams(params) : null - }); - return this.request(args); + }) + return this.request(args) }, /** @@ -4802,11 +4752,11 @@ * @return {Promise} Promise that resolves to undefined (void) or rejects with a {@link CorbelError} */ delete: function() { - corbel.validate.value('id', this.id); + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id), method: corbel.request.method.DELETE - }); + }) }, /** @@ -4825,10 +4775,9 @@ url: this._buildUri(this.uri), method: corbel.request.method.POST, data: data - }). - then(function(res) { - return corbel.Services.getLocationId(res); - }); + }).then(function(res) { + return corbel.Services.getLocationId(res) + }) }, /** @@ -4837,42 +4786,40 @@ * @return {Promise} Promise that resolves to a redirection to iam/oauth/token/upgrade or rejects with a {@link CorbelError} */ access: function(params) { - var args = params ? corbel.utils.clone(params) : {}; - args.url = this._buildUri(this.uri + '/access'); - args.method = corbel.request.method.GET; - args.noRedirect = true; + var args = params ? corbel.utils.clone(params) : {} + args.url = this._buildUri(this.uri + '/access') + args.method = corbel.request.method.GET + args.noRedirect = true - var that = this; + var that = this - return this.request(args). - then(function(response) { + return this.request(args).then(function(response) { return that.request({ noRetry: args.noRetry, method: corbel.request.method.POST, contentType: 'application/x-www-form-urlencoded; charset=UTF-8', data: response.data, url: response.headers.location - }); - }); + }) + }) }, _buildUri: function(path, id) { - var uri = ''; - var urlBase = this.driver.config.getCurrentEndpoint(corbel.Assets.moduleName, this._buildPort(this.driver.config)); + var uri = '' + var urlBase = this.driver.config.getCurrentEndpoint(corbel.Assets.moduleName, this._buildPort(this.driver.config)) - uri = urlBase + path; + uri = urlBase + path if (id) { - uri += '/' + id; + uri += '/' + id } - return uri; + return uri }, _buildPort: function(config) { - return config.get('assetsPort', null) || corbel.Assets.defaultPort; + return config.get('assetsPort', null) || corbel.Assets.defaultPort } }, { - /** * GET constant * @constant @@ -4889,130 +4836,123 @@ * @default */ create: function(driver) { - return new corbel.Assets.AssetsBuilder(driver); + return new corbel.Assets.AssetsBuilder(driver) } - }); + }) - return AssetsBuilder; - - })(); + return AssetsBuilder + })() + ; (function() { corbel.Scheduler = corbel.Object.inherit({ - /** * Create a new SchedulerBuilder * @param {String} type String * @return {Scheduler} */ constructor: function(driver) { - this.driver = driver; + this.driver = driver }, task: function(id) { - return new corbel.Scheduler.TaskBuilder(this.driver, id); + return new corbel.Scheduler.TaskBuilder(this.driver, id) } }, { - moduleName: 'scheduler', defaultPort: 8098, create: function(driver) { - return new corbel.Scheduler(driver); + return new corbel.Scheduler(driver) } - }); + }) - return corbel.Scheduler; - })(); + return corbel.Scheduler + })() + /*globals corbel */ + ; (function() { - var TaskBuilder = corbel.Scheduler.TaskBuilder = corbel.Services.inherit({ - constructor: function(driver, id) { - this.uri = 'tasks'; - this.driver = driver; - this.id = id; + this.uri = 'tasks' + this.driver = driver + this.id = id }, create: function(task) { - console.log('schedulerInterface.task.create', task); + console.log('schedulerInterface.task.create', task) return this.request({ url: this._buildUri(this.uri), method: corbel.request.method.POST, data: task - }). - then(function(res) { - return corbel.Services.getLocationId(res); - }); + }).then(function(res) { + return corbel.Services.getLocationId(res) + }) }, get: function(params) { - console.log('schedulerInterface.task.get', params); - corbel.validate.value('id', this.id); + console.log('schedulerInterface.task.get', params) + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id), method: corbel.request.method.GET, query: params ? corbel.utils.serializeParams(params) : null - }); + }) }, update: function(task) { - console.log('schedulerInterface.task.update', task); - corbel.validate.value('id', this.id); + console.log('schedulerInterface.task.update', task) + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id), method: corbel.request.method.PUT, data: task - }); + }) }, delete: function() { - console.log('schedulerInterface.task.delete'); - corbel.validate.value('id', this.id); + console.log('schedulerInterface.task.delete') + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id), method: corbel.request.method.DELETE - }); + }) }, _buildUri: function(path, id) { - var uri = ''; - var urlBase = this.driver.config.getCurrentEndpoint(corbel.Scheduler.moduleName, this._buildPort(this.driver.config)); + var uri = '' + var urlBase = this.driver.config.getCurrentEndpoint(corbel.Scheduler.moduleName, this._buildPort(this.driver.config)) - uri = urlBase + path; + uri = urlBase + path if (id) { - uri += '/' + id; + uri += '/' + id } - return uri; + return uri }, _buildPort: function(config) { - return config.get('schedulerPort', null) || corbel.Notifications.defaultPort; + return config.get('schedulerPort', null) || corbel.Notifications.defaultPort } }, { - moduleName: 'tasks', create: function(driver) { - return new corbel.TaskBuilder(driver); + return new corbel.TaskBuilder(driver) } - }); - - return TaskBuilder; - - })(); + }) + return TaskBuilder + })() var aggregationBuilder = (function() { - - var aggregationBuilder = {}; + var aggregationBuilder = {} /** * Adds a count operation to aggregation @@ -5020,19 +4960,19 @@ * @return {RequestParamsBuilder} RequestParamsBuilder */ aggregationBuilder.count = function(field) { - this.params.aggregation = this.params.aggregation || {}; - this.params.aggregation.$count = field; - return this; - }; + this.params.aggregation = this.params.aggregation || {} + this.params.aggregation.$count = field + return this + } - return aggregationBuilder; + return aggregationBuilder + })() - })(); + module.exports = aggregationBuilder var queryBuilder = (function() { - - var queryBuilder = {}; + var queryBuilder = {} /** * Adds an Equal criteria to query @@ -5041,9 +4981,9 @@ * @return {RequestParamsBuilder} RequestParamsBuilder */ queryBuilder.eq = function(field, value) { - this.addCriteria('$eq', field, value); - return this; - }; + this.addCriteria('$eq', field, value) + return this + } /** * Adds a Greater Than criteria to query @@ -5052,9 +4992,9 @@ * @return {RequestParamsBuilder} RequestParamsBuilder */ queryBuilder.gt = function(field, value) { - this.addCriteria('$gt', field, value); - return this; - }; + this.addCriteria('$gt', field, value) + return this + } /** * Adds a Greater Than Or Equal criteria to query @@ -5063,9 +5003,9 @@ * @return {RequestParamsBuilder} RequestParamsBuilder */ queryBuilder.gte = function(field, value) { - this.addCriteria('$gte', field, value); - return this; - }; + this.addCriteria('$gte', field, value) + return this + } /** * Adds a Less Than criteria to query @@ -5074,9 +5014,9 @@ * @return {RequestParamsBuilder} RequestParamsBuilder */ queryBuilder.lt = function(field, value) { - this.addCriteria('$lt', field, value); - return this; - }; + this.addCriteria('$lt', field, value) + return this + } /** * Adds a Less Than Or Equal criteria to query @@ -5085,9 +5025,9 @@ * @return {RequestParamsBuilder} RequestParamsBuilder */ queryBuilder.lte = function(field, value) { - this.addCriteria('$lte', field, value); - return this; - }; + this.addCriteria('$lte', field, value) + return this + } /** * Adds a Not Equal criteria to query @@ -5096,9 +5036,9 @@ * @return {RequestParamsBuilder} RequestParamsBuilder */ queryBuilder.ne = function(field, value) { - this.addCriteria('$ne', field, value); - return this; - }; + this.addCriteria('$ne', field, value) + return this + } /** * Adds a Like criteria to query @@ -5107,9 +5047,9 @@ * @return {RequestParamsBuilder} RequestParamsBuilder */ queryBuilder.like = function(field, value) { - this.addCriteria('$like', field, value); - return this; - }; + this.addCriteria('$like', field, value) + return this + } /** * Adds an In criteria to query @@ -5118,9 +5058,9 @@ * @return {RequestParamsBuilder} RequestParamsBuilder */ queryBuilder.in = function(field, values) { - this.addCriteria('$in', field, values); - return this; - }; + this.addCriteria('$in', field, values) + return this + } /** * Adds an All criteria to query @@ -5129,9 +5069,9 @@ * @return {RequestParamsBuilder} RequestParamsBuilder */ queryBuilder.all = function(field, values) { - this.addCriteria('$all', field, values); - return this; - }; + this.addCriteria('$all', field, values) + return this + } /** * Adds an Element Match criteria to query @@ -5140,36 +5080,36 @@ * @return {RequestParamsBuilder} RequestParamsBuilder */ queryBuilder.elemMatch = function(field, query) { - this.addCriteria('$elem_match', field, query); - return this; - }; + this.addCriteria('$elem_match', field, query) + return this + } /** * Sets an specific queryDomain, by default 'api'. * @param {String} queryDomain query domain name, 'api' and '7digital' supported */ queryBuilder.setQueryDomain = function(queryDomain) { - this.params.queryDomain = queryDomain; - return this; - }; + this.params.queryDomain = queryDomain + return this + } queryBuilder.addCriteria = function(operator, field, value) { - var criteria = {}; - criteria[operator] = {}; - criteria[operator][field] = value; - this.params.query = this.params.query || []; - this.params.query.push(criteria); - return this; - }; + var criteria = {} + criteria[operator] = {} + criteria[operator][field] = value + this.params.query = this.params.query || [] + this.params.query.push(criteria) + return this + } - return queryBuilder; + return queryBuilder + })() - })(); + module.exports = queryBuilder var pageBuilder = (function() { - - var pageBuilder = {}; + var pageBuilder = {} /** * Sets the page number of the page param @@ -5177,10 +5117,10 @@ * @return {RequestParamsBuilder} RequestParamsBuilder */ pageBuilder.page = function(page) { - this.params.pagination = this.params.pagination || {}; - this.params.pagination.page = page; - return this; - }; + this.params.pagination = this.params.pagination || {} + this.params.pagination.page = page + return this + } /** * Sets the page size of the page param @@ -5188,10 +5128,10 @@ * @return {RequestParamsBuilder} RequestParamsBuilder */ pageBuilder.pageSize = function(pageSize) { - this.params.pagination = this.params.pagination || {}; - this.params.pagination.pageSize = pageSize; - return this; - }; + this.params.pagination = this.params.pagination || {} + this.params.pagination.pageSize = pageSize + return this + } /** * Sets the page number and page size of the page param @@ -5199,51 +5139,54 @@ * @return {RequestParamsBuilder} RequestParamsBuilder */ pageBuilder.pageParam = function(page, pageSize) { - this.params.pagination = this.params.pagination || {}; - this.params.pagination.page = page; - this.params.pagination.pageSize = pageSize; - return this; - }; - - return pageBuilder; - + this.params.pagination = this.params.pagination || {} + this.params.pagination.page = page + this.params.pagination.pageSize = pageSize + return this + } - })(); + return pageBuilder + })() + module.exports = pageBuilder + /* global corbel */ var sortBuilder = (function() { - - var sortBuilder = {}; + var sortBuilder = {} /** * Sets ascending direction to sort param * @return {RequestParamsBuilder} RequestParamsBuilder */ sortBuilder.asc = function(field) { - this.params.sort = this.params.sort || {}; - this.params.sort[field] = corbel.Resources.sort.ASC; - return this; - }; + this.params.sort = this.params.sort || {} + this.params.sort[field] = corbel.Resources.sort.ASC + return this + } /** * Sets descending direction to sort param * @return {RequestParamsBuilder} RequestParamsBuilder */ sortBuilder.desc = function(field) { - this.params.sort = this.params.sort || {}; - this.params.sort[field] = corbel.Resources.sort.DESC; - return this; - }; - - return sortBuilder; - })(); - + this.params.sort = this.params.sort || {} + this.params.sort[field] = corbel.Resources.sort.DESC + return this + } - (function(aggregationBuilder, queryBuilder, sortBuilder, pageBuilder) { + return sortBuilder + })() + module.exports = sortBuilder + var aggregationBuilder = require('./aggregationBuilder') + var pageBuilder = require('./pageBuilder') + var queryBuilder = require('./queryBuilder') + var sortBuilder = require('./sortBuilder') + ; + (function(aggregationBuilder, queryBuilder, sortBuilder, pageBuilder) { /** * A module to build Request Params * @exports requestParamsBuilder @@ -5252,50 +5195,47 @@ */ corbel.requestParamsBuilder = corbel.Object.inherit({ constructor: function() { - this.params = {}; + this.params = {} }, /** * Returns the JSON representation of the params * @return {JSON} representation of the params */ build: function() { - return this.params; + return this.params } - }); - + }) - corbel.utils.extend(corbel.requestParamsBuilder.prototype, queryBuilder, sortBuilder, aggregationBuilder, pageBuilder); + corbel.utils.extend(corbel.requestParamsBuilder.prototype, queryBuilder, sortBuilder, aggregationBuilder, pageBuilder) - return corbel.requestParamsBuilder; + return corbel.requestParamsBuilder + })(aggregationBuilder, queryBuilder, sortBuilder, pageBuilder) - })(aggregationBuilder, queryBuilder, sortBuilder, pageBuilder); + ; (function() { corbel.Resources = corbel.Object.inherit({ - constructor: function(driver) { - this.driver = driver; + this.driver = driver }, collection: function(type) { - return new corbel.Resources.Collection(type, this.driver); + return new corbel.Resources.Collection(type, this.driver) }, resource: function(type, id) { - return new corbel.Resources.Resource(type, id, this.driver); + return new corbel.Resources.Resource(type, id, this.driver) }, relation: function(srcType, srcId, destType) { - return new corbel.Resources.Relation(srcType, srcId, destType, this.driver); + return new corbel.Resources.Relation(srcType, srcId, destType, this.driver) } }, { - moduleName: 'resources', defaultPort: 8080, sort: { - /** * Ascending sort * @type {String} @@ -5321,19 +5261,19 @@ ALL: '_', create: function(driver) { - return new corbel.Resources(driver); + return new corbel.Resources(driver) } - }); + }) - return corbel.Resources; + return corbel.Resources + })() - })(); + /* global corbel */ + ; (function() { - corbel.Resources.BaseResource = corbel.Services.inherit({ - /** * Helper function to build the request uri * @param {String} srcType Type of the resource @@ -5343,63 +5283,62 @@ * @return {String} Uri to perform the request */ buildUri: function(srcType, srcId, destType, destId) { + var urlBase = this.driver.config.getCurrentEndpoint(corbel.Resources.moduleName, this._buildPort(this.driver.config)) - var urlBase = this.driver.config.getCurrentEndpoint(corbel.Resources.moduleName, this._buildPort(this.driver.config)); - - var domain = this.driver.config.get(corbel.Iam.IAM_DOMAIN, 'unauthenticated'); - var customDomain = this.driver.config.get(corbel.Domain.CUSTOM_DOMAIN, domain); + var domain = this.driver.config.get(corbel.Iam.IAM_DOMAIN, 'unauthenticated') + var customDomain = this.driver.config.get(corbel.Domain.CUSTOM_DOMAIN, domain) - this.driver.config.set(corbel.Domain.CUSTOM_DOMAIN, undefined); + this.driver.config.set(corbel.Domain.CUSTOM_DOMAIN, undefined) - var uri = urlBase + customDomain + '/resource/' + srcType; + var uri = urlBase + customDomain + '/resource/' + srcType if (srcId) { - uri += '/' + srcId; + uri += '/' + srcId if (destType) { - uri += '/' + destType; + uri += '/' + destType if (destId) { - uri += ';r=' + destType + '/' + destId; + uri += ';r=' + destType + '/' + destId } } } - return uri; + return uri }, _buildPort: function(config) { - return config.get('resourcesPort', null) || corbel.Resources.defaultPort; + return config.get('resourcesPort', null) || corbel.Resources.defaultPort }, request: function(args) { - var params = corbel.utils.extend(this.params, args); + var params = corbel.utils.extend(this.params, args) - this.params = {}; //reset instance params + this.params = {} // reset instance params - args.query = corbel.utils.serializeParams(params); + args.query = corbel.utils.serializeParams(params) - //call service request implementation - return corbel.Services.prototype.request.apply(this, [args].concat(Array.prototype.slice.call(arguments, 1))); + // call service request implementation + return corbel.Services.prototype.request.apply(this, [args].concat(Array.prototype.slice.call(arguments, 1))) }, getURL: function(params) { - return this.buildUri(this.type, this.srcId, this.destType) + (params ? '?' + corbel.utils.serializeParams(params) : ''); + return this.buildUri(this.type, this.srcId, this.destType) + (params ? '?' + corbel.utils.serializeParams(params) : '') }, getDefaultOptions: function(options) { - var defaultOptions = options ? corbel.utils.clone(options) : {}; + var defaultOptions = options ? corbel.utils.clone(options) : {} - return defaultOptions; + return defaultOptions } - }); + }) // extend for inherit requestParamsBuilder methods extensible for all Resources object - corbel.utils.extend(corbel.Resources.BaseResource.prototype, corbel.requestParamsBuilder.prototype); - - return corbel.Resources.BaseResource; + corbel.utils.extend(corbel.Resources.BaseResource.prototype, corbel.requestParamsBuilder.prototype) - })(); + return corbel.Resources.BaseResource + })() + ; (function() { /** @@ -5411,14 +5350,13 @@ * @param {String} destType The destination resource type */ corbel.Resources.Relation = corbel.Resources.BaseResource.inherit({ - constructor: function(srcType, srcId, destType, driver, params) { - this.type = srcType; - this.srcId = srcId; - this.destType = destType; - corbel.validate.values(['type', 'srcId', 'destType'], this); - this.driver = driver; - this.params = params || {}; + this.type = srcType + this.srcId = srcId + this.destType = destType + corbel.validate.values(['type', 'srcId', 'destType'], this) + this.driver = driver + this.params = params || {} }, /** @@ -5432,14 +5370,14 @@ * @see {@link corbel.util.serializeParams} to see a example of the params */ get: function(destId, options) { - options = this.getDefaultOptions(options); + options = this.getDefaultOptions(options) var args = corbel.utils.extend(options, { url: this.buildUri(this.type, this.srcId, this.destType, destId), method: corbel.request.method.GET, Accept: options.dataType - }); + }) - return this.request(args); + return this.request(args) }, /** @@ -5452,17 +5390,17 @@ * @example uri = '555' */ add: function(destId, relationData, options) { - options = this.getDefaultOptions(options); - corbel.validate.value('destId', destId); + options = this.getDefaultOptions(options) + corbel.validate.value('destId', destId) var args = corbel.utils.extend(options, { url: this.buildUri(this.type, this.srcId, this.destType, destId), contentType: 'application/json', data: relationData, method: corbel.request.method.PUT - }); + }) - return this.request(args); + return this.request(args) }, /** @@ -5474,16 +5412,16 @@ * @example uri = '555' */ addAnonymous: function(relationData, options) { - options = this.getDefaultOptions(options); + options = this.getDefaultOptions(options) var args = corbel.utils.extend(options, { url: this.buildUri(this.type, this.srcId, this.destType), contentType: 'application/json', data: relationData, method: corbel.request.method.POST - }); + }) - return this.request(args); + return this.request(args) }, /** @@ -5494,13 +5432,13 @@ * @return {Promise} ES6 promise that resolves to undefined (void) or rejects with a {@link CorbelError} */ move: function(destId, pos, options) { - corbel.validate.value('destId', destId); - var positionStartId = destId.indexOf('/'); + corbel.validate.value('destId', destId) + var positionStartId = destId.indexOf('/') if (positionStartId !== -1) { - destId = destId.substring(positionStartId + 1); + destId = destId.substring(positionStartId + 1) } - options = this.getDefaultOptions(options); + options = this.getDefaultOptions(options) var args = corbel.utils.extend(options, { url: this.buildUri(this.type, this.srcId, this.destType, destId), @@ -5509,9 +5447,9 @@ '_order': '$pos(' + pos + ')' }, method: corbel.request.method.PUT - }); + }) - return this.request(args); + return this.request(args) }, /** @@ -5524,24 +5462,23 @@ * destId = 'music:Track/555' */ delete: function(destId, options) { - options = this.getDefaultOptions(options); + options = this.getDefaultOptions(options) var args = corbel.utils.extend(options, { url: this.buildUri(this.type, this.srcId, this.destType, destId), method: corbel.request.method.DELETE - }); + }) - return this.request(args); + return this.request(args) } - }); + }) - return corbel.Resources.Relation; + return corbel.Resources.Relation + })() - })(); + ; (function() { - - /** * Collection requests * @class @@ -5550,12 +5487,11 @@ * @param {CorbelDriver} corbel instance */ corbel.Resources.Collection = corbel.Resources.BaseResource.inherit({ - constructor: function(type, driver, params) { - this.type = type; - corbel.validate.value('type', this.type); - this.driver = driver; - this.params = params || {}; + this.type = type + corbel.validate.value('type', this.type) + this.driver = driver + this.params = params || {} }, /** @@ -5567,15 +5503,15 @@ * @see {@link corbel.util.serializeParams} to see a example of the params */ get: function(options) { - options = this.getDefaultOptions(options); + options = this.getDefaultOptions(options) var args = corbel.utils.extend(options, { url: this.buildUri(this.type), method: corbel.request.method.GET, Accept: options.dataType - }); + }) - return this.request(args); + return this.request(args) }, /** @@ -5587,7 +5523,7 @@ * @return {Promise} ES6 promise that resolves to the new resource id or rejects with a {@link CorbelError} */ add: function(data, options) { - options = this.getDefaultOptions(options); + options = this.getDefaultOptions(options) var args = corbel.utils.extend(options, { url: this.buildUri(this.type), @@ -5595,11 +5531,11 @@ contentType: options.dataType, Accept: options.dataType, data: data - }); + }) return this.request(args).then(function(res) { - return corbel.Services.getLocationId(res); - }); + return corbel.Services.getLocationId(res) + }) }, /** @@ -5611,7 +5547,7 @@ * @return {Promise} ES6 promise that resolves to an {Array} of resources or rejects with a {@link CorbelError} */ update: function(data, options) { - options = this.getDefaultOptions(options); + options = this.getDefaultOptions(options) var args = corbel.utils.extend(options, { url: this.buildUri(this.type), @@ -5619,9 +5555,9 @@ contentType: options.dataType, Accept: options.dataType, data: data - }); + }) - return this.request(args); + return this.request(args) }, /** @@ -5632,24 +5568,24 @@ * @return {Promise} ES6 promise that resolves to the new resource id or rejects with a {@link CorbelError} */ delete: function(options) { - options = this.getDefaultOptions(options); + options = this.getDefaultOptions(options) var args = corbel.utils.extend(options, { url: this.buildUri(this.type), method: corbel.request.method.DELETE, contentType: options.dataType, Accept: options.dataType - }); + }) - return this.request(args); + return this.request(args) } - }); - - return corbel.Resources.Collection; + }) - })(); + return corbel.Resources.Collection + })() + ; (function() { /** @@ -5660,14 +5596,13 @@ * @param {String} id The resource id */ corbel.Resources.Resource = corbel.Resources.BaseResource.inherit({ - constructor: function(type, id, driver, params) { - this.type = type; - this.id = id; - corbel.validate.values(['type', 'id'], this); + this.type = type + this.id = id + corbel.validate.values(['type', 'id'], this) - this.driver = driver; - this.params = params || {}; + this.driver = driver + this.params = params || {} }, /** @@ -5681,20 +5616,18 @@ * @see {@link services.request} to see a example of the params */ get: function(options) { - options = this.getDefaultOptions(options); - + options = this.getDefaultOptions(options) var args = corbel.utils.extend(options, { url: this.buildUri(this.type, this.id), method: corbel.request.method.GET, contentType: options.dataType, Accept: options.dataType - }); + }) - return this.request(args); + return this.request(args) }, - /** * Updates a resource * @method @@ -5707,7 +5640,7 @@ * @see {@link services.request} to see a example of the params */ update: function(data, options) { - options = this.getDefaultOptions(options); + options = this.getDefaultOptions(options) var args = corbel.utils.extend(options, { url: this.buildUri(this.type, this.id), @@ -5715,12 +5648,11 @@ data: data, contentType: options.dataType, Accept: options.dataType - }); + }) - return this.request(args); + return this.request(args) }, - /** * Updates the ACL of a resource * @method @@ -5734,9 +5666,9 @@ method: corbel.request.method.PUT, data: acl, Accept: 'application/corbel.acl+json' - }; + } - return this.request(args); + return this.request(args) }, /** @@ -5748,26 +5680,26 @@ * @return {Promise} ES6 promise that resolves to undefined (void) or rejects with a {@link CorbelError} */ delete: function(options) { - options = this.getDefaultOptions(options); + options = this.getDefaultOptions(options) var args = corbel.utils.extend(options, { url: this.buildUri(this.type, this.id), method: corbel.request.method.DELETE, contentType: options.dataType, Accept: options.dataType - }); + }) - return this.request(args); + return this.request(args) } - }); + }) - return corbel.Resources.Resource; - - })(); + return corbel.Resources.Resource + })() + /* global corbel */ + ; (function() { - /** * A module to make Oauth requests. * @exports Oauth @@ -5776,83 +5708,83 @@ */ var Oauth = corbel.Oauth = function(driver) { - this.driver = driver; - }; + this.driver = driver + } - Oauth.moduleName = 'oauth'; - Oauth.defaultPort = 8084; + Oauth.moduleName = 'oauth' + Oauth.defaultPort = 8084 Oauth.create = function(driver) { - return new Oauth(driver); - }; - /** - * Private method to build a string uri - * @private - * @param {String} uri - * @return {String} - */ + return new Oauth(driver) + } + /** + * Private method to build a string uri + * @private + * @param {String} uri + * @return {String} + */ Oauth._buildUri = function(uri) { + var urlBase = this.driver.config.getCurrentEndpoint(Oauth.moduleName, corbel.Oauth._buildPort(this.driver.config)) - var urlBase = this.driver.config.getCurrentEndpoint(Oauth.moduleName, corbel.Oauth._buildPort(this.driver.config)); - - return urlBase + uri; - }; + return urlBase + uri + } Oauth._buildPort = function(config) { - return config.get('oauthPort', null) || corbel.Oauth.defaultPort; - }; + return config.get('oauthPort', null) || corbel.Oauth.defaultPort + } /** * Default encoding * @type {String} * @default application/x-www-form-urlencoded; charset=UTF-8 */ - Oauth._URL_ENCODED = 'application/x-www-form-urlencoded; charset=UTF-8'; + Oauth._URL_ENCODED = 'application/x-www-form-urlencoded; charset=UTF-8' Oauth._checkProp = function(dict, keys, excep) { - var error = excep ? excep : 'Error validating arguments'; + var error = !excep ? 'Error validating arguments' : excep if (!dict) { - throw new Error(error); + throw new Error(error) } for (var i in keys) { if (!(keys[i] in dict)) { - throw new Error(error); + throw new Error(error) } } - }; + } Oauth._validateResponseType = function(responseType) { if (['code', 'token'].indexOf(responseType) < 0) { - throw new Error('Only "code" or "token" response type allowed'); + throw new Error('Only "code" or "token" response type allowed') } - }; + } Oauth._validateGrantType = function(grantType) { if (grantType !== 'authorization_code') { - throw new Error('Only "authorization_code" grant type is allowed'); + throw new Error('Only "authorization_code" grant type is allowed') } - }; + } Oauth._trasformParams = function(clientParams) { - for (var key in clientParams) { - var keyWithUnderscores = this._toUnderscore(key); + var keyWithUnderscores = this._toUnderscore(key) if (key !== keyWithUnderscores) { - clientParams[keyWithUnderscores] = clientParams[key]; - delete clientParams[key]; + clientParams[keyWithUnderscores] = clientParams[key] + delete clientParams[key] } } - return clientParams; - }; + return clientParams + } Oauth._toUnderscore = function(string) { return string.replace(/([A-Z])/g, function($1) { - return '_' + $1.toLowerCase(); - }); - }; - })(); + return '_' + $1.toLowerCase() + }) + } + })() + /* global corbel */ + ; (function() { /** * Create a AuthorizationBuilder for resource managing requests. @@ -5862,25 +5794,25 @@ * @return {corbel.Oauth.AuthorizationBuilder} */ corbel.Oauth.prototype.authorization = function(clientParams) { - console.log('oauthInterface.authorization', clientParams); + console.log('oauthInterface.authorization', clientParams) - corbel.Oauth._checkProp(clientParams, ['responseType'], 'Invalid client parameters'); - clientParams.responseType = clientParams.responseType.toLowerCase(); - corbel.Oauth._validateResponseType(clientParams.responseType); + corbel.Oauth._checkProp(clientParams, ['responseType'], 'Invalid client parameters') + clientParams.responseType = clientParams.responseType.toLowerCase() + corbel.Oauth._validateResponseType(clientParams.responseType) if (clientParams.responseType.toLowerCase() === 'code') { - corbel.Oauth._checkProp(clientParams, ['redirectUri'], 'Invalid client parameters'); + corbel.Oauth._checkProp(clientParams, ['redirectUri'], 'Invalid client parameters') } - clientParams.clientId = clientParams.clientId || corbel.Config.get('oauthClientId'); + clientParams.clientId = clientParams.clientId || corbel.Config.get('oauthClientId') var params = { contentType: corbel.Oauth._URL_ENCODED, data: corbel.Oauth._trasformParams(clientParams), // http://stackoverflow.com/questions/1557602/jquery-and-ajax-response-header noRedirect: true - }; - var authorization = new AuthorizationBuilder(params); - authorization.driver = this.driver; - return authorization; - }; + } + var authorization = new AuthorizationBuilder(params) + authorization.driver = this.driver + return authorization + } /** * A builder for authorization management requests. @@ -5891,10 +5823,9 @@ * @memberOf corbel.Oauth.AuthorizationBuilder */ var AuthorizationBuilder = corbel.Oauth.AuthorizationBuilder = corbel.Services.inherit({ - constructor: function(params) { - this.params = params; - this.uri = 'oauth'; + this.params = params + this.uri = 'oauth' }, /** @@ -5904,8 +5835,8 @@ * @return {Promise} Q promise that resolves to a redirection to redirectUri or rejects with a 404 {@link CorbelError} */ loginWithCookie: function() { - console.log('oauthInterface.authorization.dialog'); - // make request, generate oauth cookie, then redirect manually + console.log('oauthInterface.authorization.dialog') + // make request, generate oauth cookie, then redirect manually return this.request({ url: this._buildUri(this.uri + '/authorize'), method: corbel.request.method.GET, @@ -5914,8 +5845,8 @@ data: this.params, query: this.params.data ? corbel.utils.serializeParams(this.params.data) : null }).then(function(res) { - return corbel.Services.getLocationId(res); - }); + return corbel.Services.getLocationId(res) + }) }, /** * Does a login in oauth server @@ -5926,12 +5857,12 @@ * @return {Promise} Q promise that resolves to a redirection to redirectUri or rejects with a {@link CorbelError} */ login: function(username, password, setCookie) { - console.log('oauthInterface.authorization.login', username + ':' + password); + console.log('oauthInterface.authorization.login', username + ':' + password) - this.params.data.username = username; - this.params.data.password = password; - this.params.withCredentials = true; - // make request, generate oauth cookie, then redirect manually + this.params.data.username = username + this.params.data.password = password + this.params.withCredentials = true + // make request, generate oauth cookie, then redirect manually return this.request({ url: this._buildUri(this.uri + '/authorize'), method: corbel.request.method.POST, @@ -5941,20 +5872,20 @@ if (res.jqXHR.getResponseHeader('Location')) { var params = { url: corbel.Services.getLocationId(res) - }; + } if (setCookie) { params.headers = { RequestCookie: 'true' - }; - params.withCredentials = true; + } + params.withCredentials = true } - return this.request(params); + return this.request(params) } else { - return res.data; + return res.data } - }); + }) }, /** @@ -5964,23 +5895,24 @@ * @return {Promise} promise that resolves empty when the sign out process completes or rejects with a {@link CorbelError} */ signout: function() { - console.log('oauthInterface.authorization.signOut'); - delete this.params.data; + console.log('oauthInterface.authorization.signOut') + delete this.params.data return this.request({ url: this._buildUri(this.uri + '/signout'), method: corbel.request.method.GET, withCredentials: true }).then(function(res) { - return corbel.Services.getLocationId(res); - }); + return corbel.Services.getLocationId(res) + }) }, _buildUri: corbel.Oauth._buildUri - }); - - })(); + }) + })() + /* global corbel */ + ; (function() { /** * Create a TokenBuilder for token managing requests. @@ -5993,58 +5925,55 @@ * @return {corbel.Oauth.TokenBuilder} */ corbel.Oauth.prototype.token = function(clientParams) { - console.log('oauthInterface.token'); + console.log('oauthInterface.token') - corbel.Oauth._checkProp(clientParams, ['grantType'], 'Invalid client parameters'); - corbel.Oauth._validateGrantType(clientParams.grantType); - clientParams.clientId = clientParams.clientId || corbel.Config.get('oauthClientId'); - clientParams.clientSecret = clientParams.clientSecret || corbel.Config.get('oauthSecret'); - var params = { - contentType: corbel.Oauth._URL_ENCODED, - data: corbel.Oauth._trasformParams(clientParams) - }; - var token = new TokenBuilder(params); - token.driver = this.driver; - return token; - }; - /** - * A builder for a token management requests. - * @class - * - * @param {Object} params Initial params - * - * @memberOf corbel.Oauth.TokenBuilder - */ + corbel.Oauth._checkProp(clientParams, ['grantType'], 'Invalid client parameters') + corbel.Oauth._validateGrantType(clientParams.grantType) + clientParams.clientId = clientParams.clientId || corbel.Config.get('oauthClientId') + clientParams.clientSecret = clientParams.clientSecret || corbel.Config.get('oauthSecret') + var params = { + contentType: corbel.Oauth._URL_ENCODED, + data: corbel.Oauth._trasformParams(clientParams) + } + var token = new TokenBuilder(params) + token.driver = this.driver + return token + } + /** + * A builder for a token management requests. + * @class + * @param {Object} params Initial params + * @memberOf corbel.Oauth.TokenBuilder + */ var TokenBuilder = corbel.Oauth.TokenBuilder = corbel.Services.inherit({ - constructor: function(params) { - this.params = params; - this.uri = 'oauth/token'; + this.params = params + this.uri = 'oauth/token' }, /** * Get an access token * @method * @memberOf corbel.Oauth.TokenBuilder - * * @param {String} code The code to exchange for the token - * * @return {Promise} promise that resolves to an access token {Object} or rejects with a {@link CorbelError} */ get: function(code) { - console.log('oauthInterface.token.get'); - this.params.data.code = code; + console.log('oauthInterface.token.get') + this.params.data.code = code return this.request({ url: this._buildUri(this.uri), method: corbel.request.method.POST, data: this.params - }); + }) }, _buildUri: corbel.Oauth._buildUri - }); - })(); + }) + })() + /* global corbel btoa */ + ; (function() { /** * Create a UserBuilder for user managing requests. @@ -6057,41 +5986,38 @@ * @return {corbel.Oauth.UserBuilder} */ corbel.Oauth.prototype.user = function(clientParams, accessToken) { - console.log('oauthInterface.user'); + console.log('oauthInterface.user') - var params = {}; + var params = {} - if (accessToken) { - params.accessToken = accessToken; - params.headers = {}; - params.headers.Accept = 'application/json'; - } + if (accessToken) { + params.accessToken = accessToken + params.headers = {} + params.headers.Accept = 'application/json' + } - clientParams = clientParams || {}; - var clientId = clientParams.clientId || corbel.Config.get('oauthClientId'); - var clientSecret = clientParams.clientSecret || corbel.Config.get('oauthSecret'); + clientParams = clientParams || {} + var clientId = clientParams.clientId || corbel.Config.get('oauthClientId') + var clientSecret = clientParams.clientSecret || corbel.Config.get('oauthSecret') - var user = new UserBuilder(params, clientId, clientSecret); - user.driver = this.driver; - return user; - }; - /** - * A builder for a user management requests. - * @class - * - * @param {Object} params Parameters for initializing the builder - * @param {String} [clientId] Application client Id (required for creating user) - * @param {String} [clientSecret] Application client secret (required for creating user) - * - * @memberOf corbel.Oauth.UserBuilder - */ + var user = new UserBuilder(params, clientId, clientSecret) + user.driver = this.driver + return user + } + /** + * A builder for a user management requests. + * @class + * @param {Object} params Parameters for initializing the builder + * @param {String} [clientId] Application client Id (required for creating user) + * @param {String} [clientSecret] Application client secret (required for creating user) + * @memberOf corbel.Oauth.UserBuilder + */ var UserBuilder = corbel.Oauth.UserBuilder = corbel.Services.inherit({ - constructor: function(params, clientId, clientSecret) { - this.params = params; - this.clientSecret = clientSecret; - this.clientId = clientId; - this.uri = 'user'; + this.params = params + this.clientSecret = clientSecret + this.clientId = clientId + this.uri = 'user' }, _buildUri: corbel.Oauth._buildUri, /** @@ -6109,7 +6035,7 @@ * with a {@link corbelError}. */ create: function(user) { - console.log('oauthInterface.user.create', user); + console.log('oauthInterface.user.create', user) return this.request({ url: this._buildUri(this.uri), @@ -6120,75 +6046,69 @@ dataType: 'text', data: user }).then(function(res) { - return corbel.Services.getLocationId(res); - }); + return corbel.Services.getLocationId(res) + }) }, /** * Gets the user or the logged user * @method * @memberOf corbel.Oauth.UserBuilder - * - * @param {Object} id The user id/me - * + * @param {Object} id The user id/me * @return {Promise} Q promise that resolves to a User {Object} or rejects with a {@link corbelError} */ get: function(id) { - console.log('oauthInterface.user.get'); - this.uri += '/' + id; + console.log('oauthInterface.user.get') + this.uri += '/' + id return this.request({ url: this._buildUri(this.uri, this.uri), method: corbel.request.method.GET - }); + }) }, /** * Get profile of some user or the logged user * @method * @memberOf corbel.Oauth.UserBuilder - * @param {Object} id The user id/me + * @param {Object} id The user id/me * @return {Promise} Q promise that resolves to the profile from User {Object} or rejects with a {@link corbelError} */ getProfile: function(id) { - console.log('oauthInterface.user.getProfile'); - this.uri += '/' + id + '/profile'; + console.log('oauthInterface.user.getProfile') + this.uri += '/' + id + '/profile' return this.request({ url: this._buildUri(this.uri), method: corbel.request.method.GET - }); + }) }, /** * Updates the user or the logged user * @method * @memberOf corbel.Oauth.UserBuilder - * * @param {Object} id The user id or me * @param {Object} modification Json object with the modificacion of the user - * * @return {Promise} Q promise that resolves to undefined (void) or rejects with a {@link corbelError} */ update: function(id, modification) { - console.log('oauthInterface.user.update', modification); - this.uri += '/' + id; + console.log('oauthInterface.user.update', modification) + this.uri += '/' + id return this.request({ url: this._buildUri(this.uri), method: corbel.request.method.PUT, data: modification - }); + }) }, /** * Deletes the user or the logged user * @memberOf corbel.Oauth.UserBuilder - * * @param {Object} id The user id or me - * * @return {Promise} Q promise that resolves to undefined (void) or rejects with a {@link corbelError} */ delete: function(id) { - console.log('oauthInterface.user.delete'); - this.uri += '/' + id; + console.log('oauthInterface.user.delete') + this.uri += '/' + id return this.request({ url: this._buildUri(this.uri), method: corbel.request.method.DELETE - }); + }) }, /** * Sends a reset password email to the email address recived. @@ -6198,7 +6118,7 @@ * @return {Promise} Q promise that resolves to undefined (void) or rejects with a {@link CorbelError} */ sendResetPasswordEmail: function(userEmailToReset) { - console.log('oauthInterface.user.SendResetPasswordEmail', userEmailToReset); + console.log('oauthInterface.user.SendResetPasswordEmail', userEmailToReset) return this.request({ url: this._buildUri(this.uri + '/resetPassword'), method: corbel.request.method.GET, @@ -6208,102 +6128,96 @@ }, noRetry: true }).then(function(res) { - return corbel.Services.getLocationId(res); - }); + return corbel.Services.getLocationId(res) + }) }, /** * Sends a email to the logged user or user to validate his email address * @method * @memberOf corbel.Oauth.UsersBuilder - * * @param {Object} id The user id or me - * * @return {Promise} Q promise that resolves to undefined (void) or rejects with a {@link CorbelError} */ sendValidateEmail: function(id) { - console.log('oauthInterface.user.sendValidateEmail'); - this.uri += '/' + id + '/validate'; + console.log('oauthInterface.user.sendValidateEmail') + this.uri += '/' + id + '/validate' return this.request({ url: this._buildUri(this.uri), method: corbel.request.method.GET, withAuth: true - }); + }) }, /** * Validates the email of a user or the logged user * @method * @memberOf corbel.Oauth.UsersBuilder - * * @param {Object} id The user id or me - * * @return {Promise} Q promise that resolves to undefined (void) or rejects with a {@link CorbelError} */ emailConfirmation: function(id) { - console.log('oauthInterface.user.emailConfirmation'); - this.uri += '/' + id + '/emailConfirmation'; + console.log('oauthInterface.user.emailConfirmation') + this.uri += '/' + id + '/emailConfirmation' return this.request({ url: this._buildUri(this.uri, id), method: corbel.request.method.PUT, noRetry: true - }); + }) }, getSerializer: function() { if (corbel.Config.isNode) { - return require('btoa'); + return require('btoa') } else { - return btoa; + return btoa } } - }); - })(); + }) + })() + ; (function() { corbel.Notifications = corbel.Object.inherit({ - /** * Creates a new NotificationsBuilder * @param {String} id String with the asset id or 'all' key * @return {Notifications} */ constructor: function(driver) { - this.driver = driver; + this.driver = driver }, notification: function(id) { - return new corbel.Notifications.NotificationsBuilder(this.driver, id); + return new corbel.Notifications.NotificationsBuilder(this.driver, id) } }, { - moduleName: 'notifications', defaultPort: 8094, create: function(driver) { - return new corbel.Notifications(driver); + return new corbel.Notifications(driver) } - }); - - return corbel.Notifications; + }) - })(); + return corbel.Notifications + })() + /* global corbel */ + ; (function() { - var NotificationsBuilder = corbel.Notifications.NotificationsBuilder = corbel.Services.inherit({ - /** * Creates a new NotificationsBuilder * @param {String} id String with the asset id or 'all' key * @return {Assets} */ constructor: function(driver, id) { - this.driver = driver; - this.uri = 'notification'; - this.id = id; + this.driver = driver + this.uri = 'notification' + this.id = id }, /* * Creates a new notification @@ -6318,15 +6232,14 @@ * @return {Promise} Promise that resolves in the new notification id or rejects with a {@link CorbelError} */ create: function(notification) { - console.log('notificationsInterface.notification.create', notification); + console.log('notificationsInterface.notification.create', notification) return this.request({ url: this._buildUri(this.uri), method: corbel.request.method.POST, data: notification - }). - then(function(res) { - return corbel.Services.getLocationId(res); - }); + }).then(function(res) { + return corbel.Services.getLocationId(res) + }) }, /** * Gets a notification @@ -6336,12 +6249,12 @@ * @return {Promise} Promise that resolves to a Notification {Object} or rejects with a {@link CorbelError} */ get: function(params) { - console.log('notificationsInterface.notification.get', params); + console.log('notificationsInterface.notification.get', params) return this.request({ url: this._buildUri(this.uri, this.id), method: corbel.request.method.GET, query: params ? corbel.utils.serializeParams(params) : null - }); + }) }, /** * Updates a notification @@ -6352,13 +6265,13 @@ * @return {Promise} Promise that resolves to undefined (void) or rejects with a {@link CorbelError} */ update: function(data) { - console.log('notificationsInterface.notification.update', data); - corbel.validate.value('id', this.id); + console.log('notificationsInterface.notification.update', data) + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id), method: corbel.request.method.PUT, data: data - }); + }) }, /** * Deletes a notification @@ -6367,12 +6280,12 @@ * @return {Promise} Promise that resolves to undefined (void) or rejects with a {@link CorbelError} */ delete: function() { - console.log('notificationsInterface.notification.delete'); - corbel.validate.value('id', this.id); + console.log('notificationsInterface.notification.delete') + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id), method: corbel.request.method.DELETE - }); + }) }, /** * Send a notification @@ -6385,47 +6298,46 @@ * @return {Promise} Promise that resolves to undefined (void) or rejects with a {@link CorbelError} */ sendNotification: function(notification) { - console.log('notificationsInterface.notification.sendNotification', notification); - this.uri += '/send'; + console.log('notificationsInterface.notification.sendNotification', notification) + this.uri += '/send' return this.request({ url: this._buildUri(this.uri), method: corbel.request.method.POST, data: notification - }); + }) }, _buildUri: function(path, id) { - var uri = ''; - var urlBase = this.driver.config.getCurrentEndpoint(corbel.Notifications.moduleName, this._buildPort(this.driver.config)); + var uri = '' + var urlBase = this.driver.config.getCurrentEndpoint(corbel.Notifications.moduleName, this._buildPort(this.driver.config)) - uri = urlBase + path; + uri = urlBase + path if (id) { - uri += '/' + id; + uri += '/' + id } - return uri; + return uri }, _buildPort: function(config) { - return config.get('notificationsPort', null) || corbel.Notifications.defaultPort; + return config.get('notificationsPort', null) || corbel.Notifications.defaultPort } }, { - moduleName: 'notifications', create: function(driver) { - return new corbel.NotificationsBuilder(driver); + return new corbel.NotificationsBuilder(driver) } - }); - - return NotificationsBuilder; + }) - })(); + return NotificationsBuilder + })() + /* global corbel */ + ; (function() { - /** * A module to make Ec requests. * @exports Ec @@ -6434,15 +6346,15 @@ */ var Ec = corbel.Ec = function(driver) { - this.driver = driver; - }; + this.driver = driver + } - Ec.moduleName = 'ec'; - Ec.defaultPort = 8088; + Ec.moduleName = 'ec' + Ec.defaultPort = 8088 Ec.create = function(driver) { - return new Ec(driver); - }; + return new Ec(driver) + } Ec._ec = { /** @@ -6489,7 +6401,7 @@ */ CANCELLED: 'CANCELLED' } - }; + } /** * COMMON MIXINS @@ -6499,8 +6411,8 @@ // return { // name: data.name, // data: cse.encrypt(data.number, data.holderName, data.cvc, data.expiryMonth, data.expiryYear) - // }; - // }; + // } + // } /** * Private method to build a string uri @@ -6512,25 +6424,25 @@ */ Ec._buildUri = function(uri, id, extra) { if (id) { - uri += '/' + id; + uri += '/' + id } if (extra) { - uri += extra; + uri += extra } - var urlBase = this.driver.config.getCurrentEndpoint(Ec.moduleName, corbel.Ec._buildPort(this.driver.config)); + var urlBase = this.driver.config.getCurrentEndpoint(Ec.moduleName, corbel.Ec._buildPort(this.driver.config)) - return urlBase + uri; - }; + return urlBase + uri + } Ec._buildPort = function(config) { - return config.get('ecPort', null) || corbel.Ec.defaultPort; - }; - - })(); + return config.get('ecPort', null) || corbel.Ec.defaultPort + } + })() + /* global corbel */ + ; (function() { - /** * Create a OrderBuilder for order managing requests. * @@ -6539,10 +6451,10 @@ * @return {corbel.Ec.OrderBuilder} */ corbel.Ec.prototype.order = function(id) { - var order = new OrderBuilder(id); - order.driver = this.driver; - return order; - }; + var order = new OrderBuilder(id) + order.driver = this.driver + return order + } /** * A builder for order requests. @@ -6553,12 +6465,11 @@ * @memberOf corbel.Ec.OrderBuilder */ var OrderBuilder = corbel.Ec.OrderBuilder = corbel.Services.inherit({ - constructor: function(id) { if (id) { - this.id = id; + this.id = id } - this.uri = 'order'; + this.uri = 'order' }, /** @@ -6568,11 +6479,11 @@ * @return {Promise} Q promise that resolves to a Order {Object} or rejects with a {@link SilkRoadError} */ get: function() { - corbel.validate.value('id', this.id); + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id), method: corbel.request.method.GET - }); + }) }, /** @@ -6584,12 +6495,12 @@ * @return {Promise} Q promise that resolves to undefined (void) or rejects with a {@link SilkRoadError} */ update: function(order) { - corbel.validate.value('id', this.id); + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id), method: corbel.request.method.PUT, data: order - }); + }) }, /** @@ -6599,11 +6510,11 @@ * @return {Promise} Q promise that resolves to undefined (void) or rejects with a {@link SilkRoadError} */ delete: function() { - corbel.validate.value('id', this.id); + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id), method: corbel.request.method.DELETE - }); + }) }, /** @@ -6614,12 +6525,12 @@ * @return {Promise} Q promise that resolves to undefined (void) or rejects with a {@link SilkRoadError} */ prepare: function(couponIds) { - corbel.validate.value('id', this.id); + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id, '/prepare'), method: corbel.request.method.POST, data: couponIds - }); + }) }, /** @@ -6633,19 +6544,19 @@ */ checkout: function(data) { if (!data.paymentMethodIds) { - return Promise.reject(new Error('paymentMethodIds lists needed')); + return Promise.reject(new Error('paymentMethodIds lists needed')) } if (!data.paymentMethodIds.length) { - return Promise.reject(new Error('One payment method is needed at least')); + return Promise.reject(new Error('One payment method is needed at least')) } - corbel.validate.value('id', this.id); + corbel.validate.value('id', this.id) return this.request({ method: corbel.request.method.POST, url: this._buildUri(this.uri, this.id, '/checkout'), data: data }).then(function(res) { - return corbel.Services.getLocationId(res); - }); + return corbel.Services.getLocationId(res) + }) }, /** @@ -6656,13 +6567,13 @@ */ _buildUri: corbel.Ec._buildUri - }); - - })(); + }) + })() + /* global corbel */ + ; (function() { - /** * Create a ProductBuilder for product managing requests. * @@ -6671,25 +6582,24 @@ * @return {corbel.Ec.ProductBuilder} */ corbel.Ec.prototype.product = function(id) { - var product = new ProductBuilder(id); - product.driver = this.driver; - return product; - }; - /** - * A builder for products management requests. - * - * @param {String} id product ID. - * - * @class - * @memberOf corbel.Ec.ProductBuilder - */ + var product = new ProductBuilder(id) + product.driver = this.driver + return product + } + /** + * A builder for products management requests. + * + * @param {String} id product ID. + * + * @class + * @memberOf corbel.Ec.ProductBuilder + */ var ProductBuilder = corbel.Ec.ProductBuilder = corbel.Services.inherit({ - constructor: function(id) { if (id) { - this.id = id; + this.id = id } - this.uri = 'product'; + this.uri = 'product' }, /** @@ -6713,14 +6623,14 @@ * with a {@link corbelError}. */ create: function(product) { - console.log('ecInterface.product.create', product); + console.log('ecInterface.product.create', product) return this.request({ url: this._buildUri(this.uri), method: corbel.request.method.POST, data: product }).then(function(res) { - return corbel.Services.getLocationId(res); - }); + return corbel.Services.getLocationId(res) + }) }, /** @@ -6734,12 +6644,12 @@ * @return {Promise} A promise with product {Object} or fails with a {@link corbelError}. */ get: function(params) { - console.log('ecInterface.product.get'); + console.log('ecInterface.product.get') return this.request({ url: this._buildUri(this.uri, this.id), method: corbel.request.method.GET, query: params ? corbel.utils.serializeParams(params) : null - }); + }) }, /** @@ -6753,16 +6663,16 @@ * @return {Promise} A promise resolves to undefined (void) or fails with a {@link corbelError}. */ update: function(product) { - console.log('ecInterface.product.update'); - corbel.validate.value('id', this.id); + console.log('ecInterface.product.update') + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id), method: corbel.request.method.PUT, data: product - }); + }) }, - /**Delete a product. + /* Delete a product. * * @method * @memberOf corbel.Ec.EcBuilder @@ -6770,55 +6680,53 @@ * @return {Promise} A promise resolves to undefined (void) or fails with a {@link corbelError}. */ delete: function() { - console.log('ecInterface.product.delete'); - corbel.validate.value('id', this.id); + console.log('ecInterface.product.delete') + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id), method: corbel.request.method.DELETE - }); + }) }, _buildUri: corbel.Ec._buildUri - }); - - })(); + }) + })() + ; (function() { corbel.Evci = corbel.Object.inherit({ - /** * Create a new EventBuilder * @param {String} type String * @return {Events} */ constructor: function(driver) { - this.driver = driver; + this.driver = driver }, event: function(type) { - return new corbel.Evci.EventBuilder(type, this.driver); + return new corbel.Evci.EventBuilder(type, this.driver) } }, { - moduleName: 'evci', defaultPort: 8086, create: function(driver) { - return new corbel.Evci(driver); + return new corbel.Evci(driver) } - }); - - return corbel.Evci; + }) - })(); + return corbel.Evci + })() + /* global corbel */ + ; (function() { - var EventBuilder = corbel.Evci.EventBuilder = corbel.Services.inherit({ /** * Creates a new EventBuilder @@ -6826,9 +6734,9 @@ * @return {Events} */ constructor: function(type, driver) { - this.uri = 'event'; - this.eventType = type; - this.driver = driver; + this.uri = 'event' + this.eventType = type + this.driver = driver }, /** @@ -6844,51 +6752,51 @@ */ publish: function(eventData) { if (!eventData) { - throw new Error('Send event require data'); + throw new Error('Send event require data') } - console.log('evciInterface.publish', eventData); - corbel.validate.value('eventType', this.eventType); + console.log('evciInterface.publish', eventData) + corbel.validate.value('eventType', this.eventType) return this.request({ url: this._buildUri(this.uri, this.eventType), method: corbel.request.method.POST, data: eventData }).then(function(res) { - res.data = corbel.Services.getLocationId(res); - return res; - }); + res.data = corbel.Services.getLocationId(res) + return res + }) }, _buildUri: function(path, eventType) { - var uri = ''; - var urlBase = this.driver.config.getCurrentEndpoint(corbel.Evci.moduleName, this._buildPort(this.driver.config)); + var uri = '' + var urlBase = this.driver.config.getCurrentEndpoint(corbel.Evci.moduleName, this._buildPort(this.driver.config)) - uri = urlBase + path; + uri = urlBase + path if (eventType) { - uri += '/' + eventType; + uri += '/' + eventType } - return uri; + return uri }, _buildPort: function(config) { - return config.get('evciPort', null) || corbel.Evci.defaultPort; + return config.get('evciPort', null) || corbel.Evci.defaultPort } }, { - moduleName: 'evci', create: function(driver) { - return new corbel.EventBuilder(driver); + return new corbel.EventBuilder(driver) } - }); + }) - return EventBuilder; - })(); + return EventBuilder + })() + /* global corbel */ + ; (function() { - /** * A module to make Borrow requests. * @exports Borrow @@ -6897,13 +6805,10 @@ */ corbel.Borrow = corbel.Object.inherit({ - constructor: function(driver) { - this.driver = driver; + this.driver = driver }, - - /** * Create a BorrowBuilder for resource managing requests. * @@ -6912,9 +6817,9 @@ * @return {corbel.Borrow.BorrowBuilder} */ resource: function(id) { - var resource = new corbel.Borrow.BorrowBuilder(id); - resource.driver = this.driver; - return resource; + var resource = new corbel.Borrow.BorrowBuilder(id) + resource.driver = this.driver + return resource }, /** @@ -6925,9 +6830,9 @@ * @return {corbel.Borrow.LenderBuilder} */ lender: function(id) { - var lender = new corbel.Borrow.LenderBuilder(id); - lender.driver = this.driver; - return lender; + var lender = new corbel.Borrow.LenderBuilder(id) + lender.driver = this.driver + return lender }, /** @@ -6938,56 +6843,48 @@ * @return {corbel.Borrow.UserBuilder} */ user: function(id) { - var user = new corbel.Borrow.UserBuilder(id); - user.driver = this.driver; - return user; + var user = new corbel.Borrow.UserBuilder(id) + user.driver = this.driver + return user } - - - }, { moduleName: 'borrow', defaultPort: 8100, create: function(driver) { - return new corbel.Borrow(driver); + return new corbel.Borrow(driver) }, _buildUri: function() { - var uri = ''; + var uri = '' Array.prototype.slice.call(arguments).forEach(function(argument) { if (argument) { - uri += '/' + argument; + uri += '/' + argument } - }); + }) - var urlBase = this.driver.config.getCurrentEndpoint(corbel.Borrow.moduleName, corbel.Borrow._buildPort(this.driver.config)); + var urlBase = this.driver.config.getCurrentEndpoint(corbel.Borrow.moduleName, corbel.Borrow._buildPort(this.driver.config)) if (urlBase.slice(-1) === '/') { - urlBase = urlBase.substring(0, urlBase.length - 1); + urlBase = urlBase.substring(0, urlBase.length - 1) } - return urlBase + uri; + return urlBase + uri }, _buildPort: function(config) { - return config.get('borrowPort', null) || corbel.Borrow.defaultPort; + return config.get('borrowPort', null) || corbel.Borrow.defaultPort } - }); - - return corbel.Borrow; - + }) + return corbel.Borrow + })() + /* global corbel */ - - })(); - - + ; (function() { - - /** * A builder for borrowed management requests. * @@ -6997,10 +6894,9 @@ * @memberOf corbel.Borrow.BorrowBuilder */ corbel.Borrow.BorrowBuilder = corbel.Services.inherit({ - constructor: function(id) { - this.id = id; - this.uri = 'resource'; + this.id = id + this.uri = 'resource' }, /** * Adds the loanable resource. @@ -7023,14 +6919,14 @@ * with a {@link corbelError}. */ add: function(loanableResource) { - console.log('borrowInterface.resource.add', loanableResource); + console.log('borrowInterface.resource.add', loanableResource) return this.request({ url: this._buildUri(this.uri), method: corbel.request.method.POST, data: loanableResource }).then(function(res) { - return corbel.Services.getLocationId(res); - }); + return corbel.Services.getLocationId(res) + }) }, /** * Get a loanable resource. @@ -7041,12 +6937,12 @@ * @return {Promise} A promise with loanable resource {Object} or fails with a {@link corbelError}. */ get: function() { - console.log('borrowInterface.resource.get'); - corbel.validate.value('id', this.id); + console.log('borrowInterface.resource.get') + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id), method: corbel.request.method.GET - }); + }) }, /** * Delete a loanable resource. @@ -7057,41 +6953,41 @@ * @return {Promise} A promise resolves to undefined (void) or fails with a {@link corbelError}. */ delete: function() { - console.log('borrowInterface.resource.delete'); - corbel.validate.value('id', this.id); + console.log('borrowInterface.resource.delete') + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id), method: corbel.request.method.DELETE - }); - }, - /** - * Add license to loanable resource. - * - * @method - * @memberOf corbel.Borrow.BorrowBuilder - * - * @param {Object} data licenses data. - * @param {Object} license The license data. - * @param {String} license.resourceId Identifier of resource - * @param {number} licensee.availableUses Amount of uses that the resource is available - * @param {number} license.availableLoans Amount of concurrent loans are available for the resource - * @param {timestamp} license.expire Expire date - * @param {timestamp} licensee.start Start date - * @param {String} license.asset Asigned to the resource + }) + }, + /** + * Add license to loanable resource. + * + * @method + * @memberOf corbel.Borrow.BorrowBuilder + * + * @param {Object} data licenses data. + * @param {Object} license The license data. + * @param {String} license.resourceId Identifier of resource + * @param {number} licensee.availableUses Amount of uses that the resource is available + * @param {number} license.availableLoans Amount of concurrent loans are available for the resource + * @param {timestamp} license.expire Expire date + * @param {timestamp} licensee.start Start date + * @param {String} license.asset Asigned to the resource - * @return {Promise} A promise with the id of the created a license or fails - * with a {@link corbelError}. - */ + * @return {Promise} A promise with the id of the created a license or fails + * with a {@link corbelError}. + */ addLicense: function(license) { - console.log('borrowInterface.resource.addLicense', license); - corbel.validate.value('id', this.id); + console.log('borrowInterface.resource.addLicense', license) + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id, 'license'), method: corbel.request.method.POST, data: license }).then(function(res) { - return corbel.Services.getLocationId(res); - }); + return corbel.Services.getLocationId(res) + }) }, /** * Apply loan. @@ -7104,15 +7000,15 @@ * @return {Promise} A promise resolves to undefined (void) or fails with a {@link corbelError}. */ applyFor: function(userId) { - console.log('borrowInterface.resource.applyFor', userId); + console.log('borrowInterface.resource.applyFor', userId) corbel.validate.values(['id', 'userId'], { 'id': this.id, 'userId': userId - }); + }) return this.request({ url: this._buildUri(this.uri, this.id, 'loan/' + userId), method: corbel.request.method.PUT - }); + }) }, /** * Apply loan for user logged. @@ -7123,12 +7019,12 @@ * @return {Promise} A promise resolves to undefined (void) or fails with a {@link corbelError}. */ applyForMe: function() { - console.log('borrowInterface.resource.applyForMe'); - corbel.validate.value('id', this.id); + console.log('borrowInterface.resource.applyForMe') + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id, 'loan/me'), method: corbel.request.method.PUT - }); + }) }, /** * Get lent. @@ -7141,15 +7037,15 @@ * @return {Promise} A promise with user lents {Object} or fails with a {@link corbelError}. */ getLentOf: function(userId) { - console.log('borrowInterface.resource.getLentOf', userId); + console.log('borrowInterface.resource.getLentOf', userId) corbel.validate.values(['id', 'userId'], { 'id': this.id, 'userId': userId - }); + }) return this.request({ url: this._buildUri(this.uri, this.id, 'loan/' + userId), method: corbel.request.method.GET - }); + }) }, /** * Get lent of user logged. @@ -7159,12 +7055,12 @@ * @return {Promise} A promise with user logged lents {Object} or fails with a {@link corbelError}. */ getMyLent: function() { - console.log('borrowInterface.resource.getMyLent'); - corbel.validate.value('id', this.id); + console.log('borrowInterface.resource.getMyLent') + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id, 'loan/me'), method: corbel.request.method.GET - }); + }) }, /** * Return lent. @@ -7177,15 +7073,15 @@ * @return {Promise} A promise resolves to undefined (void) or fails with a {@link corbelError}. */ returnLoanOf: function(userId) { - console.log('borrowInterface.resource.returnLoanOf', userId); + console.log('borrowInterface.resource.returnLoanOf', userId) corbel.validate.values(['id', 'userId'], { 'id': this.id, 'userId': userId - }); + }) return this.request({ url: this._buildUri(this.uri, this.id, 'loan/' + userId), method: corbel.request.method.DELETE - }); + }) }, /** * Return loan of user logged. @@ -7196,12 +7092,12 @@ * @return {Promise} A promise resolves to undefined (void) or fails with a {@link corbelError}. */ returnMyLoan: function() { - console.log('borrowInterface.resource.returnMyLoan'); - corbel.validate.value('id', this.id); + console.log('borrowInterface.resource.returnMyLoan') + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id, 'loan/me'), method: corbel.request.method.DELETE - }); + }) }, /** * Renew loan. @@ -7214,15 +7110,15 @@ * @return {Promise} A promise resolves to undefined (void) or fails with a {@link corbelError}. */ renewFor: function(userId) { - console.log('borrowInterface.resource.renewFor', userId); + console.log('borrowInterface.resource.renewFor', userId) corbel.validate.values(['id', 'userId'], { 'id': this.id, 'userId': userId - }); + }) return this.request({ url: this._buildUri(this.uri, this.id, 'renewal/' + userId), method: corbel.request.method.PUT - }); + }) }, /** * Renew loan for user logged. @@ -7233,12 +7129,12 @@ * @return {Promise} A promise resolves to undefined (void) or fails with a {@link corbelError}. */ renewForMe: function() { - console.log('borrowInterface.resource.renewForMe'); - corbel.validate.value('id', this.id); + console.log('borrowInterface.resource.renewForMe') + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id, 'renewal/me'), method: corbel.request.method.PUT - }); + }) }, /** * Reserve a resource. @@ -7251,15 +7147,15 @@ * @return {Promise} A promise resolves to undefined (void) or fails with a {@link corbelError}. */ reserveFor: function(userId) { - console.log('borrowInterface.resource.reserveFor', userId); + console.log('borrowInterface.resource.reserveFor', userId) corbel.validate.values(['id', 'userId'], { 'id': this.id, 'userId': userId - }); + }) return this.request({ url: this._buildUri(this.uri, this.id, 'reservation/' + userId), method: corbel.request.method.PUT - }); + }) }, /** * Reserve a resource for user logged. @@ -7270,12 +7166,12 @@ * @return {Promise} A promise resolves to undefined (void) or fails with a {@link corbelError}. */ reserveForMe: function() { - console.log('borrowInterface.resource.reserveForMe'); - corbel.validate.value('id', this.id); + console.log('borrowInterface.resource.reserveForMe') + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id, 'reservation/me'), method: corbel.request.method.PUT - }); + }) }, /** * Cancel reservation. @@ -7288,15 +7184,15 @@ * @return {Promise} A promise resolves to undefined (void) or fails with a {@link corbelError}. */ cancelReservationFor: function(userId) { - console.log('borrowInterface.resource.cancelReservationFor', userId); + console.log('borrowInterface.resource.cancelReservationFor', userId) corbel.validate.values(['id', 'userId'], { 'id': this.id, 'userId': userId - }); + }) return this.request({ url: this._buildUri(this.uri, this.id, 'reservation/' + userId), method: corbel.request.method.DELETE - }); + }) }, /** * Cancel reservation for user logged. @@ -7307,12 +7203,12 @@ * @return {Promise} A promise resolves to undefined (void) or fails with a {@link corbelError}. */ cancelMyReservation: function() { - console.log('borrowInterface.resource.cancelMyReservation'); - corbel.validate.value('id', this.id); + console.log('borrowInterface.resource.cancelMyReservation') + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id, 'reservation/me'), method: corbel.request.method.DELETE - }); + }) }, /** * get the user borrowed history. @@ -7325,12 +7221,12 @@ * @return {Promise} A promise with user borowed {Object} history or fails with a {@link corbelError}. */ getHistoryOf: function(userId) { - console.log('borrowInterface.resource.getHistoryOf', userId); - corbel.validate.value('userId', userId); + console.log('borrowInterface.resource.getHistoryOf', userId) + corbel.validate.value('userId', userId) return this.request({ url: this._buildUri(this.uri, 'history/' + userId), method: corbel.request.method.GET - }); + }) }, /** * Get lent of user logged. @@ -7340,11 +7236,11 @@ * @return {Promise} A promise with user logged borrowed {Object} history or fails with a {@link corbelError}. */ getMyHistory: function() { - console.log('borrowInterface.resource.getMyHistory'); + console.log('borrowInterface.resource.getMyHistory') return this.request({ url: this._buildUri(this.uri, 'history/me'), method: corbel.request.method.GET - }); + }) }, /** * get full resources borrowed history. @@ -7355,22 +7251,22 @@ * @return {Promise} A promise with borowed full {Object} history or fails with a {@link corbelError}. */ getFullHistory: function(params) { - console.log('borrowInterface.resource.getFullHistory'); + console.log('borrowInterface.resource.getFullHistory') return this.request({ url: this._buildUri(this.uri, 'history/'), method: corbel.request.method.GET, query: params ? corbel.utils.serializeParams(params) : null - }); + }) }, _buildUri: corbel.Borrow._buildUri - }); - })(); + }) + })() + /* global corbel */ + ; (function() { - - /** * A builder for borrowed management requests. * @@ -7380,10 +7276,9 @@ * @memberOf corbel.Borrow.UserBuilder */ corbel.Borrow.UserBuilder = corbel.Services.inherit({ - constructor: function(id) { - this.id = id || 'me'; - this.uri = 'user'; + this.id = id || 'me' + this.uri = 'user' }, /** * Get all reservations of a user. @@ -7394,11 +7289,11 @@ * @return {Promise} A promise with all user reservations {Object} or fails with a {@link corbelError}. */ getAllReservations: function() { - console.log('borrowInterface.user.getAllReservations', this.id); + console.log('borrowInterface.user.getAllReservations', this.id) return this.request({ url: this._buildUri(this.uri, this.id, 'reservation'), method: corbel.request.method.GET - }); + }) }, /** * Get all loans of a user. @@ -7409,22 +7304,21 @@ * @return {Promise} A promise with all user loans {Object} or fails with a {@link corbelError}. */ getAllLoans: function() { - console.log('borrowInterface.user.getAllLoans', this.id); + console.log('borrowInterface.user.getAllLoans', this.id) return this.request({ url: this._buildUri(this.uri, this.id, 'loan'), method: corbel.request.method.GET - }); + }) }, - _buildUri: corbel.Borrow._buildUri - }); - })(); + }) + })() + /* global corbel */ + ; (function() { - - /** * A builder for borrowed management requests. * @@ -7434,10 +7328,9 @@ * @memberOf corbel.Borrow.LenderBuilder */ corbel.Borrow.LenderBuilder = corbel.Services.inherit({ - constructor: function(id) { - this.id = id; - this.uri = 'lender'; + this.id = id + this.uri = 'lender' }, /** * Create a new Lender @@ -7457,14 +7350,14 @@ * with a {@link corbelError}. */ create: function(lender) { - console.log('borrowInterface.lender.create', lender); + console.log('borrowInterface.lender.create', lender) return this.request({ url: this._buildUri(this.uri), method: corbel.request.method.POST, data: lender }).then(function(res) { - return corbel.Services.getLocationId(res); - }); + return corbel.Services.getLocationId(res) + }) }, /** * Update a Lender. @@ -7477,13 +7370,13 @@ * @return {Promise} A promise resolves to undefined (void) or fails with a {@link corbelError}. */ update: function(lender) { - console.log('borrowInterface.lender.update'); + console.log('borrowInterface.lender.update') return this.request({ url: this._buildUri(this.uri, this.id), method: corbel.request.method.PUT, data: lender - }); + }) }, /** * Delete a Lender. @@ -7494,12 +7387,12 @@ * @return {Promise} A promise resolves to undefined (void) or fails with a {@link corbelError}. */ delete: function() { - console.log('borrowInterface.lender.delete'); + console.log('borrowInterface.lender.delete') return this.request({ url: this._buildUri(this.uri, this.id), method: corbel.request.method.DELETE - }); + }) }, /** * Get Lender. @@ -7510,12 +7403,12 @@ * @return {Promise} A promise with lender {Object} or fails with a {@link corbelError}. */ get: function() { - console.log('borrowInterface.lender.get'); + console.log('borrowInterface.lender.get') return this.request({ url: this._buildUri(this.uri, this.id), method: corbel.request.method.GET - }); + }) }, /** * Get all Lenders. @@ -7526,12 +7419,12 @@ * @return {Promise} A promise with all lenders {Object} or fails with a {@link corbelError}. */ getAll: function(params) { - console.log('borrowInterface.lender.getAll'); + console.log('borrowInterface.lender.getAll') return this.request({ url: this._buildUri(this.uri, 'all'), method: corbel.request.method.GET, query: params ? corbel.utils.serializeParams(params) : null - }); + }) }, /** * Get all reservations by lender. @@ -7542,21 +7435,22 @@ * @return {Promise} A promise with all reservations {Object} by lender or fails with a {@link corbelError}. */ getAllReservations: function(params) { - console.log('borrowInterface.lender.getAllReservations'); + console.log('borrowInterface.lender.getAllReservations') return this.request({ url: this._buildUri(this.uri, 'reservation'), method: corbel.request.method.GET, query: params ? corbel.utils.serializeParams(params) : null - }); + }) }, _buildUri: corbel.Borrow._buildUri - }); - })(); + }) + })() + /* global corbel */ + ; (function() { - /** * A module to make CompoSR requests. * @exports CompoSR @@ -7565,9 +7459,8 @@ */ corbel.CompoSR = corbel.Object.inherit({ - constructor: function(driver) { - this.driver = driver; + this.driver = driver }, /** @@ -7578,9 +7471,9 @@ * @return {corbel.CompoSR.PhraseBuilder} */ phrase: function(id) { - var phraseBuilder = new corbel.CompoSR.PhraseBuilder(id); - phraseBuilder.driver = this.driver; - return phraseBuilder; + var phraseBuilder = new corbel.CompoSR.PhraseBuilder(id) + phraseBuilder.driver = this.driver + return phraseBuilder }, /** @@ -7594,51 +7487,48 @@ * @return {corbel.CompoSR.RequestBuilder} */ request: function() { - var requestBuilder = new corbel.CompoSR.RequestBuilder(Array.prototype.slice.call(arguments)); - requestBuilder.driver = this.driver; - return requestBuilder; + var requestBuilder = new corbel.CompoSR.RequestBuilder(Array.prototype.slice.call(arguments)) + requestBuilder.driver = this.driver + return requestBuilder } - }, { - moduleName: 'composr', defaultPort: 3000, create: function(driver) { - return new corbel.CompoSR(driver); + return new corbel.CompoSR(driver) }, _buildPort: function(config) { - return config.get('composrPort', null) || corbel.CompoSR.defaultPort; + return config.get('composrPort', null) || corbel.CompoSR.defaultPort }, _buildUri: function() { - var urlBase = this.driver.config.getCurrentEndpoint(corbel.CompoSR.moduleName, corbel.CompoSR._buildPort(this.driver.config)); + var urlBase = this.driver.config.getCurrentEndpoint(corbel.CompoSR.moduleName, corbel.CompoSR._buildPort(this.driver.config)) if (urlBase.slice(-1) === '/') { - urlBase = urlBase.substring(0, urlBase.length - 1); + urlBase = urlBase.substring(0, urlBase.length - 1) } - var uri = ''; + var uri = '' Array.prototype.slice.call(arguments).forEach(function(argument) { if (argument) { - uri += '/' + argument; + uri += '/' + argument } - }); - return urlBase + uri; + }) + return urlBase + uri } - }); - - return corbel.CompoSR; + }) - })(); + return corbel.CompoSR + })() + /* global corbel */ + ; (function() { - - /** * A builder for composr phrase crud. * @@ -7648,58 +7538,57 @@ * @memberOf corbel.CompoSR.PhraseBuilder */ corbel.CompoSR.PhraseBuilder = corbel.Services.inherit({ - constructor: function(id) { - this.id = id; + this.id = id }, put: function(body) { - console.log('composrInterface.phrase.add'); + console.log('composrInterface.phrase.add') return this.request({ url: this._buildUri('phrase', this.id), method: corbel.request.method.PUT, data: body - }); + }) }, get: function() { - console.log('composrInterface.phrase.get'); - corbel.validate.value('id', this.id); + console.log('composrInterface.phrase.get') + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri('phrase', this.id), method: corbel.request.method.GET - }); + }) }, getAll: function() { - console.log('composrInterface.phrase.getAll'); + console.log('composrInterface.phrase.getAll') return this.request({ url: this._buildUri('phrase'), method: corbel.request.method.GET - }); + }) }, delete: function() { - console.log('composrInterface.phrase.delete'); - corbel.validate.value('id', this.id); + console.log('composrInterface.phrase.delete') + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri('phrase', this.id), method: corbel.request.method.DELETE - }); + }) }, _buildUri: corbel.CompoSR._buildUri - }); - })(); + }) + })() + /* global corbel */ + ; (function() { - - /** * A builder for composr requests. * @@ -7708,86 +7597,87 @@ * @memberOf corbel.CompoSR.RequestBuilder */ corbel.CompoSR.RequestBuilder = corbel.Services.inherit({ - constructor: function(pathsArray) { - this.path = this.buildPath(pathsArray); + this.path = this.buildPath(pathsArray) }, post: function(data, options) { - console.log('composrInterface.request.post'); - this.options = options || {}; + console.log('composrInterface.request.post') + this.options = options || {} return this.request({ url: this._buildUri(this.path), method: corbel.request.method.POST, headers: this.options.headers, data: data, query: this.buildQueryPath(this.options.queryParams) - }); + }) }, get: function(options) { - console.log('composrInterface.request.get'); - this.options = options || {}; + console.log('composrInterface.request.get') + this.options = options || {} return this.request({ url: this._buildUri(this.path), method: corbel.request.method.GET, headers: this.options.headers, query: this.buildQueryPath(this.options.queryParams) - }); + }) }, put: function(data, options) { - console.log('composrInterface.request.put'); - this.options = options || {}; + console.log('composrInterface.request.put') + this.options = options || {} return this.request({ url: this._buildUri(this.path), method: corbel.request.method.PUT, data: data, headers: this.options.headers, query: this.buildQueryPath(this.options.queryParams) - }); + }) }, delete: function(options) { - console.log('composrInterface.request.delete'); - this.options = options || {}; + console.log('composrInterface.request.delete') + this.options = options || {} return this.request({ url: this._buildUri(this.path), method: corbel.request.method.DELETE, headers: this.options.headers, query: this.buildQueryPath(this.options.queryParams) - }); + }) }, buildPath: function(pathArray) { - var path = ''; - path += pathArray.shift(); + var path = '' + path += pathArray.shift() pathArray.forEach(function(entryPath) { - path += '/' + entryPath; - }); - return path; + path += '/' + entryPath + }) + return path }, buildQueryPath: function(dict) { - var query = ''; + var query = '' if (dict) { - var queries = []; + var queries = [] Object.keys(dict).forEach(function(key) { - queries.push(key + '=' + dict[key]); - }); + queries.push(key + '=' + dict[key]) + }) if (queries.length > 0) { - query = queries.join('&'); + query = queries.join('&') } } - return query; + return query }, _buildUri: corbel.CompoSR._buildUri - }); - })(); + }) + })() - (function() { + /*globals corbel */ + ; + (function() { /** * A webfs API factory * @exports corbel.Webfs @@ -7796,23 +7686,21 @@ * @memberof corbel */ corbel.Webfs = corbel.Object.inherit({ - - /** + /* * Creates a new WebfsBuilder * @memberof corbel.Webfs.prototype - * @param {string} id String with the resource id + * @param {string} id String with the resource id * @return {corbel.Webfs.WebfsBuilder} */ constructor: function(driver) { - this.driver = driver; + this.driver = driver }, webfs: function(id) { - return new corbel.Webfs.WebfsBuilder(this.driver, id); + return new corbel.Webfs.WebfsBuilder(this.driver, id) } }, { - /** * moduleName constant * @constant @@ -7838,18 +7726,18 @@ * @return {corbel.Webfs.WebfsBuilder} */ create: function(driver) { - return new corbel.Webfs(driver); + return new corbel.Webfs(driver) } - }); - - return corbel.Webfs; + }) - })(); + return corbel.Webfs + })() + /*globals corbel */ + ; (function() { - /** * Module for retrieve content of S3 * @exports WebfsBuilder @@ -7858,15 +7746,14 @@ * @memberof corbel.Webfs */ var WebfsBuilder = corbel.Webfs.WebfsBuilder = corbel.Services.inherit({ - /** * Creates a new WebfsBuilder * @memberof corbel.Webfs.WebfsBuilder.prototype * @return {corbel.Webfs.WebfsBuilder} */ constructor: function(driver, id) { - this.driver = driver; - this.id = id; + this.driver = driver + this.id = id }, /** @@ -7876,33 +7763,30 @@ * @return {Promise} Promise that resolves with a resource or rejects with a {@link CorbelError} */ get: function(params) { + corbel.validate.value('id', this.id) - corbel.validate.value('id', this.id); - - var options = params ? corbel.utils.clone(params) : {}; + var options = params ? corbel.utils.clone(params) : {} var args = corbel.utils.extend(options, { url: this._buildUri(this.id), method: corbel.request.method.GET, query: params ? corbel.utils.serializeParams(params) : null - }); - - return this.request(args); + }) + return this.request(args) }, _buildUri: function(id) { - var urlBase = this.driver.config.getCurrentEndpoint(corbel.Webfs.moduleName, this._buildPort(this.driver.config)); + var urlBase = this.driver.config.getCurrentEndpoint(corbel.Webfs.moduleName, this._buildPort(this.driver.config)) - return urlBase + id; + return urlBase + id }, _buildPort: function(config) { - return config.get('webfsPort', null) || corbel.Webfs.defaultPort; + return config.get('webfsPort', null) || corbel.Webfs.defaultPort } }, { - /** * GET constant * @constant @@ -7919,17 +7803,18 @@ * @default */ create: function(driver) { - return new corbel.Webfs.WebfsBuilder(driver); + return new corbel.Webfs.WebfsBuilder(driver) } - }); + }) - return WebfsBuilder; + return WebfsBuilder + })() - })(); + /* global corbel */ + ; (function() { - /** * A custom domain configuration * @exports corbel.Domain @@ -7938,7 +7823,6 @@ * @memberof corbel */ corbel.Domain = corbel.Object.inherit({ - /** * Creates a new instance of corbelDriver with a custom domain * @memberof corbel.Domain.prototype @@ -7946,18 +7830,16 @@ * @return {corbelDriver} */ constructor: function(driver) { - this.driver = driver; + this.driver = driver return function(id) { - driver.config.set(corbel.Domain.CUSTOM_DOMAIN, id); + driver.config.set(corbel.Domain.CUSTOM_DOMAIN, id) - return driver; - }; + return driver + } } - }, { - /** * moduleName constant * @constant @@ -7983,15 +7865,14 @@ * @return {function} */ create: function(driver) { - return new corbel.Domain(driver); + return new corbel.Domain(driver) } - }); - - return corbel.Domain; + }) - })(); + return corbel.Domain + })() - return corbel; -}); + return corbel +}) diff --git a/package.json b/package.json index 5d9c10a..0c3904b 100644 --- a/package.json +++ b/package.json @@ -91,6 +91,7 @@ "grunt-preprocess": "5.0.1", "grunt-release": "0.13.0", "grunt-requirejs": "0.4.2", + "grunt-standard": "^2.0.0", "grunt-usemin": "3.1.1", "grunt-version-check": "0.3.2", "i": "^0.3.4", diff --git a/src/assets/assets-builder.js b/src/assets/assets-builder.js index df02633..e2d8710 100644 --- a/src/assets/assets-builder.js +++ b/src/assets/assets-builder.js @@ -1,9 +1,9 @@ -//@exclude -'use strict'; -//@endexclude - -(function() { +// @exclude +'use strict' +// @endexclude +/* global corbel */ +;(function () { /** * Module for organize user assets * @exports AssetsBuilder @@ -12,17 +12,16 @@ * @memberof corbel.Assets */ var AssetsBuilder = corbel.Assets.AssetsBuilder = corbel.Services.inherit({ - /** * Creates a new AssetsBuilder * @memberof corbel.Assets.AssetsBuilder.prototype * @param {string} id string with the asset id or `all` key * @return {corbel.Assets.AssetsBuilder} */ - constructor: function(driver, id) { - this.driver = driver; - this.uri = 'asset'; - this.id = id; + constructor: function (driver, id) { + this.driver = driver + this.uri = 'asset' + this.id = id }, /** @@ -31,35 +30,33 @@ * @param {object} [params] Params of a {@link corbel.request} * @return {Promise} Promise that resolves with an Asset or rejects with a {@link CorbelError} */ - get: function(params) { - - var options = params ? corbel.utils.clone(params) : {}; + get: function (params) { + var options = params ? corbel.utils.clone(params) : {} var args = corbel.utils.extend(options, { url: this._buildUri(this.uri, this.id), method: corbel.request.method.GET, query: params ? corbel.utils.serializeParams(params) : null - }); - - return this.request(args); + }) + return this.request(args) }, - /** - * Gets all assets - * @memberof corbel.Assets.AssetsBuilder.prototype - * @param {object} [params] Params of a {@link corbel.request} - * @return {Promise} Promise that resolves with an Asset or rejects with a {@link CorbelError} - */ - getAll: function(params){ - var options = params ? corbel.utils.clone(params) : {}; + /** + * Gets all assets + * @memberof corbel.Assets.AssetsBuilder.prototype + * @param {object} [params] Params of a {@link corbel.request} + * @return {Promise} Promise that resolves with an Asset or rejects with a {@link CorbelError} + */ + getAll: function (params) { + var options = params ? corbel.utils.clone(params) : {} var args = corbel.utils.extend(options, { url: this._buildUri(this.uri, 'all'), method: corbel.request.method.GET, query: params ? corbel.utils.serializeParams(params) : null - }); - return this.request(args); + }) + return this.request(args) }, /** @@ -67,12 +64,12 @@ * @memberof corbel.Assets.AssetsBuilder.prototype * @return {Promise} Promise that resolves to undefined (void) or rejects with a {@link CorbelError} */ - delete: function() { - corbel.validate.value('id', this.id); + delete: function () { + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id), method: corbel.request.method.DELETE - }); + }) }, /** @@ -86,15 +83,14 @@ * @param {array} data.scopes Scopes of the asset * @return {Promise} Promise that resolves in the new asset id or rejects with a {@link CorbelError} */ - create: function(data) { + create: function (data) { return this.request({ url: this._buildUri(this.uri), method: corbel.request.method.POST, data: data - }). - then(function(res) { - return corbel.Services.getLocationId(res); - }); + }).then(function (res) { + return corbel.Services.getLocationId(res) + }) }, /** @@ -102,43 +98,41 @@ * @memberof corbel.Assets.AssetsBuilder.prototype * @return {Promise} Promise that resolves to a redirection to iam/oauth/token/upgrade or rejects with a {@link CorbelError} */ - access: function(params) { - var args = params ? corbel.utils.clone(params) : {}; - args.url = this._buildUri(this.uri + '/access'); - args.method = corbel.request.method.GET; - args.noRedirect = true; + access: function (params) { + var args = params ? corbel.utils.clone(params) : {} + args.url = this._buildUri(this.uri + '/access') + args.method = corbel.request.method.GET + args.noRedirect = true - var that = this; + var that = this - return this.request(args). - then(function(response) { + return this.request(args).then(function (response) { return that.request({ noRetry: args.noRetry, method: corbel.request.method.POST, contentType: 'application/x-www-form-urlencoded; charset=UTF-8', - data:response.data, + data: response.data, url: response.headers.location - }); - }); + }) + }) }, - _buildUri: function(path, id) { - var uri = ''; - var urlBase = this.driver.config.getCurrentEndpoint(corbel.Assets.moduleName, this._buildPort(this.driver.config)); + _buildUri: function (path, id) { + var uri = '' + var urlBase = this.driver.config.getCurrentEndpoint(corbel.Assets.moduleName, this._buildPort(this.driver.config)) - uri = urlBase + path; + uri = urlBase + path if (id) { - uri += '/' + id; + uri += '/' + id } - return uri; + return uri }, - _buildPort: function(config) { - return config.get('assetsPort', null) || corbel.Assets.defaultPort; + _buildPort: function (config) { + return config.get('assetsPort', null) || corbel.Assets.defaultPort } }, { - /** * GET constant * @constant @@ -154,12 +148,11 @@ * @type {string} * @default */ - create: function(driver) { - return new corbel.Assets.AssetsBuilder(driver); + create: function (driver) { + return new corbel.Assets.AssetsBuilder(driver) } - }); - - return AssetsBuilder; + }) -})(); + return AssetsBuilder +})() diff --git a/src/assets/assets.js b/src/assets/assets.js index 7e12d0d..a4721b3 100644 --- a/src/assets/assets.js +++ b/src/assets/assets.js @@ -1,8 +1,9 @@ -(function() { - //@exclude - 'use strict'; - //@endexclude +// @exclude +'use strict' +// @endexclude +/* global corbel */ +;(function () { /** * An assets API factory * @exports corbel.Assets @@ -11,23 +12,21 @@ * @memberof corbel */ corbel.Assets = corbel.Object.inherit({ - /** * Creates a new AssetsBuilder * @memberof corbel.Assets.prototype * @param {string} id String with the asset id or `all` key * @return {corbel.Assets.AssetsBuilder} */ - constructor: function(driver) { - this.driver = driver; + constructor: function (driver) { + this.driver = driver }, - asset: function(id) { - return new corbel.Assets.AssetsBuilder(this.driver, id); + asset: function (id) { + return new corbel.Assets.AssetsBuilder(this.driver, id) } }, { - /** * moduleName constant * @constant @@ -52,12 +51,11 @@ * @param {corbel} corbel instance driver * @return {corbel.Assets.AssetsBuilder} */ - create: function(driver) { - return new corbel.Assets(driver); + create: function (driver) { + return new corbel.Assets(driver) } - }); - - return corbel.Assets; + }) -})(); + return corbel.Assets +})() diff --git a/src/borrow/borrow.js b/src/borrow/borrow.js index 2c28bda..05f0ffa 100644 --- a/src/borrow/borrow.js +++ b/src/borrow/borrow.js @@ -1,9 +1,9 @@ -//@exclude -'use strict'; -//@endexclude - -(function() { +// @exclude +'use strict' +// @endexclude +/* global corbel */ +;(function () { /** * A module to make Borrow requests. * @exports Borrow @@ -12,13 +12,10 @@ */ corbel.Borrow = corbel.Object.inherit({ - - constructor: function(driver) { - this.driver = driver; + constructor: function (driver) { + this.driver = driver }, - - /** * Create a BorrowBuilder for resource managing requests. * @@ -26,10 +23,10 @@ * * @return {corbel.Borrow.BorrowBuilder} */ - resource : function(id) { - var resource = new corbel.Borrow.BorrowBuilder(id); - resource.driver = this.driver; - return resource; + resource: function (id) { + var resource = new corbel.Borrow.BorrowBuilder(id) + resource.driver = this.driver + return resource }, /** @@ -39,10 +36,10 @@ * * @return {corbel.Borrow.LenderBuilder} */ - lender: function(id) { - var lender = new corbel.Borrow.LenderBuilder(id); - lender.driver = this.driver; - return lender; + lender: function (id) { + var lender = new corbel.Borrow.LenderBuilder(id) + lender.driver = this.driver + return lender }, /** @@ -52,49 +49,41 @@ * * @return {corbel.Borrow.UserBuilder} */ - user: function(id) { - var user = new corbel.Borrow.UserBuilder(id); - user.driver = this.driver; - return user; - } - - - + user: function (id) { + var user = new corbel.Borrow.UserBuilder(id) + user.driver = this.driver + return user + } }, { moduleName: 'borrow', defaultPort: 8100, - create: function(driver) { - return new corbel.Borrow(driver); + create: function (driver) { + return new corbel.Borrow(driver) }, - _buildUri: function() { - var uri=''; - Array.prototype.slice.call(arguments).forEach(function(argument) { - if (argument){ - uri+= '/' + argument; - } - }); + _buildUri: function () { + var uri = '' + Array.prototype.slice.call(arguments).forEach(function (argument) { + if (argument) { + uri += '/' + argument + } + }) - var urlBase = this.driver.config.getCurrentEndpoint(corbel.Borrow.moduleName, corbel.Borrow._buildPort(this.driver.config)); + var urlBase = this.driver.config.getCurrentEndpoint(corbel.Borrow.moduleName, corbel.Borrow._buildPort(this.driver.config)) - if (urlBase.slice(-1) === '/') { - urlBase = urlBase.substring(0, urlBase.length - 1); - } + if (urlBase.slice(-1) === '/') { + urlBase = urlBase.substring(0, urlBase.length - 1) + } - return urlBase + uri; + return urlBase + uri }, - _buildPort: function(config) { - return config.get('borrowPort', null) || corbel.Borrow.defaultPort; + _buildPort: function (config) { + return config.get('borrowPort', null) || corbel.Borrow.defaultPort } - }); - - return corbel.Borrow; - - - - + }) -})(); + return corbel.Borrow +})() diff --git a/src/borrow/borrowBuilder.js b/src/borrow/borrowBuilder.js index 4a0d511..1b1ce9c 100644 --- a/src/borrow/borrowBuilder.js +++ b/src/borrow/borrowBuilder.js @@ -1,385 +1,383 @@ -//@exclude -'use strict'; -//@endexclude - -(function() { - +// @exclude +'use strict' +// @endexclude +/* global corbel */ +;(function () { + /** + * A builder for borrowed management requests. + * + * @param {String} id resource ID. + * + * @class + * @memberOf corbel.Borrow.BorrowBuilder + */ + corbel.Borrow.BorrowBuilder = corbel.Services.inherit({ + constructor: function (id) { + this.id = id + this.uri = 'resource' + }, /** - * A builder for borrowed management requests. + * Adds the loanable resource. + * + * @method + * @memberOf corbel.Borrow.BorrowBuilder + * + * @param {Object} loanable resource The loanable resource data. + * @param {String} loanableResource.resourceId Identifier of resource + * @param {Object[]} loanableResource.licenses Licenses list + * @param {number} loanableResource.licenses[].availableUses Amount of uses that the resource is available + * @param {number} loanableResource.licenses[].availableLoans Amount of concurrent loans are available for the resource + * @param {timestamp}loanableResource.licenses[].expire Expire date + * @param {timestamp}loanableResource.licenses[].start Start date + * @param {Object} loanableResource.asset Asigned to the resource + * @param {String[]} loanableResource.asset.scopes Scope list + * @param {String} loanableResource.asset.name Asset name * - * @param {String} id resource ID. + * @return {Promise} A promise with the id of the created loanable resources or fails + * with a {@link corbelError}. + */ + add: function (loanableResource) { + console.log('borrowInterface.resource.add', loanableResource) + return this.request({ + url: this._buildUri(this.uri), + method: corbel.request.method.POST, + data: loanableResource + }).then(function (res) { + return corbel.Services.getLocationId(res) + }) + }, + /** + * Get a loanable resource. * - * @class + * @method * @memberOf corbel.Borrow.BorrowBuilder + * + * @return {Promise} A promise with loanable resource {Object} or fails with a {@link corbelError}. */ - corbel.Borrow.BorrowBuilder = corbel.Services.inherit({ - - constructor: function(id) { - this.id = id; - this.uri = 'resource'; - }, - /** - * Adds the loanable resource. - * - * @method - * @memberOf corbel.Borrow.BorrowBuilder - * - * @param {Object} loanable resource The loanable resource data. - * @param {String} loanableResource.resourceId Identifier of resource - * @param {Object[]} loanableResource.licenses Licenses list - * @param {number} loanableResource.licenses[].availableUses Amount of uses that the resource is available - * @param {number} loanableResource.licenses[].availableLoans Amount of concurrent loans are available for the resource - * @param {timestamp}loanableResource.licenses[].expire Expire date - * @param {timestamp}loanableResource.licenses[].start Start date - * @param {Object} loanableResource.asset Asigned to the resource - * @param {String[]} loanableResource.asset.scopes Scope list - * @param {String} loanableResource.asset.name Asset name - * - * @return {Promise} A promise with the id of the created loanable resources or fails - * with a {@link corbelError}. - */ - add: function(loanableResource) { - console.log('borrowInterface.resource.add', loanableResource); - return this.request({ - url: this._buildUri(this.uri), - method: corbel.request.method.POST, - data: loanableResource - }).then(function(res) { - return corbel.Services.getLocationId(res); - }); - }, - /** - * Get a loanable resource. - * - * @method - * @memberOf corbel.Borrow.BorrowBuilder - * - * @return {Promise} A promise with loanable resource {Object} or fails with a {@link corbelError}. - */ - get: function() { - console.log('borrowInterface.resource.get'); - corbel.validate.value('id', this.id); - return this.request({ - url: this._buildUri(this.uri ,this.id), - method: corbel.request.method.GET - }); - }, - /** - * Delete a loanable resource. - * - * @method - * @memberOf corbel.Borrow.BorrowBuilder - * - * @return {Promise} A promise resolves to undefined (void) or fails with a {@link corbelError}. - */ - delete: function() { - console.log('borrowInterface.resource.delete'); - corbel.validate.value('id', this.id); - return this.request({ - url: this._buildUri(this.uri, this.id), - method: corbel.request.method.DELETE - }); - }, - /** - * Add license to loanable resource. - * - * @method - * @memberOf corbel.Borrow.BorrowBuilder - * - * @param {Object} data licenses data. - * @param {Object} license The license data. - * @param {String} license.resourceId Identifier of resource - * @param {number} licensee.availableUses Amount of uses that the resource is available - * @param {number} license.availableLoans Amount of concurrent loans are available for the resource - * @param {timestamp} license.expire Expire date - * @param {timestamp} licensee.start Start date - * @param {String} license.asset Asigned to the resource + get: function () { + console.log('borrowInterface.resource.get') + corbel.validate.value('id', this.id) + return this.request({ + url: this._buildUri(this.uri, this.id), + method: corbel.request.method.GET + }) + }, + /** + * Delete a loanable resource. + * + * @method + * @memberOf corbel.Borrow.BorrowBuilder + * + * @return {Promise} A promise resolves to undefined (void) or fails with a {@link corbelError}. + */ + delete: function () { + console.log('borrowInterface.resource.delete') + corbel.validate.value('id', this.id) + return this.request({ + url: this._buildUri(this.uri, this.id), + method: corbel.request.method.DELETE + }) + }, + /** + * Add license to loanable resource. + * + * @method + * @memberOf corbel.Borrow.BorrowBuilder + * + * @param {Object} data licenses data. + * @param {Object} license The license data. + * @param {String} license.resourceId Identifier of resource + * @param {number} licensee.availableUses Amount of uses that the resource is available + * @param {number} license.availableLoans Amount of concurrent loans are available for the resource + * @param {timestamp} license.expire Expire date + * @param {timestamp} licensee.start Start date + * @param {String} license.asset Asigned to the resource - * @return {Promise} A promise with the id of the created a license or fails - * with a {@link corbelError}. - */ - addLicense: function(license) { - console.log('borrowInterface.resource.addLicense', license); - corbel.validate.value('id', this.id); - return this.request({ - url: this._buildUri(this.uri, this.id, 'license'), - method: corbel.request.method.POST, - data: license - }).then(function(res) { - return corbel.Services.getLocationId(res); - }); - }, - /** - * Apply loan. - * - * @method - * @memberOf corbel.Borrow.BorrowBuilder - * - * @param {String} userId user id. - * - * @return {Promise} A promise resolves to undefined (void) or fails with a {@link corbelError}. - */ - applyFor: function(userId) { - console.log('borrowInterface.resource.applyFor', userId); - corbel.validate.values(['id', 'userId'], { - 'id': this.id, - 'userId': userId - }); - return this.request({ - url: this._buildUri(this.uri, this.id, 'loan/' + userId), - method: corbel.request.method.PUT - }); - }, - /** - * Apply loan for user logged. - * - * @method - * @memberOf corbel.Borrow.BorrowBuilder - * - * @return {Promise} A promise resolves to undefined (void) or fails with a {@link corbelError}. - */ - applyForMe: function() { - console.log('borrowInterface.resource.applyForMe'); - corbel.validate.value('id', this.id); - return this.request({ - url: this._buildUri(this.uri, this.id, 'loan/me'), - method: corbel.request.method.PUT - }); - }, - /** - * Get lent. - * - * @method - * @memberOf corbel.Borrow.BorrowBuilder - * - * @param {String} userId user id. - * - * @return {Promise} A promise with user lents {Object} or fails with a {@link corbelError}. - */ - getLentOf: function(userId) { - console.log('borrowInterface.resource.getLentOf', userId); - corbel.validate.values(['id', 'userId'], { - 'id': this.id, - 'userId': userId - }); - return this.request({ - url: this._buildUri(this.uri, this.id, 'loan/' + userId), - method: corbel.request.method.GET - }); - }, - /** - * Get lent of user logged. - * - * @method - * @memberOf corbel.Borrow.BorrowBuilder - * @return {Promise} A promise with user logged lents {Object} or fails with a {@link corbelError}. - */ - getMyLent: function() { - console.log('borrowInterface.resource.getMyLent'); - corbel.validate.value('id', this.id); - return this.request({ - url: this._buildUri(this.uri, this.id, 'loan/me'), - method: corbel.request.method.GET - }); - }, - /** - * Return lent. - * - * @method - * @memberOf corbel.Borrow.BorrowBuilder - * - * @param {String} userId user id. - * - * @return {Promise} A promise resolves to undefined (void) or fails with a {@link corbelError}. - */ - returnLoanOf: function(userId) { - console.log('borrowInterface.resource.returnLoanOf', userId); - corbel.validate.values(['id', 'userId'], { - 'id': this.id, - 'userId': userId - }); - return this.request({ - url: this._buildUri(this.uri, this.id, 'loan/' + userId), - method: corbel.request.method.DELETE - }); - }, - /** - * Return loan of user logged. - * - * @method - * @memberOf corbel.Borrow.BorrowBuilder - * - * @return {Promise} A promise resolves to undefined (void) or fails with a {@link corbelError}. - */ - returnMyLoan: function() { - console.log('borrowInterface.resource.returnMyLoan'); - corbel.validate.value('id', this.id); - return this.request({ - url: this._buildUri(this.uri, this.id, 'loan/me'), - method: corbel.request.method.DELETE - }); - }, - /** - * Renew loan. - * - * @method - * @memberOf corbel.Borrow.BorrowBuilder - * - * @param {String} userId The userId - * - * @return {Promise} A promise resolves to undefined (void) or fails with a {@link corbelError}. - */ - renewFor: function(userId) { - console.log('borrowInterface.resource.renewFor', userId); - corbel.validate.values(['id', 'userId'], { - 'id': this.id, - 'userId': userId - }); - return this.request({ - url: this._buildUri(this.uri, this.id, 'renewal/' + userId), - method: corbel.request.method.PUT - }); - }, - /** - * Renew loan for user logged. - * - * @method - * @memberOf corbel.Borrow.BorrowBuilder - * - * @return {Promise} A promise resolves to undefined (void) or fails with a {@link corbelError}. - */ - renewForMe: function() { - console.log('borrowInterface.resource.renewForMe'); - corbel.validate.value('id', this.id); - return this.request({ - url: this._buildUri(this.uri, this.id, 'renewal/me'), - method: corbel.request.method.PUT - }); - }, - /** - * Reserve a resource. - * - * @method - * @memberOf corbel.Borrow.BorrowBuilder - * - * @param {String} userId The userId - * - * @return {Promise} A promise resolves to undefined (void) or fails with a {@link corbelError}. - */ - reserveFor: function(userId) { - console.log('borrowInterface.resource.reserveFor', userId); - corbel.validate.values(['id', 'userId'], { - 'id': this.id, - 'userId': userId - }); - return this.request({ - url: this._buildUri(this.uri, this.id, 'reservation/' + userId), - method: corbel.request.method.PUT - }); - }, - /** - * Reserve a resource for user logged. - * - * @method - * @memberOf corbel.Borrow.BorrowBuilder - * - * @return {Promise} A promise resolves to undefined (void) or fails with a {@link corbelError}. - */ - reserveForMe: function() { - console.log('borrowInterface.resource.reserveForMe'); - corbel.validate.value('id', this.id); - return this.request({ - url: this._buildUri(this.uri, this.id, 'reservation/me'), - method: corbel.request.method.PUT - }); - }, - /** - * Cancel reservation. - * - * @method - * @memberOf corbel.Borrow.BorrowBuilder - * - * @param {String} userId user id. - * - * @return {Promise} A promise resolves to undefined (void) or fails with a {@link corbelError}. - */ - cancelReservationFor: function(userId) { - console.log('borrowInterface.resource.cancelReservationFor', userId); - corbel.validate.values(['id', 'userId'], { - 'id': this.id, - 'userId': userId - }); - return this.request({ - url: this._buildUri(this.uri, this.id, 'reservation/' + userId), - method: corbel.request.method.DELETE - }); - }, - /** - * Cancel reservation for user logged. - * - * @method - * @memberOf corbel.Borrow.BorrowBuilder - * - * @return {Promise} A promise resolves to undefined (void) or fails with a {@link corbelError}. - */ - cancelMyReservation: function() { - console.log('borrowInterface.resource.cancelMyReservation'); - corbel.validate.value('id', this.id); - return this.request({ - url: this._buildUri(this.uri, this.id, 'reservation/me'), - method: corbel.request.method.DELETE - }); - }, - /** - * get the user borrowed history. - * - * @method - * @memberOf corbel.Borrow.BorrowBuilder - * - * @param {String} userId user id. - * - * @return {Promise} A promise with user borowed {Object} history or fails with a {@link corbelError}. - */ - getHistoryOf: function(userId) { - console.log('borrowInterface.resource.getHistoryOf', userId); - corbel.validate.value('userId', userId); - return this.request({ - url: this._buildUri(this.uri, 'history/' + userId), - method: corbel.request.method.GET - }); - }, - /** - * Get lent of user logged. - * - * @method - * @memberOf corbel.Borrow.BorrowBuilder - * @return {Promise} A promise with user logged borrowed {Object} history or fails with a {@link corbelError}. - */ - getMyHistory: function() { - console.log('borrowInterface.resource.getMyHistory'); - return this.request({ - url: this._buildUri(this.uri, 'history/me'), - method: corbel.request.method.GET - }); - }, - /** - * get full resources borrowed history. - * - * @method - * @memberOf corbel.Borrow.BorrowBuilder - * - * @return {Promise} A promise with borowed full {Object} history or fails with a {@link corbelError}. - */ - getFullHistory: function(params) { - console.log('borrowInterface.resource.getFullHistory'); - return this.request({ - url: this._buildUri(this.uri, 'history/'), - method: corbel.request.method.GET, - query: params ? corbel.utils.serializeParams(params) : null - }); - }, + * @return {Promise} A promise with the id of the created a license or fails + * with a {@link corbelError}. + */ + addLicense: function (license) { + console.log('borrowInterface.resource.addLicense', license) + corbel.validate.value('id', this.id) + return this.request({ + url: this._buildUri(this.uri, this.id, 'license'), + method: corbel.request.method.POST, + data: license + }).then(function (res) { + return corbel.Services.getLocationId(res) + }) + }, + /** + * Apply loan. + * + * @method + * @memberOf corbel.Borrow.BorrowBuilder + * + * @param {String} userId user id. + * + * @return {Promise} A promise resolves to undefined (void) or fails with a {@link corbelError}. + */ + applyFor: function (userId) { + console.log('borrowInterface.resource.applyFor', userId) + corbel.validate.values(['id', 'userId'], { + 'id': this.id, + 'userId': userId + }) + return this.request({ + url: this._buildUri(this.uri, this.id, 'loan/' + userId), + method: corbel.request.method.PUT + }) + }, + /** + * Apply loan for user logged. + * + * @method + * @memberOf corbel.Borrow.BorrowBuilder + * + * @return {Promise} A promise resolves to undefined (void) or fails with a {@link corbelError}. + */ + applyForMe: function () { + console.log('borrowInterface.resource.applyForMe') + corbel.validate.value('id', this.id) + return this.request({ + url: this._buildUri(this.uri, this.id, 'loan/me'), + method: corbel.request.method.PUT + }) + }, + /** + * Get lent. + * + * @method + * @memberOf corbel.Borrow.BorrowBuilder + * + * @param {String} userId user id. + * + * @return {Promise} A promise with user lents {Object} or fails with a {@link corbelError}. + */ + getLentOf: function (userId) { + console.log('borrowInterface.resource.getLentOf', userId) + corbel.validate.values(['id', 'userId'], { + 'id': this.id, + 'userId': userId + }) + return this.request({ + url: this._buildUri(this.uri, this.id, 'loan/' + userId), + method: corbel.request.method.GET + }) + }, + /** + * Get lent of user logged. + * + * @method + * @memberOf corbel.Borrow.BorrowBuilder + * @return {Promise} A promise with user logged lents {Object} or fails with a {@link corbelError}. + */ + getMyLent: function () { + console.log('borrowInterface.resource.getMyLent') + corbel.validate.value('id', this.id) + return this.request({ + url: this._buildUri(this.uri, this.id, 'loan/me'), + method: corbel.request.method.GET + }) + }, + /** + * Return lent. + * + * @method + * @memberOf corbel.Borrow.BorrowBuilder + * + * @param {String} userId user id. + * + * @return {Promise} A promise resolves to undefined (void) or fails with a {@link corbelError}. + */ + returnLoanOf: function (userId) { + console.log('borrowInterface.resource.returnLoanOf', userId) + corbel.validate.values(['id', 'userId'], { + 'id': this.id, + 'userId': userId + }) + return this.request({ + url: this._buildUri(this.uri, this.id, 'loan/' + userId), + method: corbel.request.method.DELETE + }) + }, + /** + * Return loan of user logged. + * + * @method + * @memberOf corbel.Borrow.BorrowBuilder + * + * @return {Promise} A promise resolves to undefined (void) or fails with a {@link corbelError}. + */ + returnMyLoan: function () { + console.log('borrowInterface.resource.returnMyLoan') + corbel.validate.value('id', this.id) + return this.request({ + url: this._buildUri(this.uri, this.id, 'loan/me'), + method: corbel.request.method.DELETE + }) + }, + /** + * Renew loan. + * + * @method + * @memberOf corbel.Borrow.BorrowBuilder + * + * @param {String} userId The userId + * + * @return {Promise} A promise resolves to undefined (void) or fails with a {@link corbelError}. + */ + renewFor: function (userId) { + console.log('borrowInterface.resource.renewFor', userId) + corbel.validate.values(['id', 'userId'], { + 'id': this.id, + 'userId': userId + }) + return this.request({ + url: this._buildUri(this.uri, this.id, 'renewal/' + userId), + method: corbel.request.method.PUT + }) + }, + /** + * Renew loan for user logged. + * + * @method + * @memberOf corbel.Borrow.BorrowBuilder + * + * @return {Promise} A promise resolves to undefined (void) or fails with a {@link corbelError}. + */ + renewForMe: function () { + console.log('borrowInterface.resource.renewForMe') + corbel.validate.value('id', this.id) + return this.request({ + url: this._buildUri(this.uri, this.id, 'renewal/me'), + method: corbel.request.method.PUT + }) + }, + /** + * Reserve a resource. + * + * @method + * @memberOf corbel.Borrow.BorrowBuilder + * + * @param {String} userId The userId + * + * @return {Promise} A promise resolves to undefined (void) or fails with a {@link corbelError}. + */ + reserveFor: function (userId) { + console.log('borrowInterface.resource.reserveFor', userId) + corbel.validate.values(['id', 'userId'], { + 'id': this.id, + 'userId': userId + }) + return this.request({ + url: this._buildUri(this.uri, this.id, 'reservation/' + userId), + method: corbel.request.method.PUT + }) + }, + /** + * Reserve a resource for user logged. + * + * @method + * @memberOf corbel.Borrow.BorrowBuilder + * + * @return {Promise} A promise resolves to undefined (void) or fails with a {@link corbelError}. + */ + reserveForMe: function () { + console.log('borrowInterface.resource.reserveForMe') + corbel.validate.value('id', this.id) + return this.request({ + url: this._buildUri(this.uri, this.id, 'reservation/me'), + method: corbel.request.method.PUT + }) + }, + /** + * Cancel reservation. + * + * @method + * @memberOf corbel.Borrow.BorrowBuilder + * + * @param {String} userId user id. + * + * @return {Promise} A promise resolves to undefined (void) or fails with a {@link corbelError}. + */ + cancelReservationFor: function (userId) { + console.log('borrowInterface.resource.cancelReservationFor', userId) + corbel.validate.values(['id', 'userId'], { + 'id': this.id, + 'userId': userId + }) + return this.request({ + url: this._buildUri(this.uri, this.id, 'reservation/' + userId), + method: corbel.request.method.DELETE + }) + }, + /** + * Cancel reservation for user logged. + * + * @method + * @memberOf corbel.Borrow.BorrowBuilder + * + * @return {Promise} A promise resolves to undefined (void) or fails with a {@link corbelError}. + */ + cancelMyReservation: function () { + console.log('borrowInterface.resource.cancelMyReservation') + corbel.validate.value('id', this.id) + return this.request({ + url: this._buildUri(this.uri, this.id, 'reservation/me'), + method: corbel.request.method.DELETE + }) + }, + /** + * get the user borrowed history. + * + * @method + * @memberOf corbel.Borrow.BorrowBuilder + * + * @param {String} userId user id. + * + * @return {Promise} A promise with user borowed {Object} history or fails with a {@link corbelError}. + */ + getHistoryOf: function (userId) { + console.log('borrowInterface.resource.getHistoryOf', userId) + corbel.validate.value('userId', userId) + return this.request({ + url: this._buildUri(this.uri, 'history/' + userId), + method: corbel.request.method.GET + }) + }, + /** + * Get lent of user logged. + * + * @method + * @memberOf corbel.Borrow.BorrowBuilder + * @return {Promise} A promise with user logged borrowed {Object} history or fails with a {@link corbelError}. + */ + getMyHistory: function () { + console.log('borrowInterface.resource.getMyHistory') + return this.request({ + url: this._buildUri(this.uri, 'history/me'), + method: corbel.request.method.GET + }) + }, + /** + * get full resources borrowed history. + * + * @method + * @memberOf corbel.Borrow.BorrowBuilder + * + * @return {Promise} A promise with borowed full {Object} history or fails with a {@link corbelError}. + */ + getFullHistory: function (params) { + console.log('borrowInterface.resource.getFullHistory') + return this.request({ + url: this._buildUri(this.uri, 'history/'), + method: corbel.request.method.GET, + query: params ? corbel.utils.serializeParams(params) : null + }) + }, - _buildUri: corbel.Borrow._buildUri - }); -})(); + _buildUri: corbel.Borrow._buildUri + }) +})() diff --git a/src/borrow/lenderBuilder.js b/src/borrow/lenderBuilder.js index 02ad36f..87990e8 100644 --- a/src/borrow/lenderBuilder.js +++ b/src/borrow/lenderBuilder.js @@ -1,135 +1,133 @@ -//@exclude -'use strict'; -//@endexclude - -(function() { +// @exclude +'use strict' +// @endexclude +/* global corbel */ +;(function () { + /** + * A builder for borrowed management requests. + * + * @param {String} id lender ID. + * + * @class + * @memberOf corbel.Borrow.LenderBuilder + */ + corbel.Borrow.LenderBuilder = corbel.Services.inherit({ + constructor: function (id) { + this.id = id + this.uri = 'lender' + }, + /** + * Create a new Lender + * @method + * @memberOf corbel.Borrow.LenderBuilder + * @param {Object} lender The lender data + * @param {String} lender.id The lender name + * @param {String} lender.borrowPeriod The borrow period + * @param {String} lender.freeReturnPeriod Return without use + * @param {String} lender.reservationPeriod Period to apply after wait on queue + * @param {String} lender.maxConcurrentLoansPerUser Number of loans at same time + * @param {String} lender.maxLoansPerUserInMonth Limit number of loans per user + * @param {Object} lender.maxRenewalsPerResource Number of times user can renew his loans + * @param {Object} lender.maxUsersInWaitingQueue Waiting queue size + * @param {Object} lender.priority RENEW or RESERVE + * @return {Promise} A promise with the id of the created loanable resources or fails + * with a {@link corbelError}. + */ + create: function (lender) { + console.log('borrowInterface.lender.create', lender) + return this.request({ + url: this._buildUri(this.uri), + method: corbel.request.method.POST, + data: lender + }).then(function (res) { + return corbel.Services.getLocationId(res) + }) + }, + /** + * Update a Lender. + * + * @method + * @memberOf corbel.Borrow.LenderBuilder + * + * @param {Object} lender The lender data. + * + * @return {Promise} A promise resolves to undefined (void) or fails with a {@link corbelError}. + */ + update: function (lender) { + console.log('borrowInterface.lender.update') + return this.request({ + url: this._buildUri(this.uri, this.id), + method: corbel.request.method.PUT, + data: lender + }) + }, /** - * A builder for borrowed management requests. + * Delete a Lender. * - * @param {String} id lender ID. + * @method + * @memberOf corbel.Borrow.LenderBuilder * - * @class + * @return {Promise} A promise resolves to undefined (void) or fails with a {@link corbelError}. + */ + delete: function () { + console.log('borrowInterface.lender.delete') + + return this.request({ + url: this._buildUri(this.uri, this.id), + method: corbel.request.method.DELETE + }) + }, + /** + * Get Lender. + * + * @method * @memberOf corbel.Borrow.LenderBuilder + * + * @return {Promise} A promise with lender {Object} or fails with a {@link corbelError}. */ - corbel.Borrow.LenderBuilder = corbel.Services.inherit({ + get: function () { + console.log('borrowInterface.lender.get') - constructor: function(id) { - this.id = id; - this.uri = 'lender'; - }, - /** - * Create a new Lender - * @method - * @memberOf corbel.Borrow.LenderBuilder - * @param {Object} lender The lender data - * @param {String} lender.id The lender name - * @param {String} lender.borrowPeriod The borrow period - * @param {String} lender.freeReturnPeriod Return without use - * @param {String} lender.reservationPeriod Period to apply after wait on queue - * @param {String} lender.maxConcurrentLoansPerUser Number of loans at same time - * @param {String} lender.maxLoansPerUserInMonth Limit number of loans per user - * @param {Object} lender.maxRenewalsPerResource Number of times user can renew his loans - * @param {Object} lender.maxUsersInWaitingQueue Waiting queue size - * @param {Object} lender.priority RENEW or RESERVE - * @return {Promise} A promise with the id of the created loanable resources or fails - * with a {@link corbelError}. - */ - create: function(lender) { - console.log('borrowInterface.lender.create', lender); - return this.request({ - url: this._buildUri(this.uri), - method: corbel.request.method.POST, - data: lender - }).then(function(res) { - return corbel.Services.getLocationId(res); - }); - }, - /** - * Update a Lender. - * - * @method - * @memberOf corbel.Borrow.LenderBuilder - * - * @param {Object} lender The lender data. - * - * @return {Promise} A promise resolves to undefined (void) or fails with a {@link corbelError}. - */ - update: function(lender) { - console.log('borrowInterface.lender.update'); - - return this.request({ - url: this._buildUri(this.uri, this.id), - method: corbel.request.method.PUT, - data: lender - }); - }, - /** - * Delete a Lender. - * - * @method - * @memberOf corbel.Borrow.LenderBuilder - * - * @return {Promise} A promise resolves to undefined (void) or fails with a {@link corbelError}. - */ - delete: function() { - console.log('borrowInterface.lender.delete'); - - return this.request({ - url: this._buildUri(this.uri, this.id), - method: corbel.request.method.DELETE - }); - }, - /** - * Get Lender. - * - * @method - * @memberOf corbel.Borrow.LenderBuilder - * - * @return {Promise} A promise with lender {Object} or fails with a {@link corbelError}. - */ - get: function() { - console.log('borrowInterface.lender.get'); - - return this.request({ - url: this._buildUri(this.uri, this.id), - method: corbel.request.method.GET - }); - }, - /** - * Get all Lenders. - * - * @method - * @memberOf corbel.Borrow.LenderBuilder - * - * @return {Promise} A promise with all lenders {Object} or fails with a {@link corbelError}. - */ - getAll: function(params) { - console.log('borrowInterface.lender.getAll'); - return this.request({ - url: this._buildUri(this.uri, 'all'), - method: corbel.request.method.GET, - query: params ? corbel.utils.serializeParams(params) : null - }); - }, - /** - * Get all reservations by lender. - * - * @method - * @memberOf corbel.Borrow.LenderBuilder - * - * @return {Promise} A promise with all reservations {Object} by lender or fails with a {@link corbelError}. - */ - getAllReservations: function(params) { - console.log('borrowInterface.lender.getAllReservations'); - return this.request({ - url: this._buildUri(this.uri, 'reservation'), - method: corbel.request.method.GET, - query: params ? corbel.utils.serializeParams(params) : null - }); - }, + return this.request({ + url: this._buildUri(this.uri, this.id), + method: corbel.request.method.GET + }) + }, + /** + * Get all Lenders. + * + * @method + * @memberOf corbel.Borrow.LenderBuilder + * + * @return {Promise} A promise with all lenders {Object} or fails with a {@link corbelError}. + */ + getAll: function (params) { + console.log('borrowInterface.lender.getAll') + return this.request({ + url: this._buildUri(this.uri, 'all'), + method: corbel.request.method.GET, + query: params ? corbel.utils.serializeParams(params) : null + }) + }, + /** + * Get all reservations by lender. + * + * @method + * @memberOf corbel.Borrow.LenderBuilder + * + * @return {Promise} A promise with all reservations {Object} by lender or fails with a {@link corbelError}. + */ + getAllReservations: function (params) { + console.log('borrowInterface.lender.getAllReservations') + return this.request({ + url: this._buildUri(this.uri, 'reservation'), + method: corbel.request.method.GET, + query: params ? corbel.utils.serializeParams(params) : null + }) + }, - _buildUri: corbel.Borrow._buildUri - }); -})(); + _buildUri: corbel.Borrow._buildUri + }) +})() diff --git a/src/borrow/userBuilder.js b/src/borrow/userBuilder.js index 286301a..7ecad21 100644 --- a/src/borrow/userBuilder.js +++ b/src/borrow/userBuilder.js @@ -1,56 +1,53 @@ -//@exclude -'use strict'; -//@endexclude - -(function() { - +// @exclude +'use strict' +// @endexclude +/* global corbel */ +;(function () { + /** + * A builder for borrowed management requests. + * + * @param {String} id user ID. + * + * @class + * @memberOf corbel.Borrow.UserBuilder + */ + corbel.Borrow.UserBuilder = corbel.Services.inherit({ + constructor: function (id) { + this.id = id || 'me' + this.uri = 'user' + }, /** - * A builder for borrowed management requests. + * Get all reservations of a user. * - * @param {String} id user ID. + * @method + * @memberOf corbel.Borrow.UserBuilder * - * @class + * @return {Promise} A promise with all user reservations {Object} or fails with a {@link corbelError}. + */ + getAllReservations: function () { + console.log('borrowInterface.user.getAllReservations', this.id) + return this.request({ + url: this._buildUri(this.uri, this.id, 'reservation'), + method: corbel.request.method.GET + }) + }, + /** + * Get all loans of a user. + * + * @method * @memberOf corbel.Borrow.UserBuilder + * + * @return {Promise} A promise with all user loans {Object} or fails with a {@link corbelError}. */ - corbel.Borrow.UserBuilder = corbel.Services.inherit({ - - constructor: function(id) { - this.id = id || 'me'; - this.uri = 'user'; - }, - /** - * Get all reservations of a user. - * - * @method - * @memberOf corbel.Borrow.UserBuilder - * - * @return {Promise} A promise with all user reservations {Object} or fails with a {@link corbelError}. - */ - getAllReservations: function() { - console.log('borrowInterface.user.getAllReservations', this.id); - return this.request({ - url: this._buildUri(this.uri ,this.id, 'reservation'), - method: corbel.request.method.GET - }); - }, - /** - * Get all loans of a user. - * - * @method - * @memberOf corbel.Borrow.UserBuilder - * - * @return {Promise} A promise with all user loans {Object} or fails with a {@link corbelError}. - */ - getAllLoans: function() { - console.log('borrowInterface.user.getAllLoans', this.id); - return this.request({ - url: this._buildUri(this.uri ,this.id, 'loan'), - method: corbel.request.method.GET - }); - }, - + getAllLoans: function () { + console.log('borrowInterface.user.getAllLoans', this.id) + return this.request({ + url: this._buildUri(this.uri, this.id, 'loan'), + method: corbel.request.method.GET + }) + }, - _buildUri: corbel.Borrow._buildUri - }); -})(); + _buildUri: corbel.Borrow._buildUri + }) +})() diff --git a/src/build/default.js b/src/build/default.js index 766002d..d889062 100644 --- a/src/build/default.js +++ b/src/build/default.js @@ -1,19 +1,19 @@ -(function(root, factory) { - 'use strict'; +;(function (root, factory) { + 'use strict' /* jshint unused: false */ + /* global define */ if (typeof define === 'function' && define.amd) { - define([], function() { - return factory(root); - }); + define([], function () { + return factory(root) + }) } else if (typeof module !== 'undefined' && module.exports) { - module.exports = factory.call(root, root, process || undefined); + module.exports = factory.call(root, root, process || undefined) } else if (root !== undefined) { - root.corbel = factory(root); + root.corbel = factory(root) } - -})(this, function(root, process) { - 'use strict'; +})(this, function (root, process) { + 'use strict' /* jshint unused: false */ /** @@ -21,9 +21,9 @@ * @exports corbel * @namespace */ - var corbel = {}; + var corbel = {} - //-----------Utils and libraries (exports into corbel namespace)--------------------------- + // -----------Utils and libraries (exports into corbel namespace)--------------------------- // @include ../corbel.js @@ -41,7 +41,7 @@ // @include ../services.js - //----------corbel modules---------------- + // ----------corbel modules---------------- // @include ../config.js // @include ../iam/iam.js @@ -89,5 +89,5 @@ // @include ../webfs/webfsBuilder.js // @include ../domain/domain.js - return corbel; -}); + return corbel +}) diff --git a/src/build/with-polyfills.js b/src/build/with-polyfills.js index faddb40..4b71a71 100644 --- a/src/build/with-polyfills.js +++ b/src/build/with-polyfills.js @@ -1,27 +1,24 @@ -(function(root, factory) { - 'use strict'; - /* jshint unused: false */ +'use strict' +/* jshint unused: false */ +/* global define */ +;(function (root, factory) { if (typeof define === 'function' && define.amd) { - define(['es6-promise'], function(promise) { - promise.polyfill(); - return factory(root); - }); + define(['es6-promise'], function (promise) { + promise.polyfill() + return factory(root) + }) } else if (typeof module !== 'undefined' && module.exports) { - var Promise = require('es6-promise').polyfill(); - module.exports = factory.call(root); + var Promise = require('es6-promise') + Promise = Promise.polyfill() + module.exports = factory.call(root) } else if (window !== undefined) { if (root.ES6Promise !== undefined && typeof root.ES6Promise.polyfill === 'function') { - root.ES6Promise.polyfill(); + root.ES6Promise.polyfill() } - root.corbel = factory(root); + root.corbel = factory(root) } - - -})(this, function(root) { - 'use strict'; - /* jshint unused: false */ - +})(this, function (root) { // @include ../../bower_components/es6-promise/promise.js /** @@ -29,9 +26,9 @@ * @exports corbel * @namespace */ - var corbel = {}; + var corbel = {} - //-----------Utils and libraries (exports into corbel namespace)--------------------------- + // -----------Utils and libraries (exports into corbel namespace)--------------------------- // @include ../corbel.js @@ -49,7 +46,7 @@ // @include ../services.js - //----------corbel modules---------------- + // ----------corbel modules---------------- // @include ../config.js // @include ../iam/iam.js @@ -97,5 +94,5 @@ // @include ../webfs/webfsBuilder.js // @include ../domain/domain.js - return corbel; -}); + return corbel +}) diff --git a/src/composr/composr.js b/src/composr/composr.js index 597ea62..e43aa4f 100644 --- a/src/composr/composr.js +++ b/src/composr/composr.js @@ -1,9 +1,9 @@ -//@exclude -'use strict'; -//@endexclude - -(function() { +// @exclude +'use strict' +// @endexclude +/* global corbel */ +;(function () { /** * A module to make CompoSR requests. * @exports CompoSR @@ -12,9 +12,8 @@ */ corbel.CompoSR = corbel.Object.inherit({ - - constructor: function(driver) { - this.driver = driver; + constructor: function (driver) { + this.driver = driver }, /** @@ -24,10 +23,10 @@ * * @return {corbel.CompoSR.PhraseBuilder} */ - phrase: function(id) { - var phraseBuilder = new corbel.CompoSR.PhraseBuilder(id); - phraseBuilder.driver = this.driver; - return phraseBuilder; + phrase: function (id) { + var phraseBuilder = new corbel.CompoSR.PhraseBuilder(id) + phraseBuilder.driver = this.driver + return phraseBuilder }, /** @@ -40,44 +39,41 @@ * * @return {corbel.CompoSR.RequestBuilder} */ - request: function() { - var requestBuilder = new corbel.CompoSR.RequestBuilder(Array.prototype.slice.call(arguments)); - requestBuilder.driver = this.driver; - return requestBuilder; + request: function () { + var requestBuilder = new corbel.CompoSR.RequestBuilder(Array.prototype.slice.call(arguments)) + requestBuilder.driver = this.driver + return requestBuilder } - }, { - moduleName: 'composr', defaultPort: 3000, - create: function(driver) { - return new corbel.CompoSR(driver); + create: function (driver) { + return new corbel.CompoSR(driver) }, - _buildPort: function(config) { - return config.get('composrPort', null) || corbel.CompoSR.defaultPort; + _buildPort: function (config) { + return config.get('composrPort', null) || corbel.CompoSR.defaultPort }, - _buildUri: function() { - var urlBase = this.driver.config.getCurrentEndpoint(corbel.CompoSR.moduleName, corbel.CompoSR._buildPort(this.driver.config)); + _buildUri: function () { + var urlBase = this.driver.config.getCurrentEndpoint(corbel.CompoSR.moduleName, corbel.CompoSR._buildPort(this.driver.config)) if (urlBase.slice(-1) === '/') { - urlBase = urlBase.substring(0, urlBase.length - 1); + urlBase = urlBase.substring(0, urlBase.length - 1) } - var uri = ''; - Array.prototype.slice.call(arguments).forEach(function(argument) { + var uri = '' + Array.prototype.slice.call(arguments).forEach(function (argument) { if (argument) { - uri += '/' + argument; + uri += '/' + argument } - }); - return urlBase + uri; + }) + return urlBase + uri } - }); - - return corbel.CompoSR; + }) -})(); + return corbel.CompoSR +})() diff --git a/src/composr/phraseBuilder.js b/src/composr/phraseBuilder.js index 0600a7a..b55f9a3 100644 --- a/src/composr/phraseBuilder.js +++ b/src/composr/phraseBuilder.js @@ -1,10 +1,9 @@ -//@exclude -'use strict'; -//@endexclude - -(function() { - +// @exclude +'use strict' +// @endexclude +/* global corbel */ +;(function () { /** * A builder for composr phrase crud. * @@ -14,50 +13,49 @@ * @memberOf corbel.CompoSR.PhraseBuilder */ corbel.CompoSR.PhraseBuilder = corbel.Services.inherit({ - - constructor: function(id) { - this.id = id; + constructor: function (id) { + this.id = id }, - put: function(body) { - console.log('composrInterface.phrase.add'); + put: function (body) { + console.log('composrInterface.phrase.add') return this.request({ url: this._buildUri('phrase', this.id), method: corbel.request.method.PUT, data: body - }); + }) }, - get: function() { - console.log('composrInterface.phrase.get'); - corbel.validate.value('id', this.id); + get: function () { + console.log('composrInterface.phrase.get') + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri('phrase', this.id), method: corbel.request.method.GET - }); + }) }, - getAll: function() { - console.log('composrInterface.phrase.getAll'); + getAll: function () { + console.log('composrInterface.phrase.getAll') return this.request({ url: this._buildUri('phrase'), method: corbel.request.method.GET - }); + }) }, - delete: function() { - console.log('composrInterface.phrase.delete'); - corbel.validate.value('id', this.id); + delete: function () { + console.log('composrInterface.phrase.delete') + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri('phrase', this.id), method: corbel.request.method.DELETE - }); + }) }, _buildUri: corbel.CompoSR._buildUri - }); -})(); + }) +})() diff --git a/src/composr/requestBuilder.js b/src/composr/requestBuilder.js index 23d8fc0..f5306e4 100644 --- a/src/composr/requestBuilder.js +++ b/src/composr/requestBuilder.js @@ -1,92 +1,90 @@ -//@exclude -'use strict'; -//@endexclude +// @exclude +'use strict' +// @endexclude +/* global corbel */ -(function() { +;(function () { + /** + * A builder for composr requests. + * + * + * @class + * @memberOf corbel.CompoSR.RequestBuilder + */ + corbel.CompoSR.RequestBuilder = corbel.Services.inherit({ + constructor: function (pathsArray) { + this.path = this.buildPath(pathsArray) + }, + post: function (data, options) { + console.log('composrInterface.request.post') + this.options = options || {} + return this.request({ + url: this._buildUri(this.path), + method: corbel.request.method.POST, + headers: this.options.headers, + data: data, + query: this.buildQueryPath(this.options.queryParams) + }) + }, - /** - * A builder for composr requests. - * - * - * @class - * @memberOf corbel.CompoSR.RequestBuilder - */ - corbel.CompoSR.RequestBuilder = corbel.Services.inherit({ + get: function (options) { + console.log('composrInterface.request.get') + this.options = options || {} + return this.request({ + url: this._buildUri(this.path), + method: corbel.request.method.GET, + headers: this.options.headers, + query: this.buildQueryPath(this.options.queryParams) + }) + }, - constructor: function(pathsArray) { - this.path = this.buildPath(pathsArray); - }, + put: function (data, options) { + console.log('composrInterface.request.put') + this.options = options || {} + return this.request({ + url: this._buildUri(this.path), + method: corbel.request.method.PUT, + data: data, + headers: this.options.headers, + query: this.buildQueryPath(this.options.queryParams) + }) + }, - post: function(data, options) { - console.log('composrInterface.request.post'); - this.options = options || {}; - return this.request({ - url: this._buildUri(this.path), - method: corbel.request.method.POST, - headers: this.options.headers, - data: data, - query: this.buildQueryPath(this.options.queryParams) - }); - }, + delete: function (options) { + console.log('composrInterface.request.delete') + this.options = options || {} + return this.request({ + url: this._buildUri(this.path), + method: corbel.request.method.DELETE, + headers: this.options.headers, + query: this.buildQueryPath(this.options.queryParams) + }) + }, - get: function(options) { - console.log('composrInterface.request.get'); - this.options = options || {}; - return this.request({ - url: this._buildUri(this.path), - method: corbel.request.method.GET, - headers: this.options.headers, - query: this.buildQueryPath(this.options.queryParams) - }); - }, + buildPath: function (pathArray) { + var path = '' + path += pathArray.shift() + pathArray.forEach(function (entryPath) { + path += '/' + entryPath + }) + return path + }, - put: function(data, options) { - console.log('composrInterface.request.put'); - this.options = options || {}; - return this.request({ - url: this._buildUri(this.path), - method: corbel.request.method.PUT, - data: data, - headers: this.options.headers, - query: this.buildQueryPath(this.options.queryParams) - }); - }, + buildQueryPath: function (dict) { + var query = '' + if (dict) { + var queries = [] + Object.keys(dict).forEach(function (key) { + queries.push(key + '=' + dict[key]) + }) + if (queries.length > 0) { + query = queries.join('&') + } + } + return query + }, - delete: function(options) { - console.log('composrInterface.request.delete'); - this.options = options || {}; - return this.request({ - url: this._buildUri(this.path), - method: corbel.request.method.DELETE, - headers: this.options.headers, - query: this.buildQueryPath(this.options.queryParams) - }); - }, - - buildPath: function(pathArray) { - var path = ''; - path += pathArray.shift(); - pathArray.forEach(function(entryPath) { - path += '/' + entryPath; - }); - return path; - }, - - buildQueryPath: function(dict) { - var query = ''; - if (dict) { - var queries = []; - Object.keys(dict).forEach(function(key) { - queries.push(key + '=' + dict[key]); - }); - if (queries.length > 0) { - query = queries.join('&'); - } - } - return query; - }, - - _buildUri: corbel.CompoSR._buildUri - }); -})(); + _buildUri: corbel.CompoSR._buildUri + }) +})() diff --git a/src/config.js b/src/config.js index dbb8248..80f3da2 100644 --- a/src/config.js +++ b/src/config.js @@ -1,76 +1,74 @@ -//@exclude -'use strict'; +// @exclude +'use strict' /* globals corbel */ -//@endexclude +// @endexclude -function Config(config) { - config = config || {}; - // config default values - this.config = {}; +function Config (config) { + config = config || {} + // config default values + this.config = {} - corbel.utils.extend(this.config, config); + corbel.utils.extend(this.config, config) } -Config.URL_BASE_PLACEHOLDER = '{{module}}'; -Config.URL_BASE_PORT_PLACEHOLDER = '{{modulePort}}'; +Config.URL_BASE_PLACEHOLDER = '{{module}}' +Config.URL_BASE_PORT_PLACEHOLDER = '{{modulePort}}' -corbel.Config = Config; - -var processExist = function(){ - return typeof(process) !== 'undefined' || {}.toString.call(process) === '[object process]'; -}; +corbel.Config = Config +var processExist = function () { + return typeof (process) !== 'undefined' || {}.toString.call(process) === '[object process]' +} -if (typeof module !== 'undefined' && module.exports && processExist() && typeof window === 'undefined' ) { - Config.__env__ = process.env.NODE_ENV === 'browser' ? 'browser' : 'node'; +if (typeof module !== 'undefined' && module.exports && processExist() && typeof window === 'undefined') { + Config.__env__ = process.env.NODE_ENV === 'browser' ? 'browser' : 'node' } else { - Config.__env__ = 'browser'; + Config.__env__ = 'browser' } +Config.isNode = Config.__env__ === 'node' -Config.isNode = Config.__env__ === 'node'; - -Config.isBrowser = Config.__env__ === 'browser'; +Config.isBrowser = Config.__env__ === 'browser' /** * Client type * @type {String} * @default */ -Config.clientType = Config.isNode ? 'NODE' : 'WEB'; +Config.clientType = Config.isNode ? 'NODE' : 'WEB' if (Config.isNode) { - Config.wwwRoot = 'localhost'; + Config.wwwRoot = 'localhost' } else { - Config.wwwRoot = window.location.protocol + '//' + window.location.host + window.location.pathname; + Config.wwwRoot = window.location.protocol + '//' + window.location.host + window.location.pathname } /** * Returns all application config params * @return {Object} */ -Config.create = function(config) { - return new Config(config); -}; +Config.create = function (config) { + return new Config(config) +} /** * Returns all application config params * @return {Object} */ -Config.prototype.getConfig = function() { - return this.config; -}; +Config.prototype.getConfig = function () { + return this.config +} /** * Overrides current config with params object config * @param {Object} config An object with params to set as new config */ -Config.prototype.setConfig = function(config) { - this.config = corbel.utils.extend(this.config, config); - return this; -}; +Config.prototype.setConfig = function (config) { + this.config = corbel.utils.extend(this.config, config) + return this +} /** * Gets a specific config param @@ -78,36 +76,33 @@ Config.prototype.setConfig = function(config) { * @param {Mixed} defaultValue Default value if undefined * @return {Mixed} */ -Config.prototype.get = function(field, defaultValue) { - if (this.config[field] === undefined) { - if (defaultValue === undefined) { - throw new Error('config:undefined:' + field + ''); - } else { - return defaultValue; - } +Config.prototype.get = function (field, defaultValue) { + if (this.config[field] === undefined) { + if (defaultValue === undefined) { + throw new Error('config:undefined:' + field + '') + } else { + return defaultValue } + } - return this.config[field]; -}; - -Config.prototype.getCurrentEndpoint = function(moduleName, port){ - var moduleEndpoint = moduleName + 'Endpoint'; - var endpoint = this.get(moduleEndpoint, null) ? - this.get(moduleEndpoint) : - this.get('urlBase'); - endpoint = endpoint.replace(corbel.Config.URL_BASE_PLACEHOLDER, moduleName); - if (port) { - endpoint = endpoint.replace(corbel.Config.URL_BASE_PORT_PLACEHOLDER, port); - } - return endpoint; -}; + return this.config[field] +} +Config.prototype.getCurrentEndpoint = function (moduleName, port) { + var moduleEndpoint = moduleName + 'Endpoint' + var endpoint = this.get(moduleEndpoint, null) ? this.get(moduleEndpoint) : this.get('urlBase') + endpoint = endpoint.replace(corbel.Config.URL_BASE_PLACEHOLDER, moduleName) + if (port) { + endpoint = endpoint.replace(corbel.Config.URL_BASE_PORT_PLACEHOLDER, port) + } + return endpoint +} /** * Sets a new value for specific config param * @param {String} field Config param name * @param {Mixed} value Config param value */ -Config.prototype.set = function(field, value) { - this.config[field] = value; -}; +Config.prototype.set = function (field, value) { + this.config[field] = value +} diff --git a/src/corbel.js b/src/corbel.js index 44e4c37..eaf4377 100644 --- a/src/corbel.js +++ b/src/corbel.js @@ -1,134 +1,132 @@ -//@exclude -'use strict'; -//@endexclude - -(function() { - - /** - * @namespace - * @memberOf corbel - * @param {object} config - * @return {CorbelDriver} - */ - function CorbelDriver(config, events) { - - if (events && typeof events === 'object'){ - this._events = corbel.utils.clone(events); - }else{ - this._events = {}; - } - // create instance config - this.guid = corbel.utils.guid(); - this.config = corbel.Config.create(config); - - // create isntance modules with injected driver - this.iam = corbel.Iam.create(this); - this.resources = corbel.Resources.create(this); - this.assets = corbel.Assets.create(this); - this.oauth = corbel.Oauth.create(this); - this.notifications = corbel.Notifications.create(this); - this.ec = corbel.Ec.create(this); - this.evci = corbel.Evci.create(this); - this.borrow = corbel.Borrow.create(this); - this.composr = corbel.CompoSR.create(this); - this.scheduler = corbel.Scheduler.create(this); - this.webfs = corbel.Webfs.create(this); - this.domain = corbel.Domain.create(this); +// @exclude +'use strict' +// @endexclude +/* global corbel */ + +;(function () { + /** + * @namespace + * @memberOf corbel + * @param {object} config + * @return {CorbelDriver} + */ + function CorbelDriver (config, events) { + if (events && typeof events === 'object') { + this._events = corbel.utils.clone(events) + } else { + this._events = {} + } + // create instance config + this.guid = corbel.utils.guid() + this.config = corbel.Config.create(config) + + // create isntance modules with injected driver + this.iam = corbel.Iam.create(this) + this.resources = corbel.Resources.create(this) + this.assets = corbel.Assets.create(this) + this.oauth = corbel.Oauth.create(this) + this.notifications = corbel.Notifications.create(this) + this.ec = corbel.Ec.create(this) + this.evci = corbel.Evci.create(this) + this.borrow = corbel.Borrow.create(this) + this.composr = corbel.CompoSR.create(this) + this.scheduler = corbel.Scheduler.create(this) + this.webfs = corbel.Webfs.create(this) + this.domain = corbel.Domain.create(this) + } + + /** + * @return {CorbelDriver} A new instance of corbel driver with the same config + */ + CorbelDriver.prototype.clone = function () { + return new CorbelDriver(this.config.getConfig(), this._events) + } + + /** + * Adds an event handler for especific event + * @param {string} name Event name + * @param {Function} fn Function to call + */ + CorbelDriver.prototype.addEventListener = function (name, fn) { + if (typeof fn !== 'function') { + throw new Error('corbel:error:invalid:type') + } + this._events[name] = this._events[name] || [] + if (this._events[name].indexOf(fn) === -1) { + this._events[name].push(fn) + } + } + + /** + * Removes the handler from event list + * @param {string} name Event name + * @param {Function} fn Function to remove + */ + CorbelDriver.prototype.removeEventListener = function (name, fn) { + if (this._events[name]) { + var index = this._events[name].indexOf(fn) + if (index !== -1) { + this._events[name].splice(index, 1) + } + } + } + + /** + * Fires all events handlers for an specific event name + * @param {string} name Event name + * @param {Mixed} options Data for event handlers + */ + CorbelDriver.prototype.dispatch = function (name, options) { + if (this._events[name] && this._events[name].length) { + this._events[name].forEach(function (fn) { + fn(options) + }) + } + } + + /** + * Adds an event handler for especific event + * @see CorbelDriver.prototype.addEventListener + * @param {string} name Event name + * @param {Function} fn Function to call + */ + CorbelDriver.prototype.on = CorbelDriver.prototype.addEventListener + + /** + * Removes the handler from event list + * @see CorbelDriver.prototype.removeEventListener + * @param {string} name Event name + * @param {Function} fn Function to remove + */ + CorbelDriver.prototype.off = CorbelDriver.prototype.removeEventListener + + /** + * Fires all events handlers for an specific event name + * @see CorbelDriver.prototype.dispatch + * @param {string} name Event name + * @param {Mixed} options Data for event handlers + */ + CorbelDriver.prototype.trigger = CorbelDriver.prototype.dispatch + + corbel.CorbelDriver = CorbelDriver + + /** + * Instanciates new corbel driver + * @memberOf corbel + * @param {object} config + * @param {string} config.urlBase + * @param {string} [config.clientId] + * @param {string} [config.clientSecret] + * @param {string} [config.scopes] + * @return {corbel.CorbelDriver} + */ + corbel.getDriver = function (config) { + config = config || {} + + if (!config.urlBase) { + throw new Error('error:undefined:urlbase') } - /** - * @return {CorbelDriver} A new instance of corbel driver with the same config - */ - CorbelDriver.prototype.clone = function() { - return new CorbelDriver(this.config.getConfig(), this._events); - }; - - /** - * Adds an event handler for especific event - * @param {string} name Event name - * @param {Function} fn Function to call - */ - CorbelDriver.prototype.addEventListener = function(name, fn) { - if (typeof fn !== 'function') { - throw new Error('corbel:error:invalid:type'); - } - this._events[name] = this._events[name] || []; - if (this._events[name].indexOf(fn) === -1) { - this._events[name].push(fn); - } - }; - - /** - * Removes the handler from event list - * @param {string} name Event name - * @param {Function} fn Function to remove - */ - CorbelDriver.prototype.removeEventListener = function(name, fn) { - if (this._events[name]) { - var index = this._events[name].indexOf(fn); - if (index !== -1) { - this._events[name].splice(index, 1); - } - } - }; - - /** - * Fires all events handlers for an specific event name - * @param {string} name Event name - * @param {Mixed} options Data for event handlers - */ - CorbelDriver.prototype.dispatch = function(name, options) { - if (this._events[name] && this._events[name].length) { - this._events[name].forEach(function(fn) { - fn(options); - }); - } - }; - - /** - * Adds an event handler for especific event - * @see CorbelDriver.prototype.addEventListener - * @param {string} name Event name - * @param {Function} fn Function to call - */ - CorbelDriver.prototype.on = CorbelDriver.prototype.addEventListener; - - /** - * Removes the handler from event list - * @see CorbelDriver.prototype.removeEventListener - * @param {string} name Event name - * @param {Function} fn Function to remove - */ - CorbelDriver.prototype.off = CorbelDriver.prototype.removeEventListener; - - /** - * Fires all events handlers for an specific event name - * @see CorbelDriver.prototype.dispatch - * @param {string} name Event name - * @param {Mixed} options Data for event handlers - */ - CorbelDriver.prototype.trigger = CorbelDriver.prototype.dispatch; - - corbel.CorbelDriver = CorbelDriver; - - /** - * Instanciates new corbel driver - * @memberOf corbel - * @param {object} config - * @param {string} config.urlBase - * @param {string} [config.clientId] - * @param {string} [config.clientSecret] - * @param {string} [config.scopes] - * @return {corbel.CorbelDriver} - */ - corbel.getDriver = function(config) { - config = config || {}; - - if (!config.urlBase) { - throw new Error('error:undefined:urlbase'); - } - - return new CorbelDriver(config); - }; - -})(); + return new CorbelDriver(config) + } +})() diff --git a/src/cryptography.js b/src/cryptography.js index 811e7f8..e1904de 100644 --- a/src/cryptography.js +++ b/src/cryptography.js @@ -1,304 +1,311 @@ -//@exclude -'use strict'; +// @exclude +'use strict' /* globals corbel, root */ -//@endexclude - -(function() { - - /* jshint camelcase:false */ - corbel.cryptography = (function() { - /* - * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined - * in FIPS 180-2 - * Version 2.2 Copyright Angel Marin, Paul Johnston 2000 - 2009. - * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet - * Distributed under the BSD License - * See http://pajhome.org.uk/crypt/md5 for details. - * Also http://anmar.eu.org/projects/jssha2/ - */ - - /* - * Configurable variables. You may need to tweak these to be compatible with - * the server-side, but the defaults work in most cases. - */ - var hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase */ - var b64pad = ''; /* base-64 pad character. "=" for strict RFC compliance */ - - function b64_hmac_sha256(k, d) { - return rstr2b64(rstr_hmac_sha256(str2rstr_utf8(k), str2rstr_utf8(d))); +/* jshint unused:true */ +// @endexclude + +;(function () { + /* jshint camelcase:false */ + corbel.cryptography = (function () { + /* + * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined + * in FIPS 180-2 + * Version 2.2 Copyright Angel Marin, Paul Johnston 2000 - 2009. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * Distributed under the BSD License + * See http://pajhome.org.uk/crypt/md5 for details. + * Also http://anmar.eu.org/projects/jssha2/ + */ + + /* + * Configurable variables. You may need to tweak these to be compatible with + * the server-side, but the defaults work in most cases. + */ + // var hexcase = 0 hex output format. 0 - lowercase; 1 - uppercase + var b64pad = '' /* base-64 pad character. "=" for strict RFC compliance */ + + function b64_hmac_sha256 (k, d) { + return rstr2b64(rstr_hmac_sha256(str2rstr_utf8(k), str2rstr_utf8(d))) + } + + /* + * Calculate the HMAC-sha256 of a key and some data (raw strings) + */ + function rstr_hmac_sha256 (key, data) { + var bkey = rstr2binb(key) + if (bkey.length > 16) { + bkey = binb_sha256(bkey, key.length * 8) + } + + var ipad = Array(16) + var opad = Array(16) + for (var i = 0; i < 16; i++) { + ipad[i] = bkey[i] ^ 0x36363636 + opad[i] = bkey[i] ^ 0x5C5C5C5C + } + + var hash = binb_sha256(ipad.concat(rstr2binb(data)), 512 + data.length * 8) + return binb2rstr(binb_sha256(opad.concat(hash), 512 + 256)) + } + + /* + * Convert a raw string to a base-64 string + */ + function rstr2b64 (input) { + try { + b64pad + } catch (e) { + b64pad = '' + } + var tab = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' + var output = '' + var len = input.length + for (var i = 0; i < len; i += 3) { + var triplet = (input.charCodeAt(i) << 16) | (i + 1 < len ? input.charCodeAt(i + 1) << 8 : 0) | (i + 2 < len ? input.charCodeAt(i + 2) : 0) + for (var j = 0; j < 4; j++) { + if (i * 8 + j * 6 > input.length * 8) output += b64pad + else output += tab.charAt((triplet >>> 6 * (3 - j)) & 0x3F) } - - /* - * Calculate the HMAC-sha256 of a key and some data (raw strings) - */ - function rstr_hmac_sha256(key, data) { - var bkey = rstr2binb(key); - if (bkey.length > 16) { - bkey = binb_sha256(bkey, key.length * 8); - } - - var ipad = Array(16), - opad = Array(16); - for (var i = 0; i < 16; i++) { - ipad[i] = bkey[i] ^ 0x36363636; - opad[i] = bkey[i] ^ 0x5C5C5C5C; - } - - var hash = binb_sha256(ipad.concat(rstr2binb(data)), 512 + data.length * 8); - return binb2rstr(binb_sha256(opad.concat(hash), 512 + 256)); - } - - /* - * Convert a raw string to a base-64 string - */ - function rstr2b64(input) { - try { - b64pad - } catch (e) { - b64pad = ''; - } - var tab = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; - var output = ''; - var len = input.length; - for (var i = 0; i < len; i += 3) { - var triplet = (input.charCodeAt(i) << 16) | (i + 1 < len ? input.charCodeAt(i + 1) << 8 : 0) | (i + 2 < len ? input.charCodeAt(i + 2) : 0); - for (var j = 0; j < 4; j++) { - if (i * 8 + j * 6 > input.length * 8) output += b64pad; - else output += tab.charAt((triplet >>> 6 * (3 - j)) & 0x3F); - } - } - return output; - } - - /* - * Encode a string as utf-8. - * For efficiency, this assumes the input is valid utf-16. - */ - function str2rstr_utf8(input) { - var output = ''; - var i = -1; - var x, y; - - while (++i < input.length) { - /* Decode utf-16 surrogate pairs */ - x = input.charCodeAt(i); - y = i + 1 < input.length ? input.charCodeAt(i + 1) : 0; - if (0xD800 <= x && x <= 0xDBFF && 0xDC00 <= y && y <= 0xDFFF) { - x = 0x10000 + ((x & 0x03FF) << 10) + (y & 0x03FF); - i++; - } - - /* Encode output as utf-8 */ - if (x <= 0x7F) - output += String.fromCharCode(x); - else if (x <= 0x7FF) - output += String.fromCharCode(0xC0 | ((x >>> 6) & 0x1F), - 0x80 | (x & 0x3F)); - else if (x <= 0xFFFF) - output += String.fromCharCode(0xE0 | ((x >>> 12) & 0x0F), - 0x80 | ((x >>> 6) & 0x3F), - 0x80 | (x & 0x3F)); - else if (x <= 0x1FFFFF) - output += String.fromCharCode(0xF0 | ((x >>> 18) & 0x07), - 0x80 | ((x >>> 12) & 0x3F), - 0x80 | ((x >>> 6) & 0x3F), - 0x80 | (x & 0x3F)); - } - return output; - } - - /* - * Convert a raw string to an array of big-endian words - * Characters >255 have their high-byte silently ignored. - */ - function rstr2binb(input) { - var output = Array(input.length >> 2); - for (var i = 0; i < output.length; i++) - output[i] = 0; - for (var i = 0; i < input.length * 8; i += 8) - output[i >> 5] |= (input.charCodeAt(i / 8) & 0xFF) << (24 - i % 32); - return output; - } - - /* - * Convert an array of big-endian words to a string - */ - function binb2rstr(input) { - var output = ''; - for (var i = 0; i < input.length * 32; i += 8) - output += String.fromCharCode((input[i >> 5] >>> (24 - i % 32)) & 0xFF); - return output; - } - - /* - * Main sha256 function, with its support functions - */ - function sha256_S(X, n) { - return (X >>> n) | (X << (32 - n)); - } - - function sha256_R(X, n) { - return (X >>> n); - } - - function sha256_Ch(x, y, z) { - return ((x & y) ^ ((~x) & z)); + } + return output + } + + /* + * Encode a string as utf-8. + * For efficiency, this assumes the input is valid utf-16. + */ + function str2rstr_utf8 (input) { + var output = '' + var i = -1 + var x, y + + while (++i < input.length) { + /* Decode utf-16 surrogate pairs */ + x = input.charCodeAt(i) + y = i + 1 < input.length ? input.charCodeAt(i + 1) : 0 + if (x > 0xD800 && x <= 0xDBFF && y > 0xDC00 && y <= 0xDFFF) { + x = 0x10000 + ((x & 0x03FF) << 10) + (y & 0x03FF) + i++ } - function sha256_Maj(x, y, z) { - return ((x & y) ^ (x & z) ^ (y & z)); + /* Encode output as utf-8 */ + if (x <= 0x7F) { + output += String.fromCharCode(x) + } else if (x <= 0x7FF) { + output += String.fromCharCode(0xC0 | ((x >>> 6) & 0x1F), 0x80 | (x & 0x3F)) + } else if (x <= 0xFFFF) { + output += String.fromCharCode(0xE0 | ((x >>> 12) & 0x0F), + 0x80 | ((x >>> 6) & 0x3F), + 0x80 | (x & 0x3F)) + } else if (x <= 0x1FFFFF) { + output += String.fromCharCode(0xF0 | ((x >>> 18) & 0x07), + 0x80 | ((x >>> 12) & 0x3F), + 0x80 | ((x >>> 6) & 0x3F), + 0x80 | (x & 0x3F)) } - - function sha256_Sigma0256(x) { - return (sha256_S(x, 2) ^ sha256_S(x, 13) ^ sha256_S(x, 22)); - } - - function sha256_Sigma1256(x) { - return (sha256_S(x, 6) ^ sha256_S(x, 11) ^ sha256_S(x, 25)); - } - - function sha256_Gamma0256(x) { - return (sha256_S(x, 7) ^ sha256_S(x, 18) ^ sha256_R(x, 3)); - } - - function sha256_Gamma1256(x) { - return (sha256_S(x, 17) ^ sha256_S(x, 19) ^ sha256_R(x, 10)); - } - - var sha256_K = new Array( - 1116352408, 1899447441, -1245643825, -373957723, 961987163, 1508970993, -1841331548, -1424204075, -670586216, 310598401, 607225278, 1426881987, - 1925078388, -2132889090, -1680079193, -1046744716, -459576895, -272742522, - 264347078, 604807628, 770255983, 1249150122, 1555081692, 1996064986, -1740746414, -1473132947, -1341970488, -1084653625, -958395405, -710438585, - 113926993, 338241895, 666307205, 773529912, 1294757372, 1396182291, - 1695183700, 1986661051, -2117940946, -1838011259, -1564481375, -1474664885, -1035236496, -949202525, -778901479, -694614492, -200395387, 275423344, - 430227734, 506948616, 659060556, 883997877, 958139571, 1322822218, - 1537002063, 1747873779, 1955562222, 2024104815, -2067236844, -1933114872, -1866530822, -1538233109, -1090935817, -965641998 - ); - - function binb_sha256(m, l) { - var HASH = new Array(1779033703, -1150833019, 1013904242, -1521486534, - 1359893119, -1694144372, 528734635, 1541459225); - var W = new Array(64); - var a, b, c, d, e, f, g, h; - var i, j, T1, T2; - - /* append padding */ - m[l >> 5] |= 0x80 << (24 - l % 32); - m[((l + 64 >> 9) << 4) + 15] = l; - - for (i = 0; i < m.length; i += 16) { - a = HASH[0]; - b = HASH[1]; - c = HASH[2]; - d = HASH[3]; - e = HASH[4]; - f = HASH[5]; - g = HASH[6]; - h = HASH[7]; - - for (j = 0; j < 64; j++) { - if (j < 16) W[j] = m[j + i]; - else W[j] = safe_add(safe_add(safe_add(sha256_Gamma1256(W[j - 2]), W[j - 7]), - sha256_Gamma0256(W[j - 15])), W[j - 16]); - - T1 = safe_add(safe_add(safe_add(safe_add(h, sha256_Sigma1256(e)), sha256_Ch(e, f, g)), - sha256_K[j]), W[j]); - T2 = safe_add(sha256_Sigma0256(a), sha256_Maj(a, b, c)); - h = g; - g = f; - f = e; - e = safe_add(d, T1); - d = c; - c = b; - b = a; - a = safe_add(T1, T2); - } - - HASH[0] = safe_add(a, HASH[0]); - HASH[1] = safe_add(b, HASH[1]); - HASH[2] = safe_add(c, HASH[2]); - HASH[3] = safe_add(d, HASH[3]); - HASH[4] = safe_add(e, HASH[4]); - HASH[5] = safe_add(f, HASH[5]); - HASH[6] = safe_add(g, HASH[6]); - HASH[7] = safe_add(h, HASH[7]); - } - return HASH; - } - - function safe_add(x, y) { - var lsw = (x & 0xFFFF) + (y & 0xFFFF); - var msw = (x >> 16) + (y >> 16) + (lsw >> 16); - return (msw << 16) | (lsw & 0xFFFF); - } - - /*! base64x-1.1.3 (c) 2012-2014 Kenji Urushima | kjur.github.com/jsjws/license - */ - /* - * base64x.js - Base64url and supplementary functions for Tom Wu's base64.js library - * - * version: 1.1.3 (2014 May 25) - * - * Copyright (c) 2012-2014 Kenji Urushima (kenji.urushima@gmail.com) - * - * This software is licensed under the terms of the MIT License. - * http://kjur.github.com/jsjws/license/ - * - * The above copyright and license notice shall be - * included in all copies or substantial portions of the Software. - * - * DEPENDS ON: - * - base64.js - Tom Wu's Base64 library - */ - - /** - * Base64URL and supplementary functions for Tom Wu's base64.js library.
- * This class is just provide information about global functions - * defined in 'base64x.js'. The 'base64x.js' script file provides - * global functions for converting following data each other. - * - * All functions in 'base64x.js' are defined in {@link _global_} and not - * in this class. - * - * @class Base64URL and supplementary functions for Tom Wu's base64.js library - * @author Kenji Urushima - * @version 1.1 (07 May 2012) - * @requires base64.js - * @see 'jwjws'(JWS JavaScript Library) home page http://kjur.github.com/jsjws/ - * @see 'jwrsasign'(RSA Sign JavaScript Library) home page http://kjur.github.com/jsrsasign/ - */ - function Base64x() {} - - // ==== base64 / base64url ================================ - /** - * convert a Base64 encoded string to a Base64URL encoded string.
- * Example: "ab+c3f/==" → "ab-c3f_" - * @param {String} s Base64 encoded string - * @return {String} Base64URL encoded string - */ - function b64tob64u(s) { - s = s.replace(/\=/g, ''); - s = s.replace(/\+/g, '-'); - s = s.replace(/\//g, '_'); - return s; - } - - var utf8tob64u, b64utoutf8; - - return { - rstr2b64: rstr2b64, - str2rstr_utf8: str2rstr_utf8, - b64_hmac_sha256: b64_hmac_sha256, - b64tob64u: b64tob64u + } + return output + } + + /* + * Convert a raw string to an array of big-endian words + * Characters >255 have their high-byte silently ignored. + */ + function rstr2binb (input) { + var output = Array(input.length >> 2) + for (var i = 0; i < output.length; i++) { + output[i] = 0 + } + for (var j = 0; j < input.length * 8; j += 8) { + output[j >> 5] |= (input.charCodeAt(j / 8) & 0xFF) << (24 - j % 32) + } + return output + } + + /* + * Convert an array of big-endian words to a string + */ + function binb2rstr (input) { + var output = '' + for (var i = 0; i < input.length * 32; i += 8) { + output += String.fromCharCode((input[i >> 5] >>> (24 - i % 32)) & 0xFF) + } + return output + } + + /* + * Main sha256 function, with its support functions + */ + function sha256_S (X, n) { + return (X >>> n) | (X << (32 - n)) + } + + function sha256_R (X, n) { + return (X >>> n) + } + + function sha256_Ch (x, y, z) { + return ((x & y) ^ ((~x) & z)) + } + + function sha256_Maj (x, y, z) { + return ((x & y) ^ (x & z) ^ (y & z)) + } + + function sha256_Sigma0256 (x) { + return (sha256_S(x, 2) ^ sha256_S(x, 13) ^ sha256_S(x, 22)) + } + + function sha256_Sigma1256 (x) { + return (sha256_S(x, 6) ^ sha256_S(x, 11) ^ sha256_S(x, 25)) + } + + function sha256_Gamma0256 (x) { + return (sha256_S(x, 7) ^ sha256_S(x, 18) ^ sha256_R(x, 3)) + } + + function sha256_Gamma1256 (x) { + return (sha256_S(x, 17) ^ sha256_S(x, 19) ^ sha256_R(x, 10)) + } + + var sha256_K = [ + 1116352408, 1899447441, -1245643825, -373957723, 961987163, 1508970993, -1841331548, -1424204075, -670586216, 310598401, 607225278, 1426881987, + 1925078388, -2132889090, -1680079193, -1046744716, -459576895, -272742522, + 264347078, 604807628, 770255983, 1249150122, 1555081692, 1996064986, -1740746414, -1473132947, -1341970488, -1084653625, -958395405, -710438585, + 113926993, 338241895, 666307205, 773529912, 1294757372, 1396182291, + 1695183700, 1986661051, -2117940946, -1838011259, -1564481375, -1474664885, -1035236496, -949202525, -778901479, -694614492, -200395387, 275423344, + 430227734, 506948616, 659060556, 883997877, 958139571, 1322822218, + 1537002063, 1747873779, 1955562222, 2024104815, -2067236844, -1933114872, -1866530822, -1538233109, -1090935817, -965641998 + ] + + function binb_sha256 (m, l) { + var HASH = [1779033703, -1150833019, 1013904242, -1521486534, + 1359893119, -1694144372, 528734635, 1541459225] + var W = new Array(64) + var a, b, c, d, e, f, g, h + var i, j, T1, T2 + + /* append padding */ + m[l >> 5] |= 0x80 << (24 - l % 32) + m[((l + 64 >> 9) << 4) + 15] = l + + for (i = 0; i < m.length; i += 16) { + a = HASH[0] + b = HASH[1] + c = HASH[2] + d = HASH[3] + e = HASH[4] + f = HASH[5] + g = HASH[6] + h = HASH[7] + + for (j = 0; j < 64; j++) { + if (j < 16) { + W[j] = m[j + i] + } else { + W[j] = safe_add(safe_add(safe_add(sha256_Gamma1256(W[j - 2]), W[j - 7]), + sha256_Gamma0256(W[j - 15])), W[j - 16]) + } + + T1 = safe_add(safe_add(safe_add(safe_add(h, sha256_Sigma1256(e)), sha256_Ch(e, f, g)), + sha256_K[j]), W[j]) + T2 = safe_add(sha256_Sigma0256(a), sha256_Maj(a, b, c)) + h = g + g = f + f = e + e = safe_add(d, T1) + d = c + c = b + b = a + a = safe_add(T1, T2) } - })(); -})(); + HASH[0] = safe_add(a, HASH[0]) + HASH[1] = safe_add(b, HASH[1]) + HASH[2] = safe_add(c, HASH[2]) + HASH[3] = safe_add(d, HASH[3]) + HASH[4] = safe_add(e, HASH[4]) + HASH[5] = safe_add(f, HASH[5]) + HASH[6] = safe_add(g, HASH[6]) + HASH[7] = safe_add(h, HASH[7]) + } + return HASH + } + + function safe_add (x, y) { + var lsw = (x & 0xFFFF) + (y & 0xFFFF) + var msw = (x >> 16) + (y >> 16) + (lsw >> 16) + return (msw << 16) | (lsw & 0xFFFF) + } + + /*! base64x-1.1.3 (c) 2012-2014 Kenji Urushima | kjur.github.com/jsjws/license + */ + /* + * base64x.js - Base64url and supplementary functions for Tom Wu's base64.js library + * + * version: 1.1.3 (2014 May 25) + * + * Copyright (c) 2012-2014 Kenji Urushima (kenji.urushima@gmail.com) + * + * This software is licensed under the terms of the MIT License. + * http://kjur.github.com/jsjws/license/ + * + * The above copyright and license notice shall be + * included in all copies or substantial portions of the Software. + * + * DEPENDS ON: + * - base64.js - Tom Wu's Base64 library + */ + + /** + * Base64URL and supplementary functions for Tom Wu's base64.js library.
+ * This class is just provide information about global functions + * defined in 'base64x.js'. The 'base64x.js' script file provides + * global functions for converting following data each other. + * + * All functions in 'base64x.js' are defined in {@link _global_} and not + * in this class. + * + * @class Base64URL and supplementary functions for Tom Wu's base64.js library + * @author Kenji Urushima + * @version 1.1 (07 May 2012) + * @requires base64.js + * @see 'jwjws'(JWS JavaScript Library) home page http://kjur.github.com/jsjws/ + * @see 'jwrsasign'(RSA Sign JavaScript Library) home page http://kjur.github.com/jsrsasign/ + */ + + // function Base64x () {} + + // ==== base64 / base64url ================================ + /** + * convert a Base64 encoded string to a Base64URL encoded string.
+ * Example: "ab+c3f/==" → "ab-c3f_" + * @param {String} s Base64 encoded string + * @return {String} Base64URL encoded string + */ + function b64tob64u (s) { + s = s.replace(/\=/g, '') + s = s.replace(/\+/g, '-') + s = s.replace(/\//g, '_') + return s + } + + // var utf8tob64u + // var b64utoutf8 + + return { + rstr2b64: rstr2b64, + str2rstr_utf8: str2rstr_utf8, + b64_hmac_sha256: b64_hmac_sha256, + b64tob64u: b64tob64u + } + })() +})() diff --git a/src/domain/domain.js b/src/domain/domain.js index 7968b3b..9753bb2 100644 --- a/src/domain/domain.js +++ b/src/domain/domain.js @@ -1,8 +1,9 @@ -(function() { - //@exclude - 'use strict'; - //@endexclude +// @exclude +'use strict' +// @endexclude +/* global corbel */ +;(function () { /** * A custom domain configuration * @exports corbel.Domain @@ -11,26 +12,23 @@ * @memberof corbel */ corbel.Domain = corbel.Object.inherit({ - /** * Creates a new instance of corbelDriver with a custom domain * @memberof corbel.Domain.prototype * @param {string} id String with the custom domain value * @return {corbelDriver} */ - constructor: function(driver) { - this.driver = driver; + constructor: function (driver) { + this.driver = driver - return function(id) { - driver.config.set(corbel.Domain.CUSTOM_DOMAIN, id); + return function (id) { + driver.config.set(corbel.Domain.CUSTOM_DOMAIN, id) - return driver; - }; + return driver + } } - }, { - /** * moduleName constant * @constant @@ -55,12 +53,11 @@ * @param {corbel} corbel instance driver * @return {function} */ - create: function(driver) { - return new corbel.Domain(driver); + create: function (driver) { + return new corbel.Domain(driver) } - }); - - return corbel.Domain; + }) -})(); + return corbel.Domain +})() diff --git a/src/ec/ec.js b/src/ec/ec.js index 2cc9515..803943b 100644 --- a/src/ec/ec.js +++ b/src/ec/ec.js @@ -1,9 +1,9 @@ -//@exclude -'use strict'; -//@endexclude - -(function() { +// @exclude +'use strict' +// @endexclude +/* global corbel */ +;(function () { /** * A module to make Ec requests. * @exports Ec @@ -11,16 +11,16 @@ * @memberof app.corbel */ - var Ec = corbel.Ec = function(driver) { - this.driver = driver; - }; + var Ec = corbel.Ec = function (driver) { + this.driver = driver + } - Ec.moduleName = 'ec'; - Ec.defaultPort = 8088; + Ec.moduleName = 'ec' + Ec.defaultPort = 8088 - Ec.create = function(driver) { - return new Ec(driver); - }; + Ec.create = function (driver) { + return new Ec(driver) + } Ec._ec = { /** @@ -67,7 +67,7 @@ */ CANCELLED: 'CANCELLED' } - }; + } /** * COMMON MIXINS @@ -77,8 +77,8 @@ // return { // name: data.name, // data: cse.encrypt(data.number, data.holderName, data.cvc, data.expiryMonth, data.expiryYear) - // }; - // }; + // } + // } /** * Private method to build a string uri @@ -88,20 +88,19 @@ * @param {String} extra * @return {String} */ - Ec._buildUri = function(uri, id, extra) { + Ec._buildUri = function (uri, id, extra) { if (id) { - uri += '/' + id; + uri += '/' + id } if (extra) { - uri += extra; + uri += extra } - var urlBase = this.driver.config.getCurrentEndpoint( Ec.moduleName, corbel.Ec._buildPort(this.driver.config)); - - return urlBase + uri; - }; + var urlBase = this.driver.config.getCurrentEndpoint(Ec.moduleName, corbel.Ec._buildPort(this.driver.config)) - Ec._buildPort = function(config) { - return config.get('ecPort', null) || corbel.Ec.defaultPort; - }; + return urlBase + uri + } -})(); + Ec._buildPort = function (config) { + return config.get('ecPort', null) || corbel.Ec.defaultPort + } +})() diff --git a/src/ec/orderBuilder.js b/src/ec/orderBuilder.js index a647b5b..9204ef3 100644 --- a/src/ec/orderBuilder.js +++ b/src/ec/orderBuilder.js @@ -1,9 +1,9 @@ -//@exclude -'use strict'; -//@endexclude - -(function() { +// @exclude +'use strict' +// @endexclude +/* global corbel */ +;(function () { /** * Create a OrderBuilder for order managing requests. * @@ -11,11 +11,11 @@ * * @return {corbel.Ec.OrderBuilder} */ - corbel.Ec.prototype.order = function(id) { - var order = new OrderBuilder(id); - order.driver = this.driver; - return order; - }; + corbel.Ec.prototype.order = function (id) { + var order = new OrderBuilder(id) + order.driver = this.driver + return order + } /** * A builder for order requests. @@ -26,12 +26,11 @@ * @memberOf corbel.Ec.OrderBuilder */ var OrderBuilder = corbel.Ec.OrderBuilder = corbel.Services.inherit({ - - constructor: function(id) { + constructor: function (id) { if (id) { - this.id = id; + this.id = id } - this.uri = 'order'; + this.uri = 'order' }, /** @@ -40,12 +39,12 @@ * @memberOf corbel.Ec.OrderBuilder * @return {Promise} Q promise that resolves to a Order {Object} or rejects with a {@link SilkRoadError} */ - get: function() { - corbel.validate.value('id', this.id); + get: function () { + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id), method: corbel.request.method.GET - }); + }) }, /** @@ -56,13 +55,13 @@ * @param {Object[]} order.items Array of products to purchase * @return {Promise} Q promise that resolves to undefined (void) or rejects with a {@link SilkRoadError} */ - update: function(order) { - corbel.validate.value('id', this.id); + update: function (order) { + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id), method: corbel.request.method.PUT, data: order - }); + }) }, /** @@ -71,12 +70,12 @@ * @memberOf corbel.Ec.OrderBuilder * @return {Promise} Q promise that resolves to undefined (void) or rejects with a {@link SilkRoadError} */ - delete: function() { - corbel.validate.value('id', this.id); + delete: function () { + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id), method: corbel.request.method.DELETE - }); + }) }, /** @@ -86,13 +85,13 @@ * @param {string[]} couponIds Array of String with the coupons ids to prepare the order * @return {Promise} Q promise that resolves to undefined (void) or rejects with a {@link SilkRoadError} */ - prepare: function(couponIds) { - corbel.validate.value('id', this.id); + prepare: function (couponIds) { + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id, '/prepare'), method: corbel.request.method.POST, data: couponIds - }); + }) }, /** @@ -104,21 +103,21 @@ * @param {string[]} discountsIds Array of String with the discounts ids to checkout the order * @return {Promise} Promise that resolves in the new purchase id or rejects with a {@link SilkRoadError} */ - checkout: function(data) { + checkout: function (data) { if (!data.paymentMethodIds) { - return Promise.reject(new Error('paymentMethodIds lists needed')); + return Promise.reject(new Error('paymentMethodIds lists needed')) } if (!data.paymentMethodIds.length) { - return Promise.reject(new Error('One payment method is needed at least')); + return Promise.reject(new Error('One payment method is needed at least')) } - corbel.validate.value('id', this.id); + corbel.validate.value('id', this.id) return this.request({ method: corbel.request.method.POST, url: this._buildUri(this.uri, this.id, '/checkout'), data: data - }).then(function(res) { - return corbel.Services.getLocationId(res); - }); + }).then(function (res) { + return corbel.Services.getLocationId(res) + }) }, /** @@ -129,6 +128,5 @@ */ _buildUri: corbel.Ec._buildUri - }); - -})(); + }) +})() diff --git a/src/ec/productBuilder.js b/src/ec/productBuilder.js index a565941..82335e3 100644 --- a/src/ec/productBuilder.js +++ b/src/ec/productBuilder.js @@ -1,9 +1,9 @@ -//@exclude -'use strict'; -//@endexclude - -(function() { +// @exclude +'use strict' +// @endexclude +/* global corbel */ +;(function () { /** * Create a ProductBuilder for product managing requests. * @@ -11,11 +11,11 @@ * * @return {corbel.Ec.ProductBuilder} */ - corbel.Ec.prototype.product = function(id) { - var product = new ProductBuilder(id); - product.driver = this.driver; - return product; - }; + corbel.Ec.prototype.product = function (id) { + var product = new ProductBuilder(id) + product.driver = this.driver + return product + } /** * A builder for products management requests. * @@ -25,12 +25,11 @@ * @memberOf corbel.Ec.ProductBuilder */ var ProductBuilder = corbel.Ec.ProductBuilder = corbel.Services.inherit({ - - constructor: function(id) { + constructor: function (id) { if (id) { - this.id = id; + this.id = id } - this.uri = 'product'; + this.uri = 'product' }, /** @@ -53,15 +52,15 @@ * @return {Promise} A promise with the id of the created loanable resources or fails * with a {@link corbelError}. */ - create: function(product) { - console.log('ecInterface.product.create', product); + create: function (product) { + console.log('ecInterface.product.create', product) return this.request({ url: this._buildUri(this.uri), method: corbel.request.method.POST, data: product - }).then(function(res) { - return corbel.Services.getLocationId(res); - }); + }).then(function (res) { + return corbel.Services.getLocationId(res) + }) }, /** @@ -74,13 +73,13 @@ * * @return {Promise} A promise with product {Object} or fails with a {@link corbelError}. */ - get: function(params) { - console.log('ecInterface.product.get'); + get: function (params) { + console.log('ecInterface.product.get') return this.request({ url: this._buildUri(this.uri, this.id), method: corbel.request.method.GET, query: params ? corbel.utils.serializeParams(params) : null - }); + }) }, /** @@ -93,34 +92,33 @@ * * @return {Promise} A promise resolves to undefined (void) or fails with a {@link corbelError}. */ - update: function(product) { - console.log('ecInterface.product.update'); - corbel.validate.value('id', this.id); + update: function (product) { + console.log('ecInterface.product.update') + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id), method: corbel.request.method.PUT, data: product - }); + }) }, - /**Delete a product. + /* Delete a product. * * @method * @memberOf corbel.Ec.EcBuilder * * @return {Promise} A promise resolves to undefined (void) or fails with a {@link corbelError}. */ - delete: function() { - console.log('ecInterface.product.delete'); - corbel.validate.value('id', this.id); + delete: function () { + console.log('ecInterface.product.delete') + corbel.validate.value('id', this.id) return this.request({ url: this._buildUri(this.uri, this.id), method: corbel.request.method.DELETE - }); + }) }, _buildUri: corbel.Ec._buildUri - }); - -})(); + }) +})() diff --git a/src/evci/evci.js b/src/evci/evci.js index 2e4f42d..1527ccc 100644 --- a/src/evci/evci.js +++ b/src/evci/evci.js @@ -1,35 +1,32 @@ -(function() { - //@exclude - 'use strict'; - /*globals corbel */ - //@endexclude - - corbel.Evci = corbel.Object.inherit({ - - /** - * Create a new EventBuilder - * @param {String} type String - * @return {Events} - */ - constructor: function(driver) { - this.driver = driver; - }, - - event: function(type) { - return new corbel.Evci.EventBuilder(type, this.driver); - } - - }, { - - moduleName: 'evci', - defaultPort: 8086, - - create: function(driver) { - return new corbel.Evci(driver); - } - - }); - - return corbel.Evci; - -})(); +;(function () { + // @exclude + 'use strict' + /*globals corbel */ + // @endexclude + + corbel.Evci = corbel.Object.inherit({ + /** + * Create a new EventBuilder + * @param {String} type String + * @return {Events} + */ + constructor: function (driver) { + this.driver = driver + }, + + event: function (type) { + return new corbel.Evci.EventBuilder(type, this.driver) + } + + }, { + moduleName: 'evci', + defaultPort: 8086, + + create: function (driver) { + return new corbel.Evci(driver) + } + + }) + + return corbel.Evci +})() diff --git a/src/evci/eventBuilder.js b/src/evci/eventBuilder.js index 352ca26..6aec6bf 100644 --- a/src/evci/eventBuilder.js +++ b/src/evci/eventBuilder.js @@ -1,72 +1,71 @@ -//@exclude -'use strict'; -//@endexclude +// @exclude +'use strict' +// @endexclude +/* global corbel */ -(function() { +;(function () { + var EventBuilder = corbel.Evci.EventBuilder = corbel.Services.inherit({ + /** + * Creates a new EventBuilder + * @param {String} type + * @return {Events} + */ + constructor: function (type, driver) { + this.uri = 'event' + this.eventType = type + this.driver = driver + }, - var EventBuilder = corbel.Evci.EventBuilder = corbel.Services.inherit({ - /** - * Creates a new EventBuilder - * @param {String} type - * @return {Events} - */ - constructor: function(type, driver) { - this.uri = 'event'; - this.eventType = type; - this.driver = driver; - }, + /** + * Publish a new event. + * + * @method + * @memberOf corbel.Evci.EventBuilder + * + * @param {Object} eventData The data of the event. + * + * @return {Promise} A promise with the id of the created scope or fails + * with a {@link corbelError}. + */ + publish: function (eventData) { + if (!eventData) { + throw new Error('Send event require data') + } + console.log('evciInterface.publish', eventData) + corbel.validate.value('eventType', this.eventType) + return this.request({ + url: this._buildUri(this.uri, this.eventType), + method: corbel.request.method.POST, + data: eventData + }).then(function (res) { + res.data = corbel.Services.getLocationId(res) + return res + }) + }, - /** - * Publish a new event. - * - * @method - * @memberOf corbel.Evci.EventBuilder - * - * @param {Object} eventData The data of the event. - * - * @return {Promise} A promise with the id of the created scope or fails - * with a {@link corbelError}. - */ - publish: function(eventData) { - if (!eventData) { - throw new Error('Send event require data'); - } - console.log('evciInterface.publish', eventData); - corbel.validate.value('eventType', this.eventType); - return this.request({ - url: this._buildUri(this.uri,this.eventType), - method: corbel.request.method.POST, - data: eventData - }).then(function(res) { - res.data = corbel.Services.getLocationId(res); - return res; - }); - }, + _buildUri: function (path, eventType) { + var uri = '' + var urlBase = this.driver.config.getCurrentEndpoint(corbel.Evci.moduleName, this._buildPort(this.driver.config)) - _buildUri: function(path,eventType) { - var uri = ''; - var urlBase = this.driver.config.getCurrentEndpoint(corbel.Evci.moduleName, this._buildPort(this.driver.config)); + uri = urlBase + path + if (eventType) { + uri += '/' + eventType + } + return uri + }, - uri = urlBase + path; - if (eventType) { - uri += '/' + eventType; - } - return uri; - }, + _buildPort: function (config) { + return config.get('evciPort', null) || corbel.Evci.defaultPort + } - _buildPort: function(config) { - return config.get('evciPort', null) || corbel.Evci.defaultPort; - } + }, { + moduleName: 'evci', - }, { + create: function (driver) { + return new corbel.EventBuilder(driver) + } - moduleName: 'evci', + }) - create: function(driver) { - return new corbel.EventBuilder(driver); - } - - }); - - return EventBuilder; -})(); + return EventBuilder +})() diff --git a/src/iam/clientBuilder.js b/src/iam/clientBuilder.js index 8e16a3e..4f3db57 100644 --- a/src/iam/clientBuilder.js +++ b/src/iam/clientBuilder.js @@ -1,9 +1,9 @@ -//@exclude -'use strict'; -//@endexclude - -(function() { +// @exclude +'use strict' +// @endexclude +/* global corbel */ +;(function () { /** * Creates a ClientBuilder for client managing requests. * @@ -12,11 +12,11 @@ * * @return {corbel.Iam.ClientBuilder} */ - corbel.Iam.prototype.client = function(domainId, clientId) { - var client = new ClientBuilder(domainId, clientId); - client.driver = this.driver; - return client; - }; + corbel.Iam.prototype.client = function (domainId, clientId) { + var client = new ClientBuilder(domainId, clientId) + client.driver = this.driver + return client + } /** * A builder for client management requests. @@ -28,11 +28,10 @@ * @memberOf iam */ var ClientBuilder = corbel.Iam.ClientBuilder = corbel.Services.inherit({ - - constructor: function(domainId, clientId) { - this.domainId = domainId; - this.clientId = clientId; - this.uri = 'domain'; + constructor: function (domainId, clientId) { + this.domainId = domainId + this.clientId = clientId + this.uri = 'domain' }, /** @@ -55,16 +54,16 @@ * @return {Promise} A promise with the id of the created client or fails * with a {@link corbelError}. */ - create: function(client) { - console.log('iamInterface.domain.create', client); - corbel.validate.value('domainId', this.domainId); + create: function (client) { + console.log('iamInterface.domain.create', client) + corbel.validate.value('domainId', this.domainId) return this.request({ url: this._buildUri(this.uri + '/' + this.domainId + '/client'), method: corbel.request.method.POST, data: client - }).then(function(res) { - return corbel.Services.getLocationId(res); - }); + }).then(function (res) { + return corbel.Services.getLocationId(res) + }) }, /** @@ -77,13 +76,13 @@ * * @return {Promise} A promise with the client or fails with a {@link corbelError}. */ - get: function() { - console.log('iamInterface.domain.get', this.clientId); - corbel.validate.values(['domainId', 'clientId'], this); + get: function () { + console.log('iamInterface.domain.get', this.clientId) + corbel.validate.values(['domainId', 'clientId'], this) return this.request({ url: this._buildUri(this.uri + '/' + this.domainId + '/client/' + this.clientId), method: corbel.request.method.GET - }); + }) }, /** @@ -95,15 +94,15 @@ * @return {Promise} A promise with the domain or fails with a {@link corbelError}. * @see {@link corbel.util.serializeParams} to see a example of the params */ - getAll: function(params) { - corbel.validate.failIfIsDefined(this.clientId, 'This function not allowed client identifier'); - corbel.validate.value('domainId', this.domainId); - console.log('iamInterface.domain.getAll'); + getAll: function (params) { + corbel.validate.failIfIsDefined(this.clientId, 'This function not allowed client identifier') + corbel.validate.value('domainId', this.domainId) + console.log('iamInterface.domain.getAll') return this.request({ url: this._buildUri(this.uri + '/' + this.domainId + '/client'), method: corbel.request.method.GET, query: params ? corbel.utils.serializeParams(params) : null - }); + }) }, /** @@ -124,14 +123,14 @@ * * @return {Promise} A promise or fails with a {@link corbelError}. */ - update: function(client) { - console.log('iamInterface.domain.update', client); - corbel.validate.values(['domainId', 'clientId'], this); + update: function (client) { + console.log('iamInterface.domain.update', client) + corbel.validate.values(['domainId', 'clientId'], this) return this.request({ url: this._buildUri(this.uri + '/' + this.domainId + '/client/' + this.clientId), method: corbel.request.method.PUT, data: client - }); + }) }, /** @@ -144,18 +143,17 @@ * * @return {Promise} A promise or fails with a {@link corbelError}. */ - remove: function() { - console.log('iamInterface.domain.remove', this.domainId, this.clientId); - corbel.validate.values(['domainId', 'clientId'], this); + remove: function () { + console.log('iamInterface.domain.remove', this.domainId, this.clientId) + corbel.validate.values(['domainId', 'clientId'], this) return this.request({ url: this._buildUri(this.uri + '/' + this.domainId + '/client/' + this.clientId), method: corbel.request.method.DELETE - }); + }) }, _buildUri: corbel.Iam._buildUri - }); - -})(); + }) +})() diff --git a/src/iam/domainBuilder.js b/src/iam/domainBuilder.js index b0b323c..d200de3 100644 --- a/src/iam/domainBuilder.js +++ b/src/iam/domainBuilder.js @@ -1,9 +1,9 @@ -//@exclude -'use strict'; -//@endexclude - -(function() { +// @exclude +'use strict' +// @endexclude +/* global corbel */ +;(function () { /** * Creates a DomainBuilder for domain managing requests. * @@ -11,11 +11,11 @@ * * @return {corbel.Iam.DomainBuilder} */ - corbel.Iam.prototype.domain = function(domainId) { - var domain = new DomainBuilder(domainId); - domain.driver = this.driver; - return domain; - }; + corbel.Iam.prototype.domain = function (domainId) { + var domain = new DomainBuilder(domainId) + domain.driver = this.driver + return domain + } /** * A builder for domain management requests. @@ -26,10 +26,9 @@ * @memberOf iam */ var DomainBuilder = corbel.Iam.DomainBuilder = corbel.Services.inherit({ - - constructor: function(domainId) { - this.domainId = domainId; - this.uri = 'domain'; + constructor: function (domainId) { + this.domainId = domainId + this.uri = 'domain' }, _buildUri: corbel.Iam._buildUri, @@ -52,15 +51,15 @@ * @return {Promise} A promise with the id of the created domain or fails * with a {@link corbelError}. */ - create: function(domain) { - console.log('iamInterface.domain.create', domain); + create: function (domain) { + console.log('iamInterface.domain.create', domain) return this.request({ url: this._buildUri(this.uri), method: corbel.request.method.POST, data: domain - }).then(function(res) { - return corbel.Services.getLocationId(res); - }); + }).then(function (res) { + return corbel.Services.getLocationId(res) + }) }, /** @@ -71,17 +70,16 @@ * * @return {Promise} A promise with the domain or fails with a {@link corbelError}. */ - get: function() { - console.log('iamInterface.domain.get', this.domainId); - corbel.validate.value('domainId', this.domainId); + get: function () { + console.log('iamInterface.domain.get', this.domainId) + corbel.validate.value('domainId', this.domainId) return this.request({ url: this._buildUri(this.uri + '/' + this.domainId), method: corbel.request.method.GET - }); + }) }, - /** * Gets all domains. * @@ -91,14 +89,14 @@ * @return {Promise} A promise with the domain or fails with a {@link corbelError}. * @see {@link corbel.util.serializeParams} to see a example of the params */ - getAll: function(params) { - corbel.validate.failIfIsDefined(this.domainId, 'This function not allowed domain identifier'); - console.log('iamInterface.domain.getAll'); + getAll: function (params) { + corbel.validate.failIfIsDefined(this.domainId, 'This function not allowed domain identifier') + console.log('iamInterface.domain.getAll') return this.request({ url: this._buildUri(this.uri), method: corbel.request.method.GET, query: params ? corbel.utils.serializeParams(params) : null - }); + }) }, /** @@ -118,15 +116,15 @@ * * @return {Promise} A promise or fails with a {@link corbelError}. */ - update: function(domain) { - console.log('iamInterface.domain.update', domain); - corbel.validate.value('domainId', this.domainId); + update: function (domain) { + console.log('iamInterface.domain.update', domain) + corbel.validate.value('domainId', this.domainId) return this.request({ url: this._buildUri(this.uri + '/' + this.domainId), method: corbel.request.method.PUT, data: domain - }); + }) }, /** @@ -139,15 +137,14 @@ * * @return {Promise} A promise or fails with a {@link corbelError}. */ - remove: function() { - console.log('iamInterface.domain.remove', this.domainId); - corbel.validate.value('domainId', this.domainId); + remove: function () { + console.log('iamInterface.domain.remove', this.domainId) + corbel.validate.value('domainId', this.domainId) return this.request({ url: this._buildUri(this.uri + '/' + this.domainId), method: corbel.request.method.DELETE - }); + }) } - }); - -})(); + }) +})() diff --git a/src/iam/emailBuilder.js b/src/iam/emailBuilder.js index 9489de6..2ce7708 100644 --- a/src/iam/emailBuilder.js +++ b/src/iam/emailBuilder.js @@ -1,79 +1,78 @@ -//@exclude -'use strict'; -//@endexclude +// @exclude +'use strict' +// @endexclude +/* global corbel */ -(function() { +;(function () { + /** + * Creates a EmailBuilder for email requests + * @return {corbel.Iam.EmailBuilder} + */ + corbel.Iam.prototype.email = function () { + var builder + builder = new EmailBuilder() + builder.driver = this.driver + return builder + } - /** - * Creates a EmailBuilder for email requests - * @return {corbel.Iam.EmailBuilder} - */ - corbel.Iam.prototype.email = function() { - var builder; - builder = new EmailBuilder(); - builder.driver = this.driver; - return builder; - }; + /** + * Builder for creating requests of email + * @class + * @memberOf iam + */ + var EmailBuilder = corbel.Iam.EmailBuilder = corbel.Services.inherit({ + constructor: function () { + this.uri = 'email' + }, + + _buildUri: corbel.Iam._buildUri, /** - * Builder for creating requests of email - * @class - * @memberOf iam + * Gets a UserId. + * + * @method + * @memberOf corbel.Iam.EmailBuilder + * + * @param {String} email The email. + * + * @return {Promise} A promise with the user or fails with a {@link corbelError}. */ - var EmailBuilder = corbel.Iam.EmailBuilder = corbel.Services.inherit({ - - constructor: function() { - this.uri = 'email'; - }, + getUserId: function (email) { + console.log('iamInterface.email.getUserId', email) + corbel.validate.value('email', email) - _buildUri: corbel.Iam._buildUri, + return this.request({ + url: this._buildUri(this.uri, email), + method: corbel.request.method.GET + }) + }, - /** - * Gets a UserId. - * - * @method - * @memberOf corbel.Iam.EmailBuilder - * - * @param {String} email The email. - * - * @return {Promise} A promise with the user or fails with a {@link corbelError}. - */ - getUserId: function(email) { - console.log('iamInterface.email.getUserId', email); - corbel.validate.value('email', email); + /** + * Return availability endpoint. + * @method + * @memberOf corbel.Iam.EmailBuilder + * @param {String} email The email. + * @return {Promise} A promise which resolves into email availability boolean state. + */ + availability: function (email) { + console.log('iamInterface.email.availability', email) + corbel.validate.value('email', email) - return this.request({ - url: this._buildUri(this.uri, email), - method: corbel.request.method.GET - }); + return this.request({ + url: this._buildUri(this.uri, email), + method: corbel.request.method.HEAD + }).then( + function () { + return false }, - - /** - * Return availability endpoint. - * @method - * @memberOf corbel.Iam.EmailBuilder - * @param {String} email The email. - * @return {Promise} A promise which resolves into email availability boolean state. - */ - availability: function(email) { - console.log('iamInterface.email.availability', email); - corbel.validate.value('email', email); - - return this.request({ - url: this._buildUri(this.uri, email), - method: corbel.request.method.HEAD - }).then( - function() { - return false; - }, - function(response) { - if (response.status === 404) { - return true; - } else { - return Promise.reject(response); - } - } - ); + function (response) { + if (response.status === 404) { + return true + } else { + return Promise.reject(response) + } } - }); -})(); + ) + } + }) +})() diff --git a/src/iam/groupsBuilder.js b/src/iam/groupsBuilder.js index ed6b7e2..3b5c434 100644 --- a/src/iam/groupsBuilder.js +++ b/src/iam/groupsBuilder.js @@ -1,182 +1,179 @@ -//@exclude -'use strict'; -//@endexclude +// @exclude +'use strict' +// @endexclude +/* global corbel */ + +;(function () { + /** + * Creates a GroupBuilder for group requests + * + * @return {iam.GroupBuilder | iam.GroupsBuilder} + */ + corbel.Iam.prototype.group = function (id) { + var builder + + if (id) { + builder = new GroupBuilder(id) + } else { + builder = new GroupsBuilder() + } + + builder.driver = this.driver + return builder + } + + /** + * A builder for group requests without id (getAll and creation). + * + * @class + * @memberOf iam + */ + var GroupsBuilder = corbel.Iam.GroupsBuilder = corbel.Services.inherit({ + constructor: function () { + this.uri = 'group' + }, + + _buildUri: corbel.Iam._buildUri, -(function() { + /** + * Get all groups. + * + * @method + * @memberOf iam.GroupBuilder + * + * @param {Object} params Query parameters. + * + * @return {Promise} Q promise that resolves to an array of groups. + */ + getAll: function (params) { + console.log('iamInterface.groups.getAll') + return this.request({ + url: this._buildUri(this.uri), + method: corbel.request.method.GET, + query: params ? corbel.utils.serializeParams(params) : null, + withAuth: true + }) + }, /** - * Creates a GroupBuilder for group requests + * Create a group. * - * @return {iam.GroupBuilder | iam.GroupsBuilder} + * @method + * @memberOf iam.GroupBuilder + * + * @param {Object} data The group to create. + * @param {String} data.name Group name. + * @param {String} data.domain Group domain. + * @param {Array} data.scopes Group scopes. + * + * @return {Promise} A promise which resolves into the ID of the created group or fails with a {@link SilkRoadError}. */ - corbel.Iam.prototype.group = function(id) { - var builder; + create: function (data) { + console.log('iamInterface.groups.create', data) + return this.request({ + url: this._buildUri(this.uri), + method: corbel.request.method.POST, + data: data, + withAuth: true + }).then(function (res) { + return corbel.Services.getLocationId(res) + }) + } + + }) + + /** + * A builder for group requests. + * + * @class + * @memberOf iam + * @param {String} id The id of the group. + */ + var GroupBuilder = corbel.Iam.GroupBuilder = corbel.Services.inherit({ + constructor: function (id) { + this.uri = 'group' + this.id = id + }, + + _buildUri: corbel.Iam._buildUri, - if (id) { - builder = new GroupBuilder(id); - } else { - builder = new GroupsBuilder(); - } + /** + * Get a group. + * + * @method + * @memberOf corbel.Iam.GroupBuilder + * @return {Promise} Q promise that resolves to a group or rejects with a {@link SilkRoadError}. + */ + get: function () { + console.log('iamInterface.group.get') + corbel.validate.value('id', this.id) + return this.request({ + url: this._buildUri(this.uri, this.id), + method: corbel.request.method.GET, + withAuth: true + }) + }, - builder.driver = this.driver; - return builder; - }; + /** + * Add scopes to a group. + * + * @method + * @memberOf corbel.Iam.GroupBuilder + * + * @param {Array} scopes Group scopes to add. + * + * @return {Promise} A promise which resolves to undefined(void) or fails with a {@link SilkRoadError}. + */ + addScopes: function (scopes) { + console.log('iamInterface.group.addScopes', scopes) + corbel.validate.value('id', this.id) + + return this.request({ + url: this._buildUri(this.uri, this.id) + '/scopes', + method: corbel.request.method.PUT, + data: scopes, + withAuth: true + }) + }, /** - * A builder for group requests without id (getAll and creation). + * Remove a scope from a group. + * + * @method + * @memberOf iam.GroupBuilder * - * @class - * @memberOf iam + * @param {String} scope Group scope. + * + * @return {Promise} A promise which resolves to undefined(void) or fails with a {@link SilkRoadError}. */ - var GroupsBuilder = corbel.Iam.GroupsBuilder = corbel.Services.inherit({ - - constructor: function() { - this.uri = 'group'; - }, - - _buildUri: corbel.Iam._buildUri, - - /** - * Get all groups. - * - * @method - * @memberOf iam.GroupBuilder - * - * @param {Object} params Query parameters. - * - * @return {Promise} Q promise that resolves to an array of groups. - */ - getAll: function(params) { - console.log('iamInterface.groups.getAll'); - return this.request({ - url: this._buildUri(this.uri), - method: corbel.request.method.GET, - query: params ? corbel.utils.serializeParams(params) : null, - withAuth: true - }); - }, - - /** - * Create a group. - * - * @method - * @memberOf iam.GroupBuilder - * - * @param {Object} data The group to create. - * @param {String} data.name Group name. - * @param {String} data.domain Group domain. - * @param {Array} data.scopes Group scopes. - * - * @return {Promise} A promise which resolves into the ID of the created group or fails with a {@link SilkRoadError}. - */ - create: function(data) { - console.log('iamInterface.groups.create', data); - return this.request({ - url: this._buildUri(this.uri), - method: corbel.request.method.POST, - data: data, - withAuth: true - }).then(function(res) { - return corbel.Services.getLocationId(res); - }); - } - - }); + removeScope: function (scope) { + console.log('iamInterface.group.removeScope', scope) + corbel.validate.value('id', this.id) + + return this.request({ + url: this._buildUri(this.uri, this.id) + '/scopes/' + scope, + method: corbel.request.method.DELETE, + withAuth: true + }) + }, /** - * A builder for group requests. + * Delete a group. * - * @class - * @memberOf iam - * @param {String} id The id of the group. + * @method + * @memberOf iam.GroupBuilder + * @return {Promise} A promise which resolves to undefined(void) or fails with a {@link SilkRoadError}. */ - var GroupBuilder = corbel.Iam.GroupBuilder = corbel.Services.inherit({ - - constructor: function(id) { - this.uri = 'group'; - this.id = id; - }, - - _buildUri: corbel.Iam._buildUri, - - /** - * Get a group. - * - * @method - * @memberOf corbel.Iam.GroupBuilder - * @return {Promise} Q promise that resolves to a group or rejects with a {@link SilkRoadError}. - */ - get: function() { - console.log('iamInterface.group.get'); - corbel.validate.value('id', this.id); - return this.request({ - url: this._buildUri(this.uri, this.id), - method: corbel.request.method.GET, - withAuth: true - }); - }, - - /** - * Add scopes to a group. - * - * @method - * @memberOf corbel.Iam.GroupBuilder - * - * @param {Array} scopes Group scopes to add. - * - * @return {Promise} A promise which resolves to undefined(void) or fails with a {@link SilkRoadError}. - */ - addScopes: function(scopes) { - console.log('iamInterface.group.addScopes', scopes); - corbel.validate.value('id', this.id); - - return this.request({ - url: this._buildUri(this.uri, this.id) + '/scopes', - method: corbel.request.method.PUT, - data: scopes, - withAuth: true - }); - }, - - /** - * Remove a scope from a group. - * - * @method - * @memberOf iam.GroupBuilder - * - * @param {String} scope Group scope. - * - * @return {Promise} A promise which resolves to undefined(void) or fails with a {@link SilkRoadError}. - */ - removeScope: function(scope) { - console.log('iamInterface.group.removeScope', scope); - corbel.validate.value('id', this.id); - - return this.request({ - url: this._buildUri(this.uri, this.id) + '/scopes/' + scope, - method: corbel.request.method.DELETE, - withAuth: true - }); - }, - - /** - * Delete a group. - * - * @method - * @memberOf iam.GroupBuilder - * @return {Promise} A promise which resolves to undefined(void) or fails with a {@link SilkRoadError}. - */ - delete: function() { - console.log('iamInterface.group.delete'); - corbel.validate.value('id', this.id); - - return this.request({ - url: this._buildUri(this.uri, this.id), - method: corbel.request.method.DELETE, - withAuth: true - }); - } - - }); - -})(); + delete: function () { + console.log('iamInterface.group.delete') + corbel.validate.value('id', this.id) + + return this.request({ + url: this._buildUri(this.uri, this.id), + method: corbel.request.method.DELETE, + withAuth: true + }) + } + + }) +})() diff --git a/src/iam/iam.js b/src/iam/iam.js index 0b448b8..2350345 100644 --- a/src/iam/iam.js +++ b/src/iam/iam.js @@ -1,56 +1,55 @@ -//@exclude -'use strict'; -//@endexclude - -(function() { - - /** - * A module to make iam requests. - * @exports iam - * @namespace - * @memberof app.corbel - */ - - var Iam = corbel.Iam = function(driver) { - this.driver = driver; - }; - - Iam.moduleName = 'iam'; - Iam.defaultPort = 8082; - - Iam.create = function(driver) { - return new Iam(driver); - }; - - Iam.GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:jwt-bearer'; - Iam.AUD = 'http://iam.bqws.io'; - Iam.IAM_TOKEN = 'iamToken'; - Iam.IAM_TOKEN_SCOPES = 'iamScopes'; - Iam.IAM_DOMAIN = 'domain'; - - /** - * COMMON MIXINS - */ - - /** - * Private method to build a string uri - * @private - * @param {String} uri - * @param {String|Number} id - * @return {String} - */ - Iam._buildUri = function(uri, id) { - if (id) { - uri += '/' + id; - } - - var urlBase = this.driver.config.getCurrentEndpoint(Iam.moduleName, corbel.Iam._buildPort(this.driver.config)); - - return urlBase + uri; - }; - - Iam._buildPort = function(config) { - return config.get('iamPort', null) || corbel.Iam.defaultPort; - }; - -})(); +// @exclude +'use strict' +// @endexclude +/* global corbel */ + +;(function () { + /** + * A module to make iam requests. + * @exports iam + * @namespace + * @memberof app.corbel + */ + + var Iam = corbel.Iam = function (driver) { + this.driver = driver + } + + Iam.moduleName = 'iam' + Iam.defaultPort = 8082 + + Iam.create = function (driver) { + return new Iam(driver) + } + + Iam.GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:jwt-bearer' + Iam.AUD = 'http://iam.bqws.io' + Iam.IAM_TOKEN = 'iamToken' + Iam.IAM_TOKEN_SCOPES = 'iamScopes' + Iam.IAM_DOMAIN = 'domain' + + /** + * COMMON MIXINS + */ + + /** + * Private method to build a string uri + * @private + * @param {String} uri + * @param {String|Number} id + * @return {String} + */ + Iam._buildUri = function (uri, id) { + if (id) { + uri += '/' + id + } + + var urlBase = this.driver.config.getCurrentEndpoint(Iam.moduleName, corbel.Iam._buildPort(this.driver.config)) + + return urlBase + uri + } + + Iam._buildPort = function (config) { + return config.get('iamPort', null) || corbel.Iam.defaultPort + } +})() diff --git a/src/iam/scopeBuilder.js b/src/iam/scopeBuilder.js index c1698b2..da09752 100644 --- a/src/iam/scopeBuilder.js +++ b/src/iam/scopeBuilder.js @@ -1,97 +1,95 @@ -//@exclude -'use strict'; -//@endexclude +// @exclude +'use strict' +// @endexclude +/* global corbel */ -(function() { +;(function () { + /** + * Creates a ScopeBuilder for scope managing requests. + * @param {String} id Scope id. + * @return {corbel.Iam.ScopeBuilder} + */ + corbel.Iam.prototype.scope = function (id) { + var scope = new ScopeBuilder(id) + scope.driver = this.driver + return scope + } + + /** + * A builder for scope management requests. + * + * @param {String} id Scope id. + * + * @class + * @memberOf iam + */ + var ScopeBuilder = corbel.Iam.ScopeBuilder = corbel.Services.inherit({ + constructor: function (id) { + this.id = id + this.uri = 'scope' + }, + + _buildUri: corbel.Iam._buildUri, /** - * Creates a ScopeBuilder for scope managing requests. - * @param {String} id Scope id. - * @return {corbel.Iam.ScopeBuilder} + * Creates a new scope. + * + * @method + * @memberOf corbel.Iam.ScopeBuilder + * + * @param {Object} scope The scope. + * @param {Object} scope.rules Scope rules. + * @param {String} scope.type Scope type. + * @param {Object} scope.scopes Scopes for a composite scope. + * + * @return {Promise} A promise with the id of the created scope or fails + * with a {@link corbelError}. */ - corbel.Iam.prototype.scope = function(id) { - var scope = new ScopeBuilder(id); - scope.driver = this.driver; - return scope; - }; + create: function (scope) { + console.log('iamInterface.scope.create', scope) + return this.request({ + url: this._buildUri(this.uri), + method: corbel.request.method.POST, + data: scope + }).then(function (res) { + return corbel.Services.getLocationId(res) + }) + }, /** - * A builder for scope management requests. + * Gets a scope. * - * @param {String} id Scope id. + * @method + * @memberOf corbel.Iam.ScopeBuilder * - * @class - * @memberOf iam + * @return {Promise} A promise with the scope or fails with a {@link corbelError}. */ - var ScopeBuilder = corbel.Iam.ScopeBuilder = corbel.Services.inherit({ - - constructor: function(id) { - this.id = id; - this.uri = 'scope'; - }, + get: function () { + console.log('iamInterface.scope.get', this.id) + corbel.validate.value('id', this.id) - _buildUri: corbel.Iam._buildUri, + return this.request({ + url: this._buildUri(this.uri + '/' + this.id), + method: corbel.request.method.GET + }) + }, - /** - * Creates a new scope. - * - * @method - * @memberOf corbel.Iam.ScopeBuilder - * - * @param {Object} scope The scope. - * @param {Object} scope.rules Scope rules. - * @param {String} scope.type Scope type. - * @param {Object} scope.scopes Scopes for a composite scope. - * - * @return {Promise} A promise with the id of the created scope or fails - * with a {@link corbelError}. - */ - create: function(scope) { - console.log('iamInterface.scope.create', scope); - return this.request({ - url: this._buildUri(this.uri), - method: corbel.request.method.POST, - data: scope - }).then(function(res) { - return corbel.Services.getLocationId(res); - }); - }, - - /** - * Gets a scope. - * - * @method - * @memberOf corbel.Iam.ScopeBuilder - * - * @return {Promise} A promise with the scope or fails with a {@link corbelError}. - */ - get: function() { - console.log('iamInterface.scope.get', this.id); - corbel.validate.value('id', this.id); - - return this.request({ - url: this._buildUri(this.uri + '/' + this.id), - method: corbel.request.method.GET - }); - }, - - /** - * Removes a scope. - * - * @method - * @memberOf corbel.Iam.ScopeBuilder - * @return {Promise} A promise user or fails with a {@link corbelError}. - */ - remove: function() { - console.log('iamInterface.scope.remove', this.id); - corbel.validate.value('id', this.id); - - return this.request({ - url: this._buildUri(this.uri + '/' + this.id), - method: corbel.request.method.DELETE - }); - } + /** + * Removes a scope. + * + * @method + * @memberOf corbel.Iam.ScopeBuilder + * @return {Promise} A promise user or fails with a {@link corbelError}. + */ + remove: function () { + console.log('iamInterface.scope.remove', this.id) + corbel.validate.value('id', this.id) - }); + return this.request({ + url: this._buildUri(this.uri + '/' + this.id), + method: corbel.request.method.DELETE + }) + } -})(); + }) +})() diff --git a/src/iam/tokenBuilder.js b/src/iam/tokenBuilder.js index 19ff9a6..ff9aaab 100644 --- a/src/iam/tokenBuilder.js +++ b/src/iam/tokenBuilder.js @@ -1,187 +1,179 @@ -//@exclude -'use strict'; -//@endexclude - -(function() { - - /** - * Creates a TokenBuilder for token requests - * @return {corbel.Iam.TokenBuilder} - */ - corbel.Iam.prototype.token = function() { - var tokenBuilder = new TokenBuilder(this.driver); - tokenBuilder.driver = this.driver; - return tokenBuilder; - }; +// @exclude +'use strict' +// @endexclude +/* global corbel */ + +;(function () { + /** + * Creates a TokenBuilder for token requests + * @return {corbel.Iam.TokenBuilder} + */ + corbel.Iam.prototype.token = function () { + var tokenBuilder = new TokenBuilder(this.driver) + tokenBuilder.driver = this.driver + return tokenBuilder + } + + /** + * A builder for token requests + * @class + * @memberOf Iam + */ + var TokenBuilder = corbel.Iam.TokenBuilder = corbel.Services.inherit({ + constructor: function () { + this.uri = 'oauth/token' + }, + + _buildUri: corbel.Iam._buildUri, /** - * A builder for token requests - * @class - * @memberOf Iam + * Build a JWT with default driver config + * @param {Object} params + * @param {String} [params.secret] + * @param {Object} [params.claims] + * @param {String} [params.claims.iss] + * @param {String} [params.claims.aud] + * @param {String} [params.claims.scope] + * @return {String} JWT assertion */ - var TokenBuilder = corbel.Iam.TokenBuilder = corbel.Services.inherit({ - - constructor: function() { - this.uri = 'oauth/token'; - }, - - _buildUri: corbel.Iam._buildUri, - - /** - * Build a JWT with default driver config - * @param {Object} params - * @param {String} [params.secret] - * @param {Object} [params.claims] - * @param {String} [params.claims.iss] - * @param {String} [params.claims.aud] - * @param {String} [params.claims.scope] - * @return {String} JWT assertion - */ - _getJwt: function(params) { - params = params || {}; - params.claims = params.claims || {}; - - if (params.jwt) { - return params.jwt; - } - - var secret = params.secret || this.driver.config.get('clientSecret'); - params.claims.iss = params.claims.iss || this.driver.config.get('clientId'); - params.claims.aud = params.claims.aud || this.driver.config.get('audience', corbel.Iam.AUD); - params.claims.scope = params.claims.scope || this.driver.config.get('scopes', ''); - return corbel.jwt.generate(params.claims, secret); - }, - - _doGetTokenRequest: function(uri, params, setCookie) { - var args = { - url: this._buildUri(uri), - method: corbel.request.method.GET, - query: corbel.utils.param(corbel.utils.extend({ - assertion: this._getJwt(params), - 'grant_type': corbel.Iam.GRANT_TYPE - }, params.oauth)), - withCredentials: true - }; - - if (setCookie) { - args.headers = { - RequestCookie: 'true' - }; - } - - return corbel.request.send(args); - }, - - _doPostTokenRequest: function(uri, params, setCookie) { - var args = { - url: this._buildUri(uri), - method: corbel.request.method.POST, - data: { - assertion: this._getJwt(params), - 'grant_type': corbel.Iam.GRANT_TYPE - }, - contentType: 'application/x-www-form-urlencoded; charset=UTF-8', - withCredentials: true - }; - - if (setCookie) { - args.headers = { - RequestCookie: 'true' - }; - } - return corbel.request.send(args); + _getJwt: function (params) { + params = params || {} + params.claims = params.claims || {} + + if (params.jwt) { + return params.jwt + } + + var secret = params.secret || this.driver.config.get('clientSecret') + params.claims.iss = params.claims.iss || this.driver.config.get('clientId') + params.claims.aud = params.claims.aud || this.driver.config.get('audience', corbel.Iam.AUD) + params.claims.scope = params.claims.scope || this.driver.config.get('scopes', '') + return corbel.jwt.generate(params.claims, secret) + }, + + _doGetTokenRequest: function (uri, params, setCookie) { + var args = { + url: this._buildUri(uri), + method: corbel.request.method.GET, + query: corbel.utils.param(corbel.utils.extend({ + assertion: this._getJwt(params), + 'grant_type': corbel.Iam.GRANT_TYPE + }, params.oauth)), + withCredentials: true + } + + if (setCookie) { + args.headers = { + RequestCookie: 'true' + } + } + + return corbel.request.send(args) + }, + + _doPostTokenRequest: function (uri, params, setCookie) { + var args = { + url: this._buildUri(uri), + method: corbel.request.method.POST, + data: { + assertion: this._getJwt(params), + 'grant_type': corbel.Iam.GRANT_TYPE }, + contentType: 'application/x-www-form-urlencoded; charset=UTF-8', + withCredentials: true + } - /** - * Creates a token to connect with iam - * @method - * @memberOf corbel.Iam.TokenBuilder - * @param {Object} params Parameters to authorice - * @param {String} [params.jwt] Assertion to generate the token - * @param {Object} [params.claims] Claims to generate the token - * @param {Object} [params.oauth] Oauth specific params - * - * @param {string} params["oauth.service"] Service that will provide the authorization, e.g. facebook String * - * @param {string} params["oauth.code"] Code used in OAuth2 for exanging for a token String only if OAuth2 - * @param {string} params["oauth.access_token"] Access token used in OAuth2 for authentication. WARNING!! It is not recommended to pass an access token directly from the client, the oauth.code claim should be used instead. String - * @param {string} params["oauth.redirect_uri"] URI used by the client in OAuth2 to redirect the user when he does the login String only if OAuth2 - * @param {string} params["oauth.token"] Token returned by OAuth1 server to the client when the user does the login String only if OAuth1 - * @param {string} params["oauth.verifier"] Verifier returned by OAuth1 server to the client when the user does the login - * - * @param {Boolean} [setCookie] Sends 'RequestCookie' to server - * @return {Promise} Q promise that resolves to an AccessToken {Object} or rejects with a {@link corbelError} - */ - create: function(params, setCookie) { - params = params || {}; - // if there are oauth params this mean we should do use the GET verb - var promise; - try{ - if (params.oauth) { - promise = this._doGetTokenRequest(this.uri, params, setCookie); - } - - // otherwise we use the traditional POST verb. - promise = this._doPostTokenRequest(this.uri, params, setCookie); - - }catch(e){ - console.log('error', e); - return Promise.reject(e); - } - - var that = this; - return promise.then(function(response) { - that.driver.config.set(corbel.Iam.IAM_TOKEN, response.data); - that.driver.config.set(corbel.Iam.IAM_DOMAIN, corbel.jwt.decode(response.data.accessToken).domainId); - if (params.jwt) { - that.driver.config.set(corbel.Iam.IAM_TOKEN_SCOPES, corbel.jwt.decode(params.jwt).scope); - } - if (params.claims) { - if (params.claims.scope) { - that.driver.config.set(corbel.Iam.IAM_TOKEN_SCOPES, params.claims.scope); - } else { - that.driver.config.set(corbel.Iam.IAM_TOKEN_SCOPES, that.driver.config.get('scopes', '')); - } - } - return response; - }); - }, + if (setCookie) { + args.headers = { + RequestCookie: 'true' + } + } + return corbel.request.send(args) + }, - /** - * Refresh a token to connect with iam - * @method - * @memberOf corbel.Iam.TokenBuilder - * @param {String} [refresh_token] Token to refresh an AccessToken - * @param {String} [scopes] Scopes to the AccessToken - * @return {Promise} Q promise that resolves to an AccesToken {Object} or rejects with a {@link corbelError} - */ - refresh: function(refreshToken, scopes) { - // console.log('iamInterface.token.refresh', refreshToken); - // we need refresh token to refresh access token - corbel.validate.isValue(refreshToken, 'Refresh access token request must contains refresh token'); - // we need create default claims to refresh access token - var params = { - claims: { - 'scope': scopes, - 'refresh_token': refreshToken - } - }; - var that = this; - - try { - - return this._doPostTokenRequest(this.uri, params) - .then(function(response) { - that.driver.config.set(corbel.Iam.IAM_TOKEN, response.data); - return response; - }); - - } catch(e) { - console.log('error', e); - return Promise.reject(e); - } - + /** + * Creates a token to connect with iam + * @method + * @memberOf corbel.Iam.TokenBuilder + * @param {Object} params Parameters to authorice + * @param {String} [params.jwt] Assertion to generate the token + * @param {Object} [params.claims] Claims to generate the token + * @param {Object} [params.oauth] Oauth specific params + * + * @param {string} params["oauth.service"] Service that will provide the authorization, e.g. facebook String * + * @param {string} params["oauth.code"] Code used in OAuth2 for exanging for a token String only if OAuth2 + * @param {string} params["oauth.access_token"] Access token used in OAuth2 for authentication. WARNING!! It is not recommended to pass an access token directly from the client, the oauth.code claim should be used instead String + * @param {string} params["oauth.redirect_uri"] URI used by the client in OAuth2 to redirect the user when he does the login String only if OAuth2 + * @param {string} params["oauth.token"] Token returned by OAuth1 server to the client when the user does the login String only if OAuth1 + * @param {string} params["oauth.verifier"] Verifier returned by OAuth1 server to the client when the user does the login + * @param {Boolean} [setCookie] Sends 'RequestCookie' to server + * @return {Promise} Q promise that resolves to an AccessToken {Object} or rejects with a {@link corbelError} + */ + create: function (params, setCookie) { + params = params || {} + // if there are oauth params this mean we should do use the GET verb + var promise + try { + if (params.oauth) { + promise = this._doGetTokenRequest(this.uri, params, setCookie) } - }); + // otherwise we use the traditional POST verb. + promise = this._doPostTokenRequest(this.uri, params, setCookie) + } catch (e) { + console.log('error', e) + return Promise.reject(e) + } + + var that = this + return promise.then(function (response) { + that.driver.config.set(corbel.Iam.IAM_TOKEN, response.data) + that.driver.config.set(corbel.Iam.IAM_DOMAIN, corbel.jwt.decode(response.data.accessToken).domainId) + if (params.jwt) { + that.driver.config.set(corbel.Iam.IAM_TOKEN_SCOPES, corbel.jwt.decode(params.jwt).scope) + } + if (params.claims) { + if (params.claims.scope) { + that.driver.config.set(corbel.Iam.IAM_TOKEN_SCOPES, params.claims.scope) + } else { + that.driver.config.set(corbel.Iam.IAM_TOKEN_SCOPES, that.driver.config.get('scopes', '')) + } + } + return response + }) + }, -})(); \ No newline at end of file + /** + * Refresh a token to connect with iam + * @method + * @memberOf corbel.Iam.TokenBuilder + * @param {String} [refresh_token] Token to refresh an AccessToken + * @param {String} [scopes] Scopes to the AccessToken + * @return {Promise} Q promise that resolves to an AccesToken {Object} or rejects with a {@link corbelError} + */ + refresh: function (refreshToken, scopes) { + // console.log('iamInterface.token.refresh', refreshToken) + // we need refresh token to refresh access token + corbel.validate.isValue(refreshToken, 'Refresh access token request must contains refresh token') + // we need create default claims to refresh access token + var params = { + claims: { + 'scope': scopes, + 'refresh_token': refreshToken + } + } + var that = this + + try { + return this._doPostTokenRequest(this.uri, params) + .then(function (response) { + that.driver.config.set(corbel.Iam.IAM_TOKEN, response.data) + return response + }) + } catch (e) { + console.log('error', e) + return Promise.reject(e) + } + } + }) +})() diff --git a/src/iam/usernameBuilder.js b/src/iam/usernameBuilder.js index 8576761..a73cd01 100644 --- a/src/iam/usernameBuilder.js +++ b/src/iam/usernameBuilder.js @@ -1,75 +1,73 @@ -//@exclude -'use strict'; -//@endexclude +// @exclude +'use strict' +// @endexclude +/* global corbel */ -(function() { +;(function () { + /** + * Starts a username request + * @return {corbel.Iam.UsernameBuilder} The builder to create the request + */ + corbel.Iam.prototype.username = function () { + var username = new UsernameBuilder() + username.driver = this.driver + return username + } - /** - * Starts a username request - * @return {corbel.Iam.UsernameBuilder} The builder to create the request - */ - corbel.Iam.prototype.username = function() { - var username = new UsernameBuilder(); - username.driver = this.driver; - return username; - }; + /** + * Builder for creating requests of users name + * @class + * @memberOf iam + */ + var UsernameBuilder = corbel.Iam.UsernameBuilder = corbel.Services.inherit({ + constructor: function () { + this.uri = 'username' + }, + + _buildUri: corbel.Iam._buildUri, /** - * Builder for creating requests of users name - * @class - * @memberOf iam + * Return availability endpoint. + * @method + * @memberOf corbel.Iam.UsernameBuilder + * @param {String} username The username. + * @return {Promise} A promise which resolves into usename availability boolean state. */ - var UsernameBuilder = corbel.Iam.UsernameBuilder = corbel.Services.inherit({ - - constructor: function() { - this.uri = 'username'; - }, - - _buildUri: corbel.Iam._buildUri, - - /** - * Return availability endpoint. - * @method - * @memberOf corbel.Iam.UsernameBuilder - * @param {String} username The username. - * @return {Promise} A promise which resolves into usename availability boolean state. - */ - availability: function(username) { - console.log('iamInterface.username.availability', username); - corbel.validate.value('username', username); - return this.request({ - url: this._buildUri(this.uri, username), - method: corbel.request.method.HEAD - }).then(function() { - return false; - }).catch(function(response) { - if (response.status === 404) { - return true; - } else { - return Promise.reject(response); - } - }); - }, - - /** - * Gets a UserId. - * - * @method - * @memberOf corbel.Iam.UsernameBuilder - * - * @param {String} username The username. - * - * @return {Promise} A promise with the user or fails with a {@link corbelError}. - */ - getUserId: function(username) { - console.log('iamInterface.username.getUserId', username); - corbel.validate.value('username', username); - - return this.request({ - url: this._buildUri(this.uri, username), - method: corbel.request.method.GET - }); + availability: function (username) { + console.log('iamInterface.username.availability', username) + corbel.validate.value('username', username) + return this.request({ + url: this._buildUri(this.uri, username), + method: corbel.request.method.HEAD + }).then(function () { + return false + }).catch(function (response) { + if (response.status === 404) { + return true + } else { + return Promise.reject(response) } - }); + }) + }, + + /** + * Gets a UserId. + * + * @method + * @memberOf corbel.Iam.UsernameBuilder + * + * @param {String} username The username. + * + * @return {Promise} A promise with the user or fails with a {@link corbelError}. + */ + getUserId: function (username) { + console.log('iamInterface.username.getUserId', username) + corbel.validate.value('username', username) -})(); + return this.request({ + url: this._buildUri(this.uri, username), + method: corbel.request.method.GET + }) + } + }) +})() diff --git a/src/iam/usersBuilder.js b/src/iam/usersBuilder.js index 5060954..1b91f17 100644 --- a/src/iam/usersBuilder.js +++ b/src/iam/usersBuilder.js @@ -1,460 +1,457 @@ -//@exclude +// @exclude // jshint unused: false -'use strict'; -//@endexclude +'use strict' +// @endexclude +/* global corbel */ + +;(function () { + /* + * Starts a user request + * @param {string} [id=id|'me'] Id of the user to perform the request + * @return {corbel.Iam.UserBuilder|corbel.Iam.UserMeBuilder} The builder to create the request + */ + corbel.Iam.prototype.user = function (id) { + var builder + if (id === 'me') { + builder = new UserBuilder('me') + } else if (id) { + builder = new UserBuilder(id) + } else { + builder = new UserMeBuilder('me') + } + + builder.driver = this.driver + return builder + } + + /** + * Starts a users request + * @return {corbel.Iam.UserBuilder|corbel.Iam.UsersBuilder} The builder to create the request + */ + corbel.Iam.prototype.users = function () { + var builder = new UsersBuilder() + + builder.driver = this.driver + return builder + } + + /** + * getUser mixin for UserBuilder & UsersBuilder + * @param {string} uri + * @param {string} id + * @param {Bolean} postfix + * @return {Promise} + */ + corbel.Iam._getUser = function (method, uri, id, postfix) { + var url = (postfix ? this._buildUri(uri, id) + postfix : this._buildUri(uri, id)) + return this.request({ + url: url, + method: corbel.request.method.GET + }) + } + + /** + * Builder for a specific user requests + * @class + * @memberOf iam + * @param {string} id The id of the user + */ + var CommonUserBuilder = corbel.Iam.CommonUserBuilder = corbel.Services.inherit({ + constructor: function (id) { + this.uri = 'user' + this.id = id + }, + + _buildUri: corbel.Iam._buildUri, + _getUser: corbel.Iam._getUser, -(function() { + /** + * Gets the user + * @method + * @memberOf corbel.Iam.UserBuilder + * @return {Promise} Q promise that resolves to a User {Object} or rejects with a {@link corbelError} + */ + get: function () { + console.log('iamInterface.user.get') + corbel.validate.value('id', this.id) + return this._getUser(corbel.request.method.GET, this.uri, this.id) + }, + + /** + * Updates the user + * @method + * @memberOf corbel.Iam.UserBuilder + * @param {Object} The data to update + * @return {Promise} promise that resolves to undefined (void) or rejects with a {@link corbelError} + */ + _update: function (data) { + console.log('iamInterface.user.update', data) + corbel.validate.value('id', this.id) + + return this.request({ + url: this._buildUri(this.uri, this.id), + method: corbel.request.method.PUT, + data: data + }) + }, + + /** + * Deletes the user + * @method + * @memberOf corbel.Iam.UserBuilder + * @return {Promise} Q promise that resolves to undefined (void) or rejects with a {@link corbelError} + */ + _delete: function () { + console.log('iamInterface.user.delete') + corbel.validate.value('id', this.id) + + return this.request({ + url: this._buildUri(this.uri, this.id), + method: corbel.request.method.DELETE + }) + }, + + /** + * Sign Out the logged user. + * @example + * iam().user('me').signOut() + * @method + * @memberOf corbel.Iam.UsersBuilder + * @return {Promise} Q promise that resolves to a User {Object} or rejects with a {@link corbelError} + */ + _signOut: function () { + console.log('iamInterface.users.signOutMe') + corbel.validate.value('id', this.id) + + return this.request({ + url: this._buildUri(this.uri, this.id) + '/signout', + method: corbel.request.method.PUT + }) + }, + + /** + * disconnect the user, all his tokens are deleted + * @method + * @memberOf corbel.Iam.UserBuilder + * @return {Promise} Q promise that resolves to undefined (void) or rejects with a {@link corbelError} + */ + _disconnect: function () { + console.log('iamInterface.user.disconnect') + corbel.validate.value('id', this.id) + + return this.request({ + url: this._buildUri(this.uri, this.id) + '/disconnect', + method: corbel.request.method.PUT + }) + }, + + /** + * Adds an identity (link to an oauth server or social network) to the user + * @method + * @memberOf corbel.Iam.UserBuilder + * @param {Object} identity The data of the identity + * @param {string} oauthId The oauth ID of the user + * @param {string} oauthService The oauth service to connect (facebook, twitter, google, corbel) + * @return {Promise} Q promise that resolves to undefined (void) or rejects with a {@link corbelError} + */ + addIdentity: function (identity) { + // console.log('iamInterface.user.addIdentity', identity) + corbel.validate.isValue(identity, 'Missing identity') + corbel.validate.value('id', this.id) + + return this.request({ + url: this._buildUri(this.uri, this.id) + '/identity', + method: corbel.request.method.POST, + data: identity + }) + }, /** - * Starts a user request - * @param {string} [id=id|'me'] Id of the user to perform the request - * @return {corbel.Iam.UserBuilder|corbel.Iam.UserMeBuilder} The builder to create the request + * Get user identities (links to oauth servers or social networks) + * @method + * @memberOf corbel.Iam.UserBuilder + * @return {Promise} Q promise that resolves to {Array} of Identity or rejects with a {@link corbelError} */ - corbel.Iam.prototype.user = function(id) { - var builder; - if (id === 'me') { - builder = new UserBuilder('me'); - } - else if (id) { - builder = new UserBuilder(id); - } else { - builder = new UserMeBuilder('me'); - } - - builder.driver = this.driver; - return builder; - }; - - /** - * Starts a users request - * @return {corbel.Iam.UserBuilder|corbel.Iam.UsersBuilder} The builder to create the request + _getIdentities: function () { + console.log('iamInterface.user.getIdentities') + corbel.validate.value('id', this.id) + + return this.request({ + url: this._buildUri(this.uri, this.id) + '/identity', + method: corbel.request.method.GET + }) + }, + /** + * User device register + * @method + * @memberOf corbel.Iam.UserBuilder + * @param {Object} data The device data + * @param {Object} data.URI The device token + * @param {Object} data.name The device name + * @param {Object} data.type The device type (Android, Apple) + * @return {Promise} Q promise that resolves to a User {Object} or rejects with a {@link corbelError} */ - corbel.Iam.prototype.users = function() { - var builder = new UsersBuilder(); + _registerDevice: function (data) { + console.log('iamInterface.user.registerDevice') + corbel.validate.value('id', this.id) + + return this.request({ + url: this._buildUri(this.uri, this.id) + '/devices', + method: corbel.request.method.PUT, + data: data + }).then(function (res) { + return corbel.Services.getLocationId(res) + }) + }, + + /** + * Get device + * @method + * @memberOf corbel.Iam.UserBuilder + * @param {string} deviceId The device id + * @return {Promise} Q promise that resolves to a Device {Object} or rejects with a {@link corbelError} + */ + _getDevice: function (deviceId) { + console.log('iamInterface.user.getDevice') + corbel.validate.values(['id', 'deviceId'], { + 'id': this.id, + 'deviceId': deviceId + }) + + return this.request({ + url: this._buildUri(this.uri, this.id) + '/devices/' + deviceId, + method: corbel.request.method.GET + }) + }, + + /** + * Get all user devices + * @method + * @memberOf corbel.Iam.UserBuilder + * @return {Promise} Q promise that resolves to a Device {Object} or rejects with a {@link corbelError} + */ + _getDevices: function () { + console.log('iamInterface.user.getDevices') + corbel.validate.value('id', this.id) + return this.request({ + url: this._buildUri(this.uri, this.id) + '/devices/', + method: corbel.request.method.GET + }) + }, + + /** + * Delete user device + * @method + * @memberOf corbel.Iam.UserBuilder + * @param {string} deviceId The device id + * @return {Promise} Q promise that resolves to a Device {Object} or rejects with a {@link corbelError} + */ + _deleteDevice: function (deviceId) { + console.log('iamInterface.user.deleteDevice') + corbel.validate.value('deviceId', deviceId) + return this.request({ + url: this._buildUri(this.uri, this.id) + '/devices/' + deviceId, + method: corbel.request.method.DELETE + }) + }, + /** + * Get user profiles + * @method + * @memberOf corbel.Iam.UserBuilder + * @return {Promise} Q promise that resolves to a User Profile or rejects with a {@link corbelError} + */ + _getProfile: function () { + console.log('iamInterface.user.getProfile') + corbel.validate.value('id', this.id) + + return this.request({ + url: this._buildUri(this.uri, this.id) + '/profile', + method: corbel.request.method.GET + }) + }, + + /** + * Add groups to the user + * @method + * @memberOf iam.UserBuilder + * @param {Object} groups The data of the groups + * @return {Promise} Q promise that resolves to undefined (void) or rejects with a {@link SilkRoadError} + */ + addGroups: function (groups) { + console.log('iamInterface.user.addGroups') + corbel.validate.value('id', this.id) + + return this.request({ + url: this._buildUri(this.uri, this.id) + '/groups', + method: corbel.request.method.PUT, + data: groups + }) + }, - builder.driver = this.driver; - return builder; - }; + /** + * Delete group to user + * @method + * @memberOf iam.UserBuilder + * @param {Object} groups The data of the groups + * @return {Promise} Q promise that resolves to undefined (void) or rejects with a {@link SilkRoadError} + */ + _deleteGroup: function (group) { + console.log('iamInterface.user.deleteGroup') + corbel.validate.values(['id', 'group'], { + 'id': this.id, + 'group': group + }) + return this.request({ + url: this._buildUri(this.uri, this.id) + '/groups/' + group, + method: corbel.request.method.DELETE + }) + } + + }) + + var UserBuilder = CommonUserBuilder.inherit({ + deleteGroup: function () { + return this._deleteGroup.apply(this, arguments) + }, + update: function () { + return this._update.apply(this, arguments) + }, + delete: function () { + return this._delete.apply(this, arguments) + }, + registerDevice: function () { + return this._registerDevice.apply(this, arguments) + }, + getDevices: function () { + return this._getDevices.apply(this, arguments) + }, + getDevice: function () { + return this._getDevice.apply(this, arguments) + }, + deleteDevice: function () { + return this._deleteDevice.apply(this, arguments) + }, + signOut: function () { + return this._signOut.apply(this, arguments) + }, + disconnect: function () { + return this._disconnect.apply(this, arguments) + }, + getIdentities: function () { + return this._getIdentities.apply(this, arguments) + }, + getProfile: function () { + return this._getProfile.apply(this, arguments) + } + }) + + var UserMeBuilder = CommonUserBuilder.inherit({ + deleteMyGroup: function () { + return this._deleteGroup.apply(this, arguments) + }, + updateMe: function () { + return this._update.apply(this, arguments) + }, + deleteMe: function () { + return this._delete.apply(this, arguments) + }, + registerMyDevice: function () { + return this._registerDevice.apply(this, arguments) + }, + getMyDevices: function () { + return this._getDevices.apply(this, arguments) + }, + getMyDevice: function () { + return this._getDevice.apply(this, arguments) + }, + deleteMyDevice: function () { + return this._deleteDevice.apply(this, arguments) + }, + signOutMe: function () { + return this._signOut.apply(this, arguments) + }, + disconnectMe: function () { + return this._disconnect.apply(this, arguments) + }, + getMyIdentities: function () { + return this._getIdentities.apply(this, arguments) + }, + getMyProfile: function () { + return this._getProfile.apply(this, arguments) + } + }) + + /** + * Builder for creating requests of users collection + * @class + * @memberOf iam + */ + var UsersBuilder = corbel.Iam.UsersBuilder = corbel.Services.inherit({ + constructor: function () { + this.uri = 'user' + }, + + _buildUri: corbel.Iam._buildUri, /** - * getUser mixin for UserBuilder & UsersBuilder - * @param {string} uri - * @param {string} id - * @param {Bolean} postfix - * @return {Promise} + * Sends a reset password email to the email address recived. + * @method + * @memberOf oauth.UsersBuilder + * @param {string} userEmailToReset The email to send the message + * @return {Promise} Q promise that resolves to undefined (void) or rejects with a {@link corbelError} */ - corbel.Iam._getUser = function(method, uri, id, postfix) { - var url = (postfix ? this._buildUri(uri, id) + postfix : this._buildUri(uri, id)); - return this.request({ - url: url, - method: corbel.request.method.GET - }); - }; + sendResetPasswordEmail: function (userEmailToReset) { + console.log('iamInterface.users.sendResetPasswordEmail', userEmailToReset) + var query = 'email=' + userEmailToReset + return this.request({ + url: this._buildUri(this.uri + '/resetPassword'), + method: corbel.request.method.GET, + query: query + }).then(function (res) { + return corbel.Services.getLocationId(res) + }) + }, /** - * Builder for a specific user requests - * @class - * @memberOf iam - * @param {string} id The id of the user + * Creates a new user. + * @method + * @memberOf corbel.Iam.UsersBuilder + * @param {Object} data The user data. + * @return {Promise} A promise which resolves into the ID of the created user or fails with a {@link corbelError}. */ - var CommonUserBuilder = corbel.Iam.CommonUserBuilder = corbel.Services.inherit({ - - constructor: function(id) { - this.uri = 'user'; - this.id = id; - }, - - _buildUri: corbel.Iam._buildUri, - _getUser: corbel.Iam._getUser, - - /** - * Gets the user - * @method - * @memberOf corbel.Iam.UserBuilder - * @return {Promise} Q promise that resolves to a User {Object} or rejects with a {@link corbelError} - */ - get: function() { - console.log('iamInterface.user.get'); - corbel.validate.value('id', this.id); - return this._getUser(corbel.request.method.GET, this.uri, this.id); - }, - - /** - * Updates the user - * @method - * @memberOf corbel.Iam.UserBuilder - * @param {Object} data The data to update - * @return {Promise} Q promise that resolves to undefined (void) or rejects with a {@link corbelError} - */ - _update: function(data) { - console.log('iamInterface.user.update', data); - corbel.validate.value('id', this.id); - - return this.request({ - url: this._buildUri(this.uri, this.id), - method: corbel.request.method.PUT, - data: data - }); - }, - - /** - * Deletes the user - * @method - * @memberOf corbel.Iam.UserBuilder - * @return {Promise} Q promise that resolves to undefined (void) or rejects with a {@link corbelError} - */ - _delete: function() { - console.log('iamInterface.user.delete'); - corbel.validate.value('id', this.id); - - return this.request({ - url: this._buildUri(this.uri, this.id), - method: corbel.request.method.DELETE - }); - }, - - /** - * Sign Out the logged user. - * @example - * iam().user('me').signOut(); - * @method - * @memberOf corbel.Iam.UsersBuilder - * @return {Promise} Q promise that resolves to a User {Object} or rejects with a {@link corbelError} - */ - _signOut: function() { - console.log('iamInterface.users.signOutMe'); - corbel.validate.value('id', this.id); - - return this.request({ - url: this._buildUri(this.uri, this.id) + '/signout', - method: corbel.request.method.PUT - }); - }, - - /** - * disconnect the user, all his tokens are deleted - * @method - * @memberOf corbel.Iam.UserBuilder - * @return {Promise} Q promise that resolves to undefined (void) or rejects with a {@link corbelError} - */ - _disconnect: function() { - console.log('iamInterface.user.disconnect'); - corbel.validate.value('id', this.id); - - return this.request({ - url: this._buildUri(this.uri, this.id) + '/disconnect', - method: corbel.request.method.PUT - }); - }, - - /** - * Adds an identity (link to an oauth server or social network) to the user - * @method - * @memberOf corbel.Iam.UserBuilder - * @param {Object} identity The data of the identity - * @param {string} oauthId The oauth ID of the user - * @param {string} oauthService The oauth service to connect (facebook, twitter, google, corbel) - * @return {Promise} Q promise that resolves to undefined (void) or rejects with a {@link corbelError} - */ - addIdentity: function(identity) { - // console.log('iamInterface.user.addIdentity', identity); - corbel.validate.isValue(identity, 'Missing identity'); - corbel.validate.value('id', this.id); - - return this.request({ - url: this._buildUri(this.uri, this.id) + '/identity', - method: corbel.request.method.POST, - data: identity - }); - }, - - /** - * Get user identities (links to oauth servers or social networks) - * @method - * @memberOf corbel.Iam.UserBuilder - * @return {Promise} Q promise that resolves to {Array} of Identity or rejects with a {@link corbelError} - */ - _getIdentities: function() { - console.log('iamInterface.user.getIdentities'); - corbel.validate.value('id', this.id); - - return this.request({ - url: this._buildUri(this.uri, this.id) + '/identity', - method: corbel.request.method.GET - }); - }, - /** - * User device register - * @method - * @memberOf corbel.Iam.UserBuilder - * @param {Object} data The device data - * @param {Object} data.URI The device token - * @param {Object} data.name The device name - * @param {Object} data.type The device type (Android, Apple) - * @return {Promise} Q promise that resolves to a User {Object} or rejects with a {@link corbelError} - */ - _registerDevice: function(data) { - console.log('iamInterface.user.registerDevice'); - corbel.validate.value('id', this.id); - - return this.request({ - url: this._buildUri(this.uri, this.id) + '/devices', - method: corbel.request.method.PUT, - data: data - }).then(function(res) { - return corbel.Services.getLocationId(res); - }); - }, - - /** - * Get device - * @method - * @memberOf corbel.Iam.UserBuilder - * @param {string} deviceId The device id - * @return {Promise} Q promise that resolves to a Device {Object} or rejects with a {@link corbelError} - */ - _getDevice: function(deviceId) { - console.log('iamInterface.user.getDevice'); - corbel.validate.values(['id', 'deviceId'], { - 'id':this.id, - 'deviceId': deviceId - }); - - return this.request({ - url: this._buildUri(this.uri, this.id) + '/devices/' + deviceId, - method: corbel.request.method.GET - }); - }, - - /** - * Get all user devices - * @method - * @memberOf corbel.Iam.UserBuilder - * @return {Promise} Q promise that resolves to a Device {Object} or rejects with a {@link corbelError} - */ - _getDevices: function() { - console.log('iamInterface.user.getDevices'); - corbel.validate.value('id', this.id); - return this.request({ - url: this._buildUri(this.uri, this.id) + '/devices/', - method: corbel.request.method.GET - }); - }, - - /** - * Delete user device - * @method - * @memberOf corbel.Iam.UserBuilder - * @param {string} deviceId The device id - * @return {Promise} Q promise that resolves to a Device {Object} or rejects with a {@link corbelError} - */ - _deleteDevice: function(deviceId) { - console.log('iamInterface.user.deleteDevice'); - corbel.validate.value('deviceId', deviceId); - return this.request({ - url: this._buildUri(this.uri, this.id) + '/devices/' + deviceId, - method: corbel.request.method.DELETE - }); - }, - /** - * Get user profiles - * @method - * @memberOf corbel.Iam.UserBuilder - * @return {Promise} Q promise that resolves to a User Profile or rejects with a {@link corbelError} - */ - _getProfile: function() { - console.log('iamInterface.user.getProfile'); - corbel.validate.value('id', this.id); - - return this.request({ - url: this._buildUri(this.uri, this.id) + '/profile', - method: corbel.request.method.GET - }); - }, - - /** - * Add groups to the user - * @method - * @memberOf iam.UserBuilder - * @param {Object} groups The data of the groups - * @return {Promise} Q promise that resolves to undefined (void) or rejects with a {@link SilkRoadError} - */ - addGroups: function(groups) { - console.log('iamInterface.user.addGroups'); - corbel.validate.value('id', this.id); - - return this.request({ - url: this._buildUri(this.uri, this.id) + '/groups', - method: corbel.request.method.PUT, - data: groups - }); - }, - - /** - * Delete group to user - * @method - * @memberOf iam.UserBuilder - * @param {Object} groups The data of the groups - * @return {Promise} Q promise that resolves to undefined (void) or rejects with a {@link SilkRoadError} - */ - _deleteGroup: function(group) { - console.log('iamInterface.user.deleteGroup'); - corbel.validate.values(['id', 'group'], { - 'id':this.id, - 'group': group - }); - return this.request({ - url: this._buildUri(this.uri, this.id) + '/groups/'+group, - method: corbel.request.method.DELETE - }); - } - - }); - - var UserBuilder = corbel.Iam.CommonUserBuilder.inherit({ - deleteGroup : function(){ - return this._deleteGroup.apply(this, arguments); - }, - update : function(){ - return this._update.apply(this, arguments); - }, - delete :function(){ - return this._delete.apply(this, arguments); - }, - registerDevice :function(){ - return this._registerDevice.apply(this, arguments); - }, - getDevices :function(){ - return this._getDevices.apply(this, arguments); - }, - getDevice :function(){ - return this._getDevice.apply(this, arguments); - }, - deleteDevice :function(){ - return this._deleteDevice.apply(this, arguments); - }, - signOut :function(){ - return this._signOut.apply(this, arguments); - }, - disconnect :function(){ - return this._disconnect.apply(this, arguments); - }, - getIdentities :function(){ - return this._getIdentities.apply(this, arguments); - }, - getProfile : function(){ - return this._getProfile.apply(this, arguments); - } - }); - - var UserMeBuilder = corbel.Iam.CommonUserBuilder.inherit({ - deleteMyGroup : function(){ - return this._deleteGroup.apply(this, arguments); - }, - updateMe : function(){ - return this._update.apply(this, arguments); - }, - deleteMe :function(){ - return this._delete.apply(this, arguments); - }, - registerMyDevice :function(){ - return this._registerDevice.apply(this, arguments); - }, - getMyDevices :function(){ - return this._getDevices.apply(this, arguments); - }, - getMyDevice :function(){ - return this._getDevice.apply(this, arguments); - }, - deleteMyDevice :function(){ - return this._deleteDevice.apply(this, arguments); - }, - signOutMe :function(){ - return this._signOut.apply(this, arguments); - }, - disconnectMe :function(){ - return this._disconnect.apply(this, arguments); - }, - getMyIdentities :function(){ - return this._getIdentities.apply(this, arguments); - }, - getMyProfile : function(){ - return this._getProfile.apply(this, arguments); - } - }); + create: function (data) { + console.log('iamInterface.users.create', data) + return this.request({ + url: this._buildUri(this.uri), + method: corbel.request.method.POST, + data: data + }).then(function (res) { + return corbel.Services.getLocationId(res) + }) + }, /** - * Builder for creating requests of users collection - * @class - * @memberOf iam + * Gets all users of the current domain + * @method + * @memberOf corbel.Iam.UsersBuilder + * @return {Promise} Q promise that resolves to an {Array} of Users or rejects with a {@link corbelError} */ - var UsersBuilder = corbel.Iam.UsersBuilder = corbel.Services.inherit({ - - constructor: function() { - this.uri = 'user'; - }, - - _buildUri: corbel.Iam._buildUri, - - /** - * Sends a reset password email to the email address recived. - * @method - * @memberOf oauth.UsersBuilder - * @param {string} userEmailToReset The email to send the message - * @return {Promise} Q promise that resolves to undefined (void) or rejects with a {@link corbelError} - */ - sendResetPasswordEmail: function(userEmailToReset) { - console.log('iamInterface.users.sendResetPasswordEmail', userEmailToReset); - var query = 'email=' + userEmailToReset; - return this.request({ - url: this._buildUri(this.uri + '/resetPassword'), - method: corbel.request.method.GET, - query: query - }).then(function(res) { - return corbel.Services.getLocationId(res); - }); - }, - - /** - * Creates a new user. - * @method - * @memberOf corbel.Iam.UsersBuilder - * @param {Object} data The user data. - * @return {Promise} A promise which resolves into the ID of the created user or fails with a {@link corbelError}. - */ - create: function(data) { - console.log('iamInterface.users.create', data); - return this.request({ - url: this._buildUri(this.uri), - method: corbel.request.method.POST, - data: data - }).then(function(res) { - return corbel.Services.getLocationId(res); - }); - }, - - /** - * Gets all users of the current domain - * @method - * @memberOf corbel.Iam.UsersBuilder - * @return {Promise} Q promise that resolves to an {Array} of Users or rejects with a {@link corbelError} - */ - get: function(params) { - console.log('iamInterface.users.get', params); - return this.request({ - url: this._buildUri(this.uri), - method: corbel.request.method.GET, - query: params ? corbel.utils.serializeParams(params) : null - }); - }, - - getProfiles: function(params) { - console.log('iamInterface.users.getProfiles', params); - return this.request({ - url: this._buildUri(this.uri) + '/profile', - method: corbel.request.method.GET, - query: params ? corbel.utils.serializeParams(params) : null //TODO cambiar por util e implementar dicho metodo - }); - } - }); -})(); + get: function (params) { + console.log('iamInterface.users.get', params) + return this.request({ + url: this._buildUri(this.uri), + method: corbel.request.method.GET, + query: params ? corbel.utils.serializeParams(params) : null + }) + }, + + getProfiles: function (params) { + console.log('iamInterface.users.getProfiles', params) + return this.request({ + url: this._buildUri(this.uri) + '/profile', + method: corbel.request.method.GET, + query: params ? corbel.utils.serializeParams(params) : null // TODO cambiar por util e implementar dicho metodo + }) + } + }) +})() diff --git a/src/jwt.js b/src/jwt.js index de84b36..79a9e6a 100644 --- a/src/jwt.js +++ b/src/jwt.js @@ -1,125 +1,123 @@ /* jshint camelcase:false */ -//@exclude -'use strict'; -//@endexclude - -(function() { - - var jwt = corbel.jwt = { - - EXPIRATION: 3500, - ALGORITHM: 'HS256', - TYP: 'JWT', - VERSION: '1.0.0', - - /** - * JWT-HmacSHA256 generator - * http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html - * @param {Object} claims Specific claims to include in the JWT (iss, aud, exp, scope, ...) - * @param {String} secret String with the client assigned secret - * @param {Object} [alg='corbel.jwt.ALGORITHM'] Object with the algorithm type - * @return {String} jwt JWT string - */ - generate: function(claims, secret, alg) { - claims = claims || {}; - claims.exp = claims.exp || jwt._generateExp(); - - if (!claims.iss) { - throw new Error('jwt:undefined:iss'); - } - if (!claims.aud) { - throw new Error('jwt:undefined:aud'); - } - - return jwt._generate(claims, secret, alg); - }, - - _generate: function(claims, secret, alg){ - alg = alg || jwt.ALGORITHM; - - // Ensure claims specific order - var claimsKeys = [ - 'iss', - 'aud', - 'exp', - 'scope', - 'prn', - 'version', - 'refresh_token', - 'request_domain', - - 'basic_auth.username', - 'basic_auth.password', - - 'device_id' - ]; - - var finalClaims = {}; - claimsKeys.forEach(function(key) { - if (claims[key]) { - finalClaims[key] = claims[key]; - } - }); - - corbel.utils.extend(finalClaims, claims); - - if (Array.isArray(finalClaims.scope)) { - finalClaims.scope = finalClaims.scope.join(' '); - } - - var bAlg = corbel.cryptography.rstr2b64(corbel.cryptography.str2rstr_utf8(JSON.stringify({ - typ: jwt.TYP, - alg: alg - }))), - bClaims = corbel.cryptography.rstr2b64(corbel.cryptography.str2rstr_utf8(JSON.stringify(finalClaims))), - segment = bAlg + '.' + bClaims, - assertion = corbel.cryptography.b64tob64u(corbel.cryptography.b64_hmac_sha256(secret, segment)); - - return segment + '.' + assertion; - }, - - _generateExp: function() { - return Math.round((new Date().getTime() / 1000)) + jwt.EXPIRATION; - }, - - decode: function(assertion) { - var serialize; - if (corbel.Config.isNode) { - // node environment - serialize = require('atob'); - } else { - serialize = root.atob; - } - var decoded = assertion.split('.'); - - try { - decoded[0] = JSON.parse(serialize(decoded[0])); - } catch (e) { - decoded[0] = false; - } - - try { - decoded[1] = JSON.parse(serialize(decoded[1])); - } catch (e) { - decoded[1] = false; - } - - if (!decoded[0] && !decoded[1]) { - throw new Error('corbel:jwt:decode:invalid_assertion'); - } - - decoded[0] = decoded[0] || {}; - decoded[1] = decoded[1] || {}; - - Object.keys(decoded[1]).forEach(function(key) { - decoded[0][key] = decoded[1][key]; - }); - - return decoded[0]; +// @exclude +'use strict' +// @endexclude +/* global corbel */ + +;(function () { + var jwt = corbel.jwt = { + EXPIRATION: 3500, + ALGORITHM: 'HS256', + TYP: 'JWT', + VERSION: '1.0.0', + + /** + * JWT-HmacSHA256 generator + * http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html + * @param {Object} claims Specific claims to include in the JWT (iss, aud, exp, scope, ...) + * @param {String} secret String with the client assigned secret + * @param {Object} [alg='corbel.jwt.ALGORITHM'] Object with the algorithm type + * @return {String} jwt JWT string + */ + generate: function (claims, secret, alg) { + claims = claims || {} + claims.exp = claims.exp || jwt._generateExp() + + if (!claims.iss) { + throw new Error('jwt:undefined:iss') + } + if (!claims.aud) { + throw new Error('jwt:undefined:aud') + } + + return jwt._generate(claims, secret, alg) + }, + + _generate: function (claims, secret, alg) { + alg = alg || jwt.ALGORITHM + + // Ensure claims specific order + var claimsKeys = [ + 'iss', + 'aud', + 'exp', + 'scope', + 'prn', + 'version', + 'refresh_token', + 'request_domain', + + 'basic_auth.username', + 'basic_auth.password', + + 'device_id' + ] + + var finalClaims = {} + claimsKeys.forEach(function (key) { + if (claims[key]) { + finalClaims[key] = claims[key] } - - }; - - return jwt; - -})(); \ No newline at end of file + }) + + corbel.utils.extend(finalClaims, claims) + + if (Array.isArray(finalClaims.scope)) { + finalClaims.scope = finalClaims.scope.join(' ') + } + + var bAlg = corbel.cryptography.rstr2b64(corbel.cryptography.str2rstr_utf8(JSON.stringify({ + typ: jwt.TYP, + alg: alg + }))) + var bClaims = corbel.cryptography.rstr2b64(corbel.cryptography.str2rstr_utf8(JSON.stringify(finalClaims))) + var segment = bAlg + '.' + bClaims + var assertion = corbel.cryptography.b64tob64u(corbel.cryptography.b64_hmac_sha256(secret, segment)) + + return segment + '.' + assertion + }, + + _generateExp: function () { + return Math.round((new Date().getTime() / 1000)) + jwt.EXPIRATION + }, + + decode: function (assertion) { + var serialize + if (corbel.Config.isNode) { + // node environment + serialize = require('atob') + } else { + serialize = root.atob + } + var decoded = assertion.split('.') + + try { + decoded[0] = JSON.parse(serialize(decoded[0])) + } catch (e) { + decoded[0] = false + } + + try { + decoded[1] = JSON.parse(serialize(decoded[1])) + } catch (e) { + decoded[1] = false + } + + if (!decoded[0] && !decoded[1]) { + throw new Error('corbel:jwt:decode:invalid_assertion') + } + + decoded[0] = decoded[0] || {} + decoded[1] = decoded[1] || {} + + Object.keys(decoded[1]).forEach(function (key) { + decoded[0][key] = decoded[1][key] + }) + + return decoded[0] + } + + } + + return jwt +})() diff --git a/src/notifications/notifications.js b/src/notifications/notifications.js index 31c53d2..78f08fc 100644 --- a/src/notifications/notifications.js +++ b/src/notifications/notifications.js @@ -1,35 +1,32 @@ -(function() { - //@exclude - 'use strict'; - /*globals corbel */ - //@endexclude - - corbel.Notifications = corbel.Object.inherit({ - - /** - * Creates a new NotificationsBuilder - * @param {String} id String with the asset id or 'all' key - * @return {Notifications} - */ - constructor: function(driver) { - this.driver = driver; - }, - - notification: function(id) { - return new corbel.Notifications.NotificationsBuilder(this.driver, id); - } - - }, { - - moduleName: 'notifications', - defaultPort: 8094, - - create: function(driver) { - return new corbel.Notifications(driver); - } - - }); - - return corbel.Notifications; - -})(); +;(function () { + // @exclude + 'use strict' + /*globals corbel */ + // @endexclude + + corbel.Notifications = corbel.Object.inherit({ + /** + * Creates a new NotificationsBuilder + * @param {String} id String with the asset id or 'all' key + * @return {Notifications} + */ + constructor: function (driver) { + this.driver = driver + }, + + notification: function (id) { + return new corbel.Notifications.NotificationsBuilder(this.driver, id) + } + + }, { + moduleName: 'notifications', + defaultPort: 8094, + + create: function (driver) { + return new corbel.Notifications(driver) + } + + }) + + return corbel.Notifications +})() diff --git a/src/notifications/notificationsBuilder.js b/src/notifications/notificationsBuilder.js index 34a6750..e3fce92 100644 --- a/src/notifications/notificationsBuilder.js +++ b/src/notifications/notificationsBuilder.js @@ -1,135 +1,131 @@ -//@exclude -'use strict'; -//@endexclude +// @exclude +'use strict' +// @endexclude +/* global corbel */ -(function() { +;(function () { + var NotificationsBuilder = corbel.Notifications.NotificationsBuilder = corbel.Services.inherit({ + /** + * Creates a new NotificationsBuilder + * @param {String} id String with the asset id or 'all' key + * @return {Assets} + */ + constructor: function (driver, id) { + this.driver = driver + this.uri = 'notification' + this.id = id + }, + /* + * Creates a new notification + * @method + * @memberOf Corbel.Notifications.NotificationsBuilder + * @param {Object} notification Contains the data of the new notification + * @param {String} notification.type Notification type (mail, sms...) + * @param {String} notification.text Notification content + * @param {String} notification.sender Notification sender + * @param {String} [notification.title] Notification title + * + * @return {Promise} Promise that resolves in the new notification id or rejects with a {@link CorbelError} + */ + create: function (notification) { + console.log('notificationsInterface.notification.create', notification) + return this.request({ + url: this._buildUri(this.uri), + method: corbel.request.method.POST, + data: notification + }).then(function (res) { + return corbel.Services.getLocationId(res) + }) + }, + /** + * Gets a notification + * @method + * @memberOf Corbel.Notifications.NotificationsBuilder + * @param {Object} [params] Params of the corbel request + * @return {Promise} Promise that resolves to a Notification {Object} or rejects with a {@link CorbelError} + */ + get: function (params) { + console.log('notificationsInterface.notification.get', params) + return this.request({ + url: this._buildUri(this.uri, this.id), + method: corbel.request.method.GET, + query: params ? corbel.utils.serializeParams(params) : null + }) + }, + /** + * Updates a notification + * @method + * @memberOf Corbel.Notifications.NotificationsBuilder + * @param {Object} data Data to be updated + * + * @return {Promise} Promise that resolves to undefined (void) or rejects with a {@link CorbelError} + */ + update: function (data) { + console.log('notificationsInterface.notification.update', data) + corbel.validate.value('id', this.id) + return this.request({ + url: this._buildUri(this.uri, this.id), + method: corbel.request.method.PUT, + data: data + }) + }, + /** + * Deletes a notification + * @method + * @memberOf Corbel.Notifications.NotificationsBuilder + * @return {Promise} Promise that resolves to undefined (void) or rejects with a {@link CorbelError} + */ + delete: function () { + console.log('notificationsInterface.notification.delete') + corbel.validate.value('id', this.id) + return this.request({ + url: this._buildUri(this.uri, this.id), + method: corbel.request.method.DELETE + }) + }, + /** + * Send a notification + * @method + * @memberOf Corbel.Notifications.NotificationsBuilder + * @param {Object} notification Notification + * @param {String} notification.notificationId Notification id (mail, sms...) + * @param {String} notification.recipient Notification recipient + * @param {Object} notification.propierties Notification propierties + * @return {Promise} Promise that resolves to undefined (void) or rejects with a {@link CorbelError} + */ + sendNotification: function (notification) { + console.log('notificationsInterface.notification.sendNotification', notification) + this.uri += '/send' + return this.request({ + url: this._buildUri(this.uri), + method: corbel.request.method.POST, + data: notification + }) + }, - var NotificationsBuilder = corbel.Notifications.NotificationsBuilder = corbel.Services.inherit({ + _buildUri: function (path, id) { + var uri = '' + var urlBase = this.driver.config.getCurrentEndpoint(corbel.Notifications.moduleName, this._buildPort(this.driver.config)) - /** - * Creates a new NotificationsBuilder - * @param {String} id String with the asset id or 'all' key - * @return {Assets} - */ - constructor: function(driver, id) { - this.driver = driver; - this.uri = 'notification'; - this.id = id; - }, - /* - * Creates a new notification - * @method - * @memberOf Corbel.Notifications.NotificationsBuilder - * @param {Object} notification Contains the data of the new notification - * @param {String} notification.type Notification type (mail, sms...) - * @param {String} notification.text Notification content - * @param {String} notification.sender Notification sender - * @param {String} [notification.title] Notification title - * - * @return {Promise} Promise that resolves in the new notification id or rejects with a {@link CorbelError} - */ - create: function(notification) { - console.log('notificationsInterface.notification.create', notification); - return this.request({ - url: this._buildUri(this.uri), - method: corbel.request.method.POST, - data: notification - }). - then(function(res) { - return corbel.Services.getLocationId(res); - }); - }, - /** - * Gets a notification - * @method - * @memberOf Corbel.Notifications.NotificationsBuilder - * @param {Object} [params] Params of the corbel request - * @return {Promise} Promise that resolves to a Notification {Object} or rejects with a {@link CorbelError} - */ - get: function(params) { - console.log('notificationsInterface.notification.get', params); - return this.request({ - url: this._buildUri(this.uri, this.id), - method: corbel.request.method.GET, - query: params ? corbel.utils.serializeParams(params) : null - }); - }, - /** - * Updates a notification - * @method - * @memberOf Corbel.Notifications.NotificationsBuilder - * @param {Object} data Data to be updated - * - * @return {Promise} Promise that resolves to undefined (void) or rejects with a {@link CorbelError} - */ - update: function(data) { - console.log('notificationsInterface.notification.update', data); - corbel.validate.value('id', this.id); - return this.request({ - url: this._buildUri(this.uri, this.id), - method: corbel.request.method.PUT, - data: data - }); - }, - /** - * Deletes a notification - * @method - * @memberOf Corbel.Notifications.NotificationsBuilder - * @return {Promise} Promise that resolves to undefined (void) or rejects with a {@link CorbelError} - */ - delete: function() { - console.log('notificationsInterface.notification.delete'); - corbel.validate.value('id', this.id); - return this.request({ - url: this._buildUri(this.uri, this.id), - method: corbel.request.method.DELETE - }); - }, - /** - * Send a notification - * @method - * @memberOf Corbel.Notifications.NotificationsBuilder - * @param {Object} notification Notification - * @param {String} notification.notificationId Notification id (mail, sms...) - * @param {String} notification.recipient Notification recipient - * @param {Object} notification.propierties Notification propierties - * @return {Promise} Promise that resolves to undefined (void) or rejects with a {@link CorbelError} - */ - sendNotification: function(notification) { - console.log('notificationsInterface.notification.sendNotification', notification); - this.uri += '/send'; - return this.request({ - url: this._buildUri(this.uri), - method: corbel.request.method.POST, - data: notification - }); - }, + uri = urlBase + path + if (id) { + uri += '/' + id + } + return uri + }, - _buildUri: function(path, id) { - var uri = ''; - var urlBase = this.driver.config.getCurrentEndpoint(corbel.Notifications.moduleName, this._buildPort(this.driver.config)); + _buildPort: function (config) { + return config.get('notificationsPort', null) || corbel.Notifications.defaultPort + } - uri = urlBase + path; - if (id) { - uri += '/' + id; - } - return uri; - }, + }, { + moduleName: 'notifications', - _buildPort: function(config) { - return config.get('notificationsPort', null) || corbel.Notifications.defaultPort; - } + create: function (driver) { + return new corbel.NotificationsBuilder(driver) + } - }, { + }) - moduleName: 'notifications', - - create: function(driver) { - return new corbel.NotificationsBuilder(driver); - } - - }); - - return NotificationsBuilder; - -})(); + return NotificationsBuilder +})() diff --git a/src/oauth/authorizationBuilder.js b/src/oauth/authorizationBuilder.js index 32e8bd0..8735145 100644 --- a/src/oauth/authorizationBuilder.js +++ b/src/oauth/authorizationBuilder.js @@ -1,131 +1,129 @@ -//@exclude -'use strict'; -//@endexclude +// @exclude +'use strict' +// @endexclude +/* global corbel */ -(function() { - /** - * Create a AuthorizationBuilder for resource managing requests. - * - * @param {Object} clientParams Initial params - * - * @return {corbel.Oauth.AuthorizationBuilder} - */ - corbel.Oauth.prototype.authorization = function(clientParams) { - console.log('oauthInterface.authorization', clientParams); +;(function () { + /** + * Create a AuthorizationBuilder for resource managing requests. + * + * @param {Object} clientParams Initial params + * + * @return {corbel.Oauth.AuthorizationBuilder} + */ + corbel.Oauth.prototype.authorization = function (clientParams) { + console.log('oauthInterface.authorization', clientParams) - corbel.Oauth._checkProp(clientParams, ['responseType'], 'Invalid client parameters'); - clientParams.responseType = clientParams.responseType.toLowerCase(); - corbel.Oauth._validateResponseType(clientParams.responseType); - if (clientParams.responseType.toLowerCase() === 'code') { - corbel.Oauth._checkProp(clientParams, ['redirectUri'], 'Invalid client parameters'); - } - clientParams.clientId = clientParams.clientId || corbel.Config.get('oauthClientId'); - var params = { - contentType: corbel.Oauth._URL_ENCODED, - data: corbel.Oauth._trasformParams(clientParams), - // http://stackoverflow.com/questions/1557602/jquery-and-ajax-response-header - noRedirect: true - }; - var authorization = new AuthorizationBuilder(params); - authorization.driver = this.driver; - return authorization; - }; + corbel.Oauth._checkProp(clientParams, ['responseType'], 'Invalid client parameters') + clientParams.responseType = clientParams.responseType.toLowerCase() + corbel.Oauth._validateResponseType(clientParams.responseType) + if (clientParams.responseType.toLowerCase() === 'code') { + corbel.Oauth._checkProp(clientParams, ['redirectUri'], 'Invalid client parameters') + } + clientParams.clientId = clientParams.clientId || corbel.Config.get('oauthClientId') + var params = { + contentType: corbel.Oauth._URL_ENCODED, + data: corbel.Oauth._trasformParams(clientParams), + // http://stackoverflow.com/questions/1557602/jquery-and-ajax-response-header + noRedirect: true + } + var authorization = new AuthorizationBuilder(params) + authorization.driver = this.driver + return authorization + } + + /** + * A builder for authorization management requests. + * + * @param {Object} params Initial params + * + * @class + * @memberOf corbel.Oauth.AuthorizationBuilder + */ + var AuthorizationBuilder = corbel.Oauth.AuthorizationBuilder = corbel.Services.inherit({ + constructor: function (params) { + this.params = params + this.uri = 'oauth' + }, /** - * A builder for authorization management requests. - * - * @param {Object} params Initial params - * - * @class + * Does a login with stored cookie in oauth server + * @method * @memberOf corbel.Oauth.AuthorizationBuilder + * @return {Promise} Q promise that resolves to a redirection to redirectUri or rejects with a 404 {@link CorbelError} */ - var AuthorizationBuilder = corbel.Oauth.AuthorizationBuilder = corbel.Services.inherit({ - - constructor: function(params) { - this.params = params; - this.uri = 'oauth'; - }, - - /** - * Does a login with stored cookie in oauth server - * @method - * @memberOf corbel.Oauth.AuthorizationBuilder - * @return {Promise} Q promise that resolves to a redirection to redirectUri or rejects with a 404 {@link CorbelError} - */ - loginWithCookie: function() { - console.log('oauthInterface.authorization.dialog'); - // make request, generate oauth cookie, then redirect manually - return this.request({ - url: this._buildUri(this.uri + '/authorize'), - method: corbel.request.method.GET, - dataType: 'text', - withCredentials: true, - data: this.params, - query: this.params.data ? corbel.utils.serializeParams(this.params.data) : null - }).then(function(res) { - return corbel.Services.getLocationId(res); - }); - }, - /** - * Does a login in oauth server - * @method - * @memberOf corbel.Oauth.AuthorizationBuilder - * @param {String} username The username of the user to log in - * @param {String} password The password of the user - * @return {Promise} Q promise that resolves to a redirection to redirectUri or rejects with a {@link CorbelError} - */ - login: function(username, password, setCookie) { - console.log('oauthInterface.authorization.login', username + ':' + password); - - this.params.data.username = username; - this.params.data.password = password; - this.params.withCredentials = true; - // make request, generate oauth cookie, then redirect manually - return this.request({ - url: this._buildUri(this.uri + '/authorize'), - method: corbel.request.method.POST, - data: this.params.data, - contentType: this.params.contentType - }).then(function(res) { - if (res.jqXHR.getResponseHeader('Location')) { - var params = { - url: corbel.Services.getLocationId(res) - }; + loginWithCookie: function () { + console.log('oauthInterface.authorization.dialog') + // make request, generate oauth cookie, then redirect manually + return this.request({ + url: this._buildUri(this.uri + '/authorize'), + method: corbel.request.method.GET, + dataType: 'text', + withCredentials: true, + data: this.params, + query: this.params.data ? corbel.utils.serializeParams(this.params.data) : null + }).then(function (res) { + return corbel.Services.getLocationId(res) + }) + }, + /** + * Does a login in oauth server + * @method + * @memberOf corbel.Oauth.AuthorizationBuilder + * @param {String} username The username of the user to log in + * @param {String} password The password of the user + * @return {Promise} Q promise that resolves to a redirection to redirectUri or rejects with a {@link CorbelError} + */ + login: function (username, password, setCookie) { + console.log('oauthInterface.authorization.login', username + ':' + password) - if (setCookie) { - params.headers = { - RequestCookie: 'true' - }; - params.withCredentials = true; - } + this.params.data.username = username + this.params.data.password = password + this.params.withCredentials = true + // make request, generate oauth cookie, then redirect manually + return this.request({ + url: this._buildUri(this.uri + '/authorize'), + method: corbel.request.method.POST, + data: this.params.data, + contentType: this.params.contentType + }).then(function (res) { + if (res.jqXHR.getResponseHeader('Location')) { + var params = { + url: corbel.Services.getLocationId(res) + } - return this.request(params); - } - else { - return res.data; - } - }); - }, + if (setCookie) { + params.headers = { + RequestCookie: 'true' + } + params.withCredentials = true + } - /** - * Sign out from oauth server - * @method - * @memberOf corbel.Oauth.SignOutBuilder - * @return {Promise} promise that resolves empty when the sign out process completes or rejects with a {@link CorbelError} - */ - signout: function() { - console.log('oauthInterface.authorization.signOut'); - delete this.params.data; - return this.request({ - url: this._buildUri(this.uri + '/signout'), - method: corbel.request.method.GET, - withCredentials: true - }).then(function(res) { - return corbel.Services.getLocationId(res); - }); - }, + return this.request(params) + } else { + return res.data + } + }) + }, - _buildUri: corbel.Oauth._buildUri - }); + /** + * Sign out from oauth server + * @method + * @memberOf corbel.Oauth.SignOutBuilder + * @return {Promise} promise that resolves empty when the sign out process completes or rejects with a {@link CorbelError} + */ + signout: function () { + console.log('oauthInterface.authorization.signOut') + delete this.params.data + return this.request({ + url: this._buildUri(this.uri + '/signout'), + method: corbel.request.method.GET, + withCredentials: true + }).then(function (res) { + return corbel.Services.getLocationId(res) + }) + }, -})(); + _buildUri: corbel.Oauth._buildUri + }) +})() diff --git a/src/oauth/oauth.js b/src/oauth/oauth.js index 9070321..22462e3 100644 --- a/src/oauth/oauth.js +++ b/src/oauth/oauth.js @@ -1,89 +1,87 @@ -//@exclude -'use strict'; -//@endexclude +// @exclude +'use strict' +// @endexclude +/* global corbel */ -(function() { +;(function () { + /** + * A module to make Oauth requests. + * @exports Oauth + * @namespace + * @memberof app.corbel + */ - /** - * A module to make Oauth requests. - * @exports Oauth - * @namespace - * @memberof app.corbel - */ + var Oauth = corbel.Oauth = function (driver) { + this.driver = driver + } - var Oauth = corbel.Oauth = function(driver) { - this.driver = driver; - }; + Oauth.moduleName = 'oauth' + Oauth.defaultPort = 8084 - Oauth.moduleName = 'oauth'; - Oauth.defaultPort = 8084; + Oauth.create = function (driver) { + return new Oauth(driver) + } + /** + * Private method to build a string uri + * @private + * @param {String} uri + * @return {String} + */ + Oauth._buildUri = function (uri) { + var urlBase = this.driver.config.getCurrentEndpoint(Oauth.moduleName, corbel.Oauth._buildPort(this.driver.config)) - Oauth.create = function(driver) { - return new Oauth(driver); - }; - /** - * Private method to build a string uri - * @private - * @param {String} uri - * @return {String} - */ - Oauth._buildUri = function(uri) { + return urlBase + uri + } - var urlBase = this.driver.config.getCurrentEndpoint(Oauth.moduleName, corbel.Oauth._buildPort(this.driver.config)); + Oauth._buildPort = function (config) { + return config.get('oauthPort', null) || corbel.Oauth.defaultPort + } - return urlBase + uri; - }; + /** + * Default encoding + * @type {String} + * @default application/x-www-form-urlencoded; charset=UTF-8 + */ + Oauth._URL_ENCODED = 'application/x-www-form-urlencoded; charset=UTF-8' - Oauth._buildPort = function(config) { - return config.get('oauthPort', null) || corbel.Oauth.defaultPort; - }; + Oauth._checkProp = function (dict, keys, excep) { + var error = !excep ? 'Error validating arguments' : excep + if (!dict) { + throw new Error(error) + } + for (var i in keys) { + if (!(keys[i] in dict)) { + throw new Error(error) + } + } + } - /** - * Default encoding - * @type {String} - * @default application/x-www-form-urlencoded; charset=UTF-8 - */ - Oauth._URL_ENCODED = 'application/x-www-form-urlencoded; charset=UTF-8'; + Oauth._validateResponseType = function (responseType) { + if (['code', 'token'].indexOf(responseType) < 0) { + throw new Error('Only "code" or "token" response type allowed') + } + } - Oauth._checkProp = function(dict, keys, excep) { - var error = excep ? excep : 'Error validating arguments'; - if (!dict) { - throw new Error(error); - } - for (var i in keys) { - if (!(keys[i] in dict)) { - throw new Error(error); - } - } - }; + Oauth._validateGrantType = function (grantType) { + if (grantType !== 'authorization_code') { + throw new Error('Only "authorization_code" grant type is allowed') + } + } - Oauth._validateResponseType = function(responseType) { - if (['code', 'token'].indexOf(responseType) < 0) { - throw new Error('Only "code" or "token" response type allowed'); - } - }; + Oauth._trasformParams = function (clientParams) { + for (var key in clientParams) { + var keyWithUnderscores = this._toUnderscore(key) + if (key !== keyWithUnderscores) { + clientParams[keyWithUnderscores] = clientParams[key] + delete clientParams[key] + } + } + return clientParams + } - Oauth._validateGrantType = function(grantType) { - if (grantType !== 'authorization_code') { - throw new Error('Only "authorization_code" grant type is allowed'); - } - }; - - Oauth._trasformParams = function(clientParams) { - - for (var key in clientParams) { - var keyWithUnderscores = this._toUnderscore(key); - if (key !== keyWithUnderscores) { - clientParams[keyWithUnderscores] = clientParams[key]; - delete clientParams[key]; - } - } - return clientParams; - }; - - Oauth._toUnderscore = function(string) { - return string.replace(/([A-Z])/g, function($1) { - return '_' + $1.toLowerCase(); - }); - }; -})(); + Oauth._toUnderscore = function (string) { + return string.replace(/([A-Z])/g, function ($1) { + return '_' + $1.toLowerCase() + }) + } +})() diff --git a/src/oauth/tokenBuilder.js b/src/oauth/tokenBuilder.js index 26e8147..96a188d 100644 --- a/src/oauth/tokenBuilder.js +++ b/src/oauth/tokenBuilder.js @@ -1,66 +1,62 @@ -//@exclude -'use strict'; -//@endexclude +// @exclude +'use strict' +// @endexclude +/* global corbel */ -(function() { - /** - * Create a TokenBuilder for token managing requests. - * Starts to build a token request - * @method - * @param {Object} clientParams - * @param {String} [clientParams.clientId=corbel.Config.get('oauthClientId')] Client id - * @param {String} [clientParams.clientSecret=corbel.Config.get('oauthSecret')] Client secret - * @param {String} clientParams.grantType The grant type (only allowed 'authorization_code') - * @return {corbel.Oauth.TokenBuilder} - */ - corbel.Oauth.prototype.token = function(clientParams) { - console.log('oauthInterface.token'); +;(function () { + /** + * Create a TokenBuilder for token managing requests. + * Starts to build a token request + * @method + * @param {Object} clientParams + * @param {String} [clientParams.clientId=corbel.Config.get('oauthClientId')] Client id + * @param {String} [clientParams.clientSecret=corbel.Config.get('oauthSecret')] Client secret + * @param {String} clientParams.grantType The grant type (only allowed 'authorization_code') + * @return {corbel.Oauth.TokenBuilder} + */ + corbel.Oauth.prototype.token = function (clientParams) { + console.log('oauthInterface.token') - corbel.Oauth._checkProp(clientParams, ['grantType'], 'Invalid client parameters'); - corbel.Oauth._validateGrantType(clientParams.grantType); - clientParams.clientId = clientParams.clientId || corbel.Config.get('oauthClientId'); - clientParams.clientSecret = clientParams.clientSecret || corbel.Config.get('oauthSecret'); - var params = { - contentType: corbel.Oauth._URL_ENCODED, - data: corbel.Oauth._trasformParams(clientParams) - }; - var token = new TokenBuilder(params); - token.driver = this.driver; - return token; - }; + corbel.Oauth._checkProp(clientParams, ['grantType'], 'Invalid client parameters') + corbel.Oauth._validateGrantType(clientParams.grantType) + clientParams.clientId = clientParams.clientId || corbel.Config.get('oauthClientId') + clientParams.clientSecret = clientParams.clientSecret || corbel.Config.get('oauthSecret') + var params = { + contentType: corbel.Oauth._URL_ENCODED, + data: corbel.Oauth._trasformParams(clientParams) + } + var token = new TokenBuilder(params) + token.driver = this.driver + return token + } + /** + * A builder for a token management requests. + * @class + * @param {Object} params Initial params + * @memberOf corbel.Oauth.TokenBuilder + */ + var TokenBuilder = corbel.Oauth.TokenBuilder = corbel.Services.inherit({ + constructor: function (params) { + this.params = params + this.uri = 'oauth/token' + }, /** - * A builder for a token management requests. - * @class - * - * @param {Object} params Initial params - * + * Get an access token + * @method * @memberOf corbel.Oauth.TokenBuilder + * @param {String} code The code to exchange for the token + * @return {Promise} promise that resolves to an access token {Object} or rejects with a {@link CorbelError} */ - var TokenBuilder = corbel.Oauth.TokenBuilder = corbel.Services.inherit({ - - constructor: function(params) { - this.params = params; - this.uri = 'oauth/token'; - }, - /** - * Get an access token - * @method - * @memberOf corbel.Oauth.TokenBuilder - * - * @param {String} code The code to exchange for the token - * - * @return {Promise} promise that resolves to an access token {Object} or rejects with a {@link CorbelError} - */ - get: function(code) { - console.log('oauthInterface.token.get'); - this.params.data.code = code; - return this.request({ - url: this._buildUri(this.uri), - method: corbel.request.method.POST, - data: this.params - }); - }, + get: function (code) { + console.log('oauthInterface.token.get') + this.params.data.code = code + return this.request({ + url: this._buildUri(this.uri), + method: corbel.request.method.POST, + data: this.params + }) + }, - _buildUri: corbel.Oauth._buildUri - }); -})(); + _buildUri: corbel.Oauth._buildUri + }) +})() diff --git a/src/oauth/userBuilder.js b/src/oauth/userBuilder.js index 9c7791d..e522a9a 100644 --- a/src/oauth/userBuilder.js +++ b/src/oauth/userBuilder.js @@ -1,216 +1,204 @@ -//@exclude -'use strict'; -//@endexclude +// @exclude +'use strict' +// @endexclude +/* global corbel btoa */ -(function() { - /** - * Create a UserBuilder for user managing requests. - * Starts a user request - * @method - * @param {Object} clientParams - * @param {String} [clientParams.clientId=corbel.Config.get('oauthClientId')] Client id - * @param {String} [clientParams.clientSecret=corbel.Config.get('oauthSecret')] Client secret - * @param {String} clientParams.grantType The grant type (only allowed 'authorization_code') - * @return {corbel.Oauth.UserBuilder} - */ - corbel.Oauth.prototype.user = function(clientParams, accessToken) { - console.log('oauthInterface.user'); +;(function () { + /** + * Create a UserBuilder for user managing requests. + * Starts a user request + * @method + * @param {Object} clientParams + * @param {String} [clientParams.clientId=corbel.Config.get('oauthClientId')] Client id + * @param {String} [clientParams.clientSecret=corbel.Config.get('oauthSecret')] Client secret + * @param {String} clientParams.grantType The grant type (only allowed 'authorization_code') + * @return {corbel.Oauth.UserBuilder} + */ + corbel.Oauth.prototype.user = function (clientParams, accessToken) { + console.log('oauthInterface.user') - var params = {}; + var params = {} - if (accessToken) { - params.accessToken = accessToken; - params.headers = {}; - params.headers.Accept = 'application/json'; - } + if (accessToken) { + params.accessToken = accessToken + params.headers = {} + params.headers.Accept = 'application/json' + } - clientParams = clientParams || {}; - var clientId = clientParams.clientId || corbel.Config.get('oauthClientId'); - var clientSecret = clientParams.clientSecret || corbel.Config.get('oauthSecret'); + clientParams = clientParams || {} + var clientId = clientParams.clientId || corbel.Config.get('oauthClientId') + var clientSecret = clientParams.clientSecret || corbel.Config.get('oauthSecret') - var user = new UserBuilder(params, clientId, clientSecret); - user.driver = this.driver; - return user; - }; + var user = new UserBuilder(params, clientId, clientSecret) + user.driver = this.driver + return user + } + /** + * A builder for a user management requests. + * @class + * @param {Object} params Parameters for initializing the builder + * @param {String} [clientId] Application client Id (required for creating user) + * @param {String} [clientSecret] Application client secret (required for creating user) + * @memberOf corbel.Oauth.UserBuilder + */ + var UserBuilder = corbel.Oauth.UserBuilder = corbel.Services.inherit({ + constructor: function (params, clientId, clientSecret) { + this.params = params + this.clientSecret = clientSecret + this.clientId = clientId + this.uri = 'user' + }, + _buildUri: corbel.Oauth._buildUri, /** - * A builder for a user management requests. - * @class - * - * @param {Object} params Parameters for initializing the builder - * @param {String} [clientId] Application client Id (required for creating user) - * @param {String} [clientSecret] Application client secret (required for creating user) - * + * Adds a new user to the oauth server. + * + * @method * @memberOf corbel.Oauth.UserBuilder + * + * @param {Object} user The user to be created + * @param {String} username The username of the user + * @param {String} email The email of the user + * @param {String} password The password of the user + * + * @return {Promise} A promise with the id of the created user or fails + * with a {@link corbelError}. */ - var UserBuilder = corbel.Oauth.UserBuilder = corbel.Services.inherit({ + create: function (user) { + console.log('oauthInterface.user.create', user) - constructor: function(params, clientId, clientSecret) { - this.params = params; - this.clientSecret = clientSecret; - this.clientId = clientId; - this.uri = 'user'; - }, - _buildUri: corbel.Oauth._buildUri, - /** - * Adds a new user to the oauth server. - * - * @method - * @memberOf corbel.Oauth.UserBuilder - * - * @param {Object} user The user to be created - * @param {String} username The username of the user - * @param {String} email The email of the user - * @param {String} password The password of the user - * - * @return {Promise} A promise with the id of the created user or fails - * with a {@link corbelError}. - */ - create: function(user) { - console.log('oauthInterface.user.create', user); - - return this.request({ - url: this._buildUri(this.uri), - method: corbel.request.method.POST, - headers: { - Authorization: 'Basic ' + this.getSerializer()(this.clientId + ':' + this.clientSecret) - }, - dataType: 'text', - data: user - }).then(function(res) { - return corbel.Services.getLocationId(res); - }); - }, - /** - * Gets the user or the logged user - * @method - * @memberOf corbel.Oauth.UserBuilder - * - * @param {Object} id The user id/me - * - * @return {Promise} Q promise that resolves to a User {Object} or rejects with a {@link corbelError} - */ - get: function(id) { - console.log('oauthInterface.user.get'); - this.uri += '/' + id; - return this.request({ - url: this._buildUri(this.uri, this.uri), - method: corbel.request.method.GET - }); - }, - /** - * Get profile of some user or the logged user - * @method - * @memberOf corbel.Oauth.UserBuilder - * @param {Object} id The user id/me - * @return {Promise} Q promise that resolves to the profile from User {Object} or rejects with a {@link corbelError} - */ - getProfile: function(id) { - console.log('oauthInterface.user.getProfile'); - this.uri += '/' + id + '/profile'; - return this.request({ - url: this._buildUri(this.uri), - method: corbel.request.method.GET - }); - }, - /** - * Updates the user or the logged user - * @method - * @memberOf corbel.Oauth.UserBuilder - * - * @param {Object} id The user id or me - * @param {Object} modification Json object with the modificacion of the user - * - * @return {Promise} Q promise that resolves to undefined (void) or rejects with a {@link corbelError} - */ - update: function(id, modification) { - console.log('oauthInterface.user.update', modification); - this.uri += '/' + id; - return this.request({ - url: this._buildUri(this.uri), - method: corbel.request.method.PUT, - data: modification - }); - }, - /** - * Deletes the user or the logged user - * @memberOf corbel.Oauth.UserBuilder - * - * @param {Object} id The user id or me - * - * @return {Promise} Q promise that resolves to undefined (void) or rejects with a {@link corbelError} - */ - delete: function(id) { - console.log('oauthInterface.user.delete'); - this.uri += '/' + id; - return this.request({ - url: this._buildUri(this.uri), - method: corbel.request.method.DELETE - }); + return this.request({ + url: this._buildUri(this.uri), + method: corbel.request.method.POST, + headers: { + Authorization: 'Basic ' + this.getSerializer()(this.clientId + ':' + this.clientSecret) }, - /** - * Sends a reset password email to the email address recived. - * @method - * @memberOf corbel.Oauth.UsersBuilder - * @param {String} userEmailToReset The email to send the message - * @return {Promise} Q promise that resolves to undefined (void) or rejects with a {@link CorbelError} - */ - sendResetPasswordEmail: function(userEmailToReset) { - console.log('oauthInterface.user.SendResetPasswordEmail', userEmailToReset); - return this.request({ - url: this._buildUri(this.uri + '/resetPassword'), - method: corbel.request.method.GET, - query: 'email=' + userEmailToReset, - headers: { - Authorization: 'Basic ' + this.getSerializer()(this.clientId + ':' + this.clientSecret) - }, - noRetry: true - }).then(function(res) { - return corbel.Services.getLocationId(res); - }); - }, - /** - * Sends a email to the logged user or user to validate his email address - * @method - * @memberOf corbel.Oauth.UsersBuilder - * - * @param {Object} id The user id or me - * - * @return {Promise} Q promise that resolves to undefined (void) or rejects with a {@link CorbelError} - */ - sendValidateEmail: function(id) { - console.log('oauthInterface.user.sendValidateEmail'); - this.uri += '/' + id + '/validate'; - return this.request({ - url: this._buildUri(this.uri), - method: corbel.request.method.GET, - withAuth: true - }); - }, - /** - * Validates the email of a user or the logged user - * @method - * @memberOf corbel.Oauth.UsersBuilder - * - * @param {Object} id The user id or me - * - * @return {Promise} Q promise that resolves to undefined (void) or rejects with a {@link CorbelError} - */ - emailConfirmation: function(id) { - console.log('oauthInterface.user.emailConfirmation'); - this.uri += '/' + id + '/emailConfirmation'; - return this.request({ - url: this._buildUri(this.uri, id), - method: corbel.request.method.PUT, - noRetry: true - }); + dataType: 'text', + data: user + }).then(function (res) { + return corbel.Services.getLocationId(res) + }) + }, + /** + * Gets the user or the logged user + * @method + * @memberOf corbel.Oauth.UserBuilder + * @param {Object} id The user id/me + * @return {Promise} Q promise that resolves to a User {Object} or rejects with a {@link corbelError} + */ + get: function (id) { + console.log('oauthInterface.user.get') + this.uri += '/' + id + return this.request({ + url: this._buildUri(this.uri, this.uri), + method: corbel.request.method.GET + }) + }, + /** + * Get profile of some user or the logged user + * @method + * @memberOf corbel.Oauth.UserBuilder + * @param {Object} id The user id/me + * @return {Promise} Q promise that resolves to the profile from User {Object} or rejects with a {@link corbelError} + */ + getProfile: function (id) { + console.log('oauthInterface.user.getProfile') + this.uri += '/' + id + '/profile' + return this.request({ + url: this._buildUri(this.uri), + method: corbel.request.method.GET + }) + }, + /** + * Updates the user or the logged user + * @method + * @memberOf corbel.Oauth.UserBuilder + * @param {Object} id The user id or me + * @param {Object} modification Json object with the modificacion of the user + * @return {Promise} Q promise that resolves to undefined (void) or rejects with a {@link corbelError} + */ + update: function (id, modification) { + console.log('oauthInterface.user.update', modification) + this.uri += '/' + id + return this.request({ + url: this._buildUri(this.uri), + method: corbel.request.method.PUT, + data: modification + }) + }, + /** + * Deletes the user or the logged user + * @memberOf corbel.Oauth.UserBuilder + * @param {Object} id The user id or me + * @return {Promise} Q promise that resolves to undefined (void) or rejects with a {@link corbelError} + */ + delete: function (id) { + console.log('oauthInterface.user.delete') + this.uri += '/' + id + return this.request({ + url: this._buildUri(this.uri), + method: corbel.request.method.DELETE + }) + }, + /** + * Sends a reset password email to the email address recived. + * @method + * @memberOf corbel.Oauth.UsersBuilder + * @param {String} userEmailToReset The email to send the message + * @return {Promise} Q promise that resolves to undefined (void) or rejects with a {@link CorbelError} + */ + sendResetPasswordEmail: function (userEmailToReset) { + console.log('oauthInterface.user.SendResetPasswordEmail', userEmailToReset) + return this.request({ + url: this._buildUri(this.uri + '/resetPassword'), + method: corbel.request.method.GET, + query: 'email=' + userEmailToReset, + headers: { + Authorization: 'Basic ' + this.getSerializer()(this.clientId + ':' + this.clientSecret) }, + noRetry: true + }).then(function (res) { + return corbel.Services.getLocationId(res) + }) + }, + /** + * Sends a email to the logged user or user to validate his email address + * @method + * @memberOf corbel.Oauth.UsersBuilder + * @param {Object} id The user id or me + * @return {Promise} Q promise that resolves to undefined (void) or rejects with a {@link CorbelError} + */ + sendValidateEmail: function (id) { + console.log('oauthInterface.user.sendValidateEmail') + this.uri += '/' + id + '/validate' + return this.request({ + url: this._buildUri(this.uri), + method: corbel.request.method.GET, + withAuth: true + }) + }, + /** + * Validates the email of a user or the logged user + * @method + * @memberOf corbel.Oauth.UsersBuilder + * @param {Object} id The user id or me + * @return {Promise} Q promise that resolves to undefined (void) or rejects with a {@link CorbelError} + */ + emailConfirmation: function (id) { + console.log('oauthInterface.user.emailConfirmation') + this.uri += '/' + id + '/emailConfirmation' + return this.request({ + url: this._buildUri(this.uri, id), + method: corbel.request.method.PUT, + noRetry: true + }) + }, - getSerializer: function() { - if (corbel.Config.isNode) { - return require('btoa'); - } else { - return btoa; - } - } - }); -})(); + getSerializer: function () { + if (corbel.Config.isNode) { + return require('btoa') + } else { + return btoa + } + } + }) +})() diff --git a/src/object.js b/src/object.js index dfa73a4..6d7d6c7 100644 --- a/src/object.js +++ b/src/object.js @@ -1,28 +1,27 @@ -//@exclude -'use strict'; -//@endexclude +// @exclude +'use strict' +// @endexclude +/* global corbel */ -(function() { +;(function () { + /** + * Base object with + * @class + * @exports Object + * @namespace + * @memberof corbel + */ + corbel.Object = function () { + return this + } - /** - * Base object with - * @class - * @exports Object - * @namespace - * @memberof corbel - */ - corbel.Object = function() { - return this; - }; + /** + * Gets my user assets + * @memberof corbel.Object + * @see corbel.utils.inherit + * @return {Object} + */ + corbel.Object.inherit = corbel.utils.inherit - /** - * Gets my user assets - * @memberof corbel.Object - * @see corbel.utils.inherit - * @return {Object} - */ - corbel.Object.inherit = corbel.utils.inherit; - - return corbel.Object; - -})(); \ No newline at end of file + return corbel.Object +})() diff --git a/src/request-params/aggregation-builder.js b/src/request-params/aggregation-builder.js index 92d6ba1..d0548e0 100644 --- a/src/request-params/aggregation-builder.js +++ b/src/request-params/aggregation-builder.js @@ -1,24 +1,20 @@ -//@exclude -'use strict'; -/* jshint unused:false */ -//@endexclude +// @exclude +'use strict' +// @endexclude +var aggregationBuilder = (function () { + var aggregationBuilder = {} -var aggregationBuilder = (function() { + /** + * Adds a count operation to aggregation + * @param {String} field Name of the field to aggregate or * to aggregate all + * @return {RequestParamsBuilder} RequestParamsBuilder + */ + aggregationBuilder.count = function (field) { + this.params.aggregation = this.params.aggregation || {} + this.params.aggregation.$count = field + return this + } - var aggregationBuilder = {}; - - /** - * Adds a count operation to aggregation - * @param {String} field Name of the field to aggregate or * to aggregate all - * @return {RequestParamsBuilder} RequestParamsBuilder - */ - aggregationBuilder.count = function(field) { - this.params.aggregation = this.params.aggregation || {}; - this.params.aggregation.$count = field; - return this; - }; - - return aggregationBuilder; - -})(); \ No newline at end of file + return aggregationBuilder +})() diff --git a/src/request-params/page-builder.js b/src/request-params/page-builder.js index 553341c..f7ee0af 100644 --- a/src/request-params/page-builder.js +++ b/src/request-params/page-builder.js @@ -1,48 +1,43 @@ -//@exclude -'use strict'; -/* jshint unused:false */ -//@endexclude - - -var pageBuilder = (function() { - - var pageBuilder = {}; - - /** - * Sets the page number of the page param - * @param {int} page - * @return {RequestParamsBuilder} RequestParamsBuilder - */ - pageBuilder.page = function(page) { - this.params.pagination = this.params.pagination || {}; - this.params.pagination.page = page; - return this; - }; - - /** - * Sets the page size of the page param - * @param {int} size - * @return {RequestParamsBuilder} RequestParamsBuilder - */ - pageBuilder.pageSize = function(pageSize) { - this.params.pagination = this.params.pagination || {}; - this.params.pagination.pageSize = pageSize; - return this; - }; - - /** - * Sets the page number and page size of the page param - * @param {int} size - * @return {RequestParamsBuilder} RequestParamsBuilder - */ - pageBuilder.pageParam = function(page, pageSize) { - this.params.pagination = this.params.pagination || {}; - this.params.pagination.page = page; - this.params.pagination.pageSize = pageSize; - return this; - }; - - return pageBuilder; - - -})(); +// @exclude +'use strict' +// @endexclude + +var pageBuilder = (function () { + var pageBuilder = {} + + /** + * Sets the page number of the page param + * @param {int} page + * @return {RequestParamsBuilder} RequestParamsBuilder + */ + pageBuilder.page = function (page) { + this.params.pagination = this.params.pagination || {} + this.params.pagination.page = page + return this + } + + /** + * Sets the page size of the page param + * @param {int} size + * @return {RequestParamsBuilder} RequestParamsBuilder + */ + pageBuilder.pageSize = function (pageSize) { + this.params.pagination = this.params.pagination || {} + this.params.pagination.pageSize = pageSize + return this + } + + /** + * Sets the page number and page size of the page param + * @param {int} size + * @return {RequestParamsBuilder} RequestParamsBuilder + */ + pageBuilder.pageParam = function (page, pageSize) { + this.params.pagination = this.params.pagination || {} + this.params.pagination.page = page + this.params.pagination.pageSize = pageSize + return this + } + + return pageBuilder +})() diff --git a/src/request-params/query-builder.js b/src/request-params/query-builder.js index 660f061..3eebae0 100644 --- a/src/request-params/query-builder.js +++ b/src/request-params/query-builder.js @@ -1,141 +1,137 @@ -//@exclude -'use strict'; -/* jshint unused:false */ -//@endexclude - - -var queryBuilder = (function() { - - var queryBuilder = {}; - - /** - * Adds an Equal criteria to query - * @param {String} field - * @param {String | Number | Date} value - * @return {RequestParamsBuilder} RequestParamsBuilder - */ - queryBuilder.eq = function(field, value) { - this.addCriteria('$eq', field, value); - return this; - }; - - /** - * Adds a Greater Than criteria to query - * @param {String} field - * @param {String | Number | Date} value - * @return {RequestParamsBuilder} RequestParamsBuilder - */ - queryBuilder.gt = function(field, value) { - this.addCriteria('$gt', field, value); - return this; - }; - - /** - * Adds a Greater Than Or Equal criteria to query - * @param {String} field - * @param {String | Number | Date} value - * @return {RequestParamsBuilder} RequestParamsBuilder - */ - queryBuilder.gte = function(field, value) { - this.addCriteria('$gte', field, value); - return this; - }; - - /** - * Adds a Less Than criteria to query - * @param {String} field - * @param {String | Number | Date} value - * @return {RequestParamsBuilder} RequestParamsBuilder - */ - queryBuilder.lt = function(field, value) { - this.addCriteria('$lt', field, value); - return this; - }; - - /** - * Adds a Less Than Or Equal criteria to query - * @param {String} field - * @param {String | Number | Date} value - * @return {RequestParamsBuilder} RequestParamsBuilder - */ - queryBuilder.lte = function(field, value) { - this.addCriteria('$lte', field, value); - return this; - }; - - /** - * Adds a Not Equal criteria to query - * @param {String} field - * @param {String | Number | Date} value - * @return {RequestParamsBuilder} RequestParamsBuilder - */ - queryBuilder.ne = function(field, value) { - this.addCriteria('$ne', field, value); - return this; - }; - - /** - * Adds a Like criteria to query - * @param {String} field - * @param {String | Number | Date} value - * @return {RequestParamsBuilder} RequestParamsBuilder - */ - queryBuilder.like = function(field, value) { - this.addCriteria('$like', field, value); - return this; - }; - - /** - * Adds an In criteria to query - * @param {String} field - * @param {String[]|Number[]|Date[]} values - * @return {RequestParamsBuilder} RequestParamsBuilder - */ - queryBuilder.in = function(field, values) { - this.addCriteria('$in', field, values); - return this; - }; - - /** - * Adds an All criteria to query - * @param {String} field - * @param {String[]|Number[]|Date[]} values - * @return {RequestParamsBuilder} RequestParamsBuilder - */ - queryBuilder.all = function(field, values) { - this.addCriteria('$all', field, values); - return this; - }; - - /** - * Adds an Element Match criteria to query - * @param {String} field - * @param {JSON} value Query for the matching - * @return {RequestParamsBuilder} RequestParamsBuilder - */ - queryBuilder.elemMatch = function(field, query) { - this.addCriteria('$elem_match', field, query); - return this; - }; - - /** - * Sets an specific queryDomain, by default 'api'. - * @param {String} queryDomain query domain name, 'api' and '7digital' supported - */ - queryBuilder.setQueryDomain = function(queryDomain) { - this.params.queryDomain = queryDomain; - return this; - }; - - queryBuilder.addCriteria = function(operator, field, value) { - var criteria = {}; - criteria[operator] = {}; - criteria[operator][field] = value; - this.params.query = this.params.query || []; - this.params.query.push(criteria); - return this; - }; - - return queryBuilder; - -})(); \ No newline at end of file +// @exclude +'use strict' +// @endexclude + +var queryBuilder = (function () { + var queryBuilder = {} + + /** + * Adds an Equal criteria to query + * @param {String} field + * @param {String | Number | Date} value + * @return {RequestParamsBuilder} RequestParamsBuilder + */ + queryBuilder.eq = function (field, value) { + this.addCriteria('$eq', field, value) + return this + } + + /** + * Adds a Greater Than criteria to query + * @param {String} field + * @param {String | Number | Date} value + * @return {RequestParamsBuilder} RequestParamsBuilder + */ + queryBuilder.gt = function (field, value) { + this.addCriteria('$gt', field, value) + return this + } + + /** + * Adds a Greater Than Or Equal criteria to query + * @param {String} field + * @param {String | Number | Date} value + * @return {RequestParamsBuilder} RequestParamsBuilder + */ + queryBuilder.gte = function (field, value) { + this.addCriteria('$gte', field, value) + return this + } + + /** + * Adds a Less Than criteria to query + * @param {String} field + * @param {String | Number | Date} value + * @return {RequestParamsBuilder} RequestParamsBuilder + */ + queryBuilder.lt = function (field, value) { + this.addCriteria('$lt', field, value) + return this + } + + /** + * Adds a Less Than Or Equal criteria to query + * @param {String} field + * @param {String | Number | Date} value + * @return {RequestParamsBuilder} RequestParamsBuilder + */ + queryBuilder.lte = function (field, value) { + this.addCriteria('$lte', field, value) + return this + } + + /** + * Adds a Not Equal criteria to query + * @param {String} field + * @param {String | Number | Date} value + * @return {RequestParamsBuilder} RequestParamsBuilder + */ + queryBuilder.ne = function (field, value) { + this.addCriteria('$ne', field, value) + return this + } + + /** + * Adds a Like criteria to query + * @param {String} field + * @param {String | Number | Date} value + * @return {RequestParamsBuilder} RequestParamsBuilder + */ + queryBuilder.like = function (field, value) { + this.addCriteria('$like', field, value) + return this + } + + /** + * Adds an In criteria to query + * @param {String} field + * @param {String[]|Number[]|Date[]} values + * @return {RequestParamsBuilder} RequestParamsBuilder + */ + queryBuilder.in = function (field, values) { + this.addCriteria('$in', field, values) + return this + } + + /** + * Adds an All criteria to query + * @param {String} field + * @param {String[]|Number[]|Date[]} values + * @return {RequestParamsBuilder} RequestParamsBuilder + */ + queryBuilder.all = function (field, values) { + this.addCriteria('$all', field, values) + return this + } + + /** + * Adds an Element Match criteria to query + * @param {String} field + * @param {JSON} value Query for the matching + * @return {RequestParamsBuilder} RequestParamsBuilder + */ + queryBuilder.elemMatch = function (field, query) { + this.addCriteria('$elem_match', field, query) + return this + } + + /** + * Sets an specific queryDomain, by default 'api'. + * @param {String} queryDomain query domain name, 'api' and '7digital' supported + */ + queryBuilder.setQueryDomain = function (queryDomain) { + this.params.queryDomain = queryDomain + return this + } + + queryBuilder.addCriteria = function (operator, field, value) { + var criteria = {} + criteria[operator] = {} + criteria[operator][field] = value + this.params.query = this.params.query || [] + this.params.query.push(criteria) + return this + } + + return queryBuilder +})() diff --git a/src/request-params/request-params-builder.js b/src/request-params/request-params-builder.js index 6564d0e..a6e90e5 100644 --- a/src/request-params/request-params-builder.js +++ b/src/request-params/request-params-builder.js @@ -1,35 +1,29 @@ -//@exclude -'use strict'; +// @exclude +'use strict' /* global corbel, aggregationBuilder, queryBuilder, sortBuilder, pageBuilder */ -//@endexclude - - -(function(aggregationBuilder, queryBuilder, sortBuilder, pageBuilder) { - - - +// @endexclude + +;(function (aggregationBuilder, queryBuilder, sortBuilder, pageBuilder) { + /** + * A module to build Request Params + * @exports requestParamsBuilder + * @namespace + * @memberof app.silkroad + */ + corbel.requestParamsBuilder = corbel.Object.inherit({ + constructor: function () { + this.params = {} + }, /** - * A module to build Request Params - * @exports requestParamsBuilder - * @namespace - * @memberof app.silkroad + * Returns the JSON representation of the params + * @return {JSON} representation of the params */ - corbel.requestParamsBuilder = corbel.Object.inherit({ - constructor: function() { - this.params = {}; - }, - /** - * Returns the JSON representation of the params - * @return {JSON} representation of the params - */ - build: function() { - return this.params; - } - }); - - - corbel.utils.extend(corbel.requestParamsBuilder.prototype, queryBuilder, sortBuilder, aggregationBuilder, pageBuilder); + build: function () { + return this.params + } + }) - return corbel.requestParamsBuilder; + corbel.utils.extend(corbel.requestParamsBuilder.prototype, queryBuilder, sortBuilder, aggregationBuilder, pageBuilder) -})(aggregationBuilder, queryBuilder, sortBuilder, pageBuilder); \ No newline at end of file + return corbel.requestParamsBuilder +})(aggregationBuilder, queryBuilder, sortBuilder, pageBuilder) diff --git a/src/request-params/sort-builder.js b/src/request-params/sort-builder.js index aab93b6..5d393dd 100644 --- a/src/request-params/sort-builder.js +++ b/src/request-params/sort-builder.js @@ -1,32 +1,30 @@ -//@exclude -'use strict'; -/* jshint unused:false */ -//@endexclude +// @exclude +'use strict' +// @endexclude +/* global corbel */ +var sortBuilder = (function () { + var sortBuilder = {} -var sortBuilder = (function() { + /** + * Sets ascending direction to sort param + * @return {RequestParamsBuilder} RequestParamsBuilder + */ + sortBuilder.asc = function (field) { + this.params.sort = this.params.sort || {} + this.params.sort[field] = corbel.Resources.sort.ASC + return this + } - var sortBuilder = {}; + /** + * Sets descending direction to sort param + * @return {RequestParamsBuilder} RequestParamsBuilder + */ + sortBuilder.desc = function (field) { + this.params.sort = this.params.sort || {} + this.params.sort[field] = corbel.Resources.sort.DESC + return this + } - /** - * Sets ascending direction to sort param - * @return {RequestParamsBuilder} RequestParamsBuilder - */ - sortBuilder.asc = function(field) { - this.params.sort = this.params.sort || {}; - this.params.sort[field] = corbel.Resources.sort.ASC; - return this; - }; - - /** - * Sets descending direction to sort param - * @return {RequestParamsBuilder} RequestParamsBuilder - */ - sortBuilder.desc = function(field) { - this.params.sort = this.params.sort || {}; - this.params.sort[field] = corbel.Resources.sort.DESC; - return this; - }; - - return sortBuilder; -})(); \ No newline at end of file + return sortBuilder +})() diff --git a/src/request.js b/src/request.js index a55e5a0..b96a2fb 100644 --- a/src/request.js +++ b/src/request.js @@ -1,9 +1,9 @@ -//@exclude -'use strict'; -//@endexclude - -(function() { +// @exclude +'use strict' +// @endexclude +/* global corbel XMLHttpRequest*/ +;(function () { /** * Request object available for brwoser and node environment * @exports request @@ -16,7 +16,6 @@ * @namespace */ method: { - /** * GET constant * @constant @@ -61,7 +60,7 @@ */ HEAD: 'HEAD' } - }; + } /** * Serialize handlers @@ -73,11 +72,11 @@ * @param {object} data * @return {string} */ - json: function(data, cb) { + json: function (data, cb) { if (typeof data !== 'string') { - cb(JSON.stringify(data)); + cb(JSON.stringify(data)) } else { - cb(data); + cb(data) } }, /** @@ -85,21 +84,21 @@ * @param {object} data * @return {string} */ - 'form-urlencoded': function(data, cb) { - cb(corbel.utils.toURLEncoded(data)); + 'form-urlencoded': function (data, cb) { + cb(corbel.utils.toURLEncoded(data)) }, /** * dataURI serialize handler * @param {object} data * @return {string} */ - dataURI: function(data, cb) { + dataURI: function (data, cb) { if (corbel.Config.isNode) { // in node transform to stream - cb(corbel.utils.toURLEncoded(data)); + cb(corbel.utils.toURLEncoded(data)) } else { // in browser transform to blob - cb(corbel.utils.dataURItoBlob(data)); + cb(corbel.utils.dataURItoBlob(data)) } }, /** @@ -108,26 +107,26 @@ * @param {object} data * @return {ArrayBuffer || Blob} */ - blob: function(data, cb) { - if(data instanceof ArrayBuffer) { - throw new Error('ArrayBuffer is not supported, please use Blob'); - } else { - cb(data); - } + blob: function (data, cb) { + if (data instanceof ArrayBuffer) { + throw new Error('ArrayBuffer is not supported, please use Blob') + } else { + cb(data) + } }, /** * stream serialize handler * @param {object || string} data * @return {UintArray} */ - stream: function(data, cb) { - if(data instanceof ArrayBuffer) { - throw new Error('ArrayBuffer is not supported, please use Blob, File, Stream or ArrayBufferView'); - } else { - cb(data); - } + stream: function (data, cb) { + if (data instanceof ArrayBuffer) { + throw new Error('ArrayBuffer is not supported, please use Blob, File, Stream or ArrayBufferView') + } else { + cb(data) + } } - }; + } /** * Serialize hada with according contentType handler @@ -136,19 +135,19 @@ * @param {string} contentType * @return {Mixed} */ - request.serialize = function(data, contentType, cb) { - var contentTypeSerializable = Object.keys(request.serializeHandlers).filter(function(type) { + request.serialize = function (data, contentType, cb) { + var contentTypeSerializable = Object.keys(request.serializeHandlers).filter(function (type) { if (contentType.indexOf(type) !== -1) { - return type; + return type } - }); + }) - if(contentTypeSerializable.length > 0){ - request.serializeHandlers[contentTypeSerializable[0]](data, cb); - }else{ - cb(data); + if (contentTypeSerializable.length > 0) { + request.serializeHandlers[contentTypeSerializable[0]](data, cb) + } else { + cb(data) } - }; + } /** * Parse handlers @@ -160,16 +159,16 @@ * @param {string} data * @return {mixed} */ - json: function(data) { - data = data || '{}'; + json: function (data) { + data = data || '{}' if (typeof data === 'string') { - data = JSON.parse(data); + data = JSON.parse(data) } - return data; + return data } - // 'blob' type do not require any process - // @todo: xml - }; + // 'blob' type do not require any process + // @todo: xml + } /** * Process the server response data to the specified object/array/blob/byteArray/text @@ -178,24 +177,24 @@ * @param {Stirng} dataType Is an extra param to form the blob object (if the type is blob) * @return {mixed} Processed data */ - request.parse = function(data, responseType, dataType) { - var parsed; - Object.keys(request.parseHandlers).forEach(function(type) { + request.parse = function (data, responseType, dataType) { + var parsed + Object.keys(request.parseHandlers).forEach(function (type) { if (responseType && responseType.indexOf(type) !== -1) { - parsed = request.parseHandlers[type](data, dataType); + parsed = request.parseHandlers[type](data, dataType) } - }); - parsed = parsed || data; - return parsed; - }; + }) + parsed = parsed || data + return parsed + } - function doRequest(module, params, resolver){ + function doRequest (module, params, resolver) { if (corbel.Config.isBrowser) { - //browser - request._browserAjax.call(module, params, resolver); + // browser + request._browserAjax.call(module, params, resolver) } else { - //nodejs - request._nodeAjax.call(module, params, resolver); + // nodejs + request._nodeAjax.call(module, params, resolver) } } @@ -213,16 +212,16 @@ * @param {function} options.error Callback function for handle error in the request * @return {Promise} Promise about the request status and response */ - request.send = function(options, driver) { - options = options || {}; - var module = this; + request.send = function (options, driver) { + options = options || {} + var module = this if (!options.url) { - throw new Error('undefined:url'); + throw new Error('undefined:url') } - if (typeof(options.url) !== 'string') { - throw new Error('invalid:url', options.url); + if (typeof (options.url) !== 'string') { + throw new Error('invalid:url', options.url) } var params = { @@ -234,38 +233,38 @@ responseType: options.responseType, withCredentials: options.withCredentials || true, useCookies: options.useCookies || false - }; + } - params = rewriteRequestToPostIfUrlLengthIsTooLarge(options, params); + params = rewriteRequestToPostIfUrlLengthIsTooLarge(options, params) // default content-type - params.headers['content-type'] = options.contentType || 'application/json'; + params.headers['content-type'] = options.contentType || 'application/json' - var dataMethods = [request.method.PUT, request.method.POST, request.method.PATCH]; + var dataMethods = [request.method.PUT, request.method.POST, request.method.PATCH] - var resolver; - var promise = new Promise(function(resolve, reject) { + var resolver + var promise = new Promise(function (resolve, reject) { resolver = { resolve: resolve, reject: reject - }; + } - if(driver){ - driver.trigger('request', params); + if (driver) { + driver.trigger('request', params) } - }); + }) if (dataMethods.indexOf(params.method) !== -1) { - request.serialize(options.data, params.headers['content-type'], function(serialized){ - params.data = serialized; - doRequest(module, params, resolver); - }); - }else{ - doRequest(module, params, resolver); + request.serialize(options.data, params.headers['content-type'], function (serialized) { + params.data = serialized + doRequest(module, params, resolver) + }) + } else { + doRequest(module, params, resolver) } - return promise; - }; + return promise + } var xhrSuccessStatus = { // file protocol always yields status code 0, assume 200 @@ -273,7 +272,7 @@ // Support: IE9 // #1450: sometimes IE returns 1223 when it should be 204 1223: 204 - }; + } /** * Process server response @@ -282,46 +281,43 @@ * @param {function} callbackSuccess * @param {function} callbackError */ - var processResponse = function(response, resolver, callbackSuccess, callbackError) { - - //xhr = xhr.target || xhr || {}; - var statusCode = xhrSuccessStatus[response.status] || response.status, - statusType = Number(response.status.toString()[0]), - promiseResponse; + var processResponse = function (response, resolver, callbackSuccess, callbackError) { + // xhr = xhr.target || xhr || {} + var statusCode = xhrSuccessStatus[response.status] || response.status + var statusType = Number(response.status.toString()[0]) + var promiseResponse - var data = response.response; - var headers = corbel.utils.keysToLowerCase(response.headers); + var data = response.response + var headers = corbel.utils.keysToLowerCase(response.headers) if (statusType <= 3 && !response.error) { - if (response.response) { - data = request.parse(response.response, response.responseType, response.dataType); + data = request.parse(response.response, response.responseType, response.dataType) } if (callbackSuccess) { - callbackSuccess.call(this, data, statusCode, response.responseObject, headers); + callbackSuccess.call(this, data, statusCode, response.responseObject, headers) } promiseResponse = { data: data, status: statusCode, headers: headers - }; + } - promiseResponse[response.responseObjectType] = response.responseObject; + promiseResponse[response.responseObjectType] = response.responseObject - resolver.resolve(promiseResponse); + resolver.resolve(promiseResponse) } else { - - var disconnected = response.error && response.status === 0; - statusCode = disconnected ? 0 : statusCode; + var disconnected = response.error && response.status === 0 + statusCode = disconnected ? 0 : statusCode if (callbackError) { - callbackError.call(this, response.error, statusCode, response.responseObject, headers); + callbackError.call(this, response.error, statusCode, response.responseObject, headers) } if (response.response) { - data = request.parse(response.response, response.responseType, response.dataType); + data = request.parse(response.response, response.responseType, response.dataType) } promiseResponse = { @@ -329,61 +325,61 @@ status: statusCode, error: response.error, headers: headers - }; + } - promiseResponse[response.responseObjectType] = response.responseObject; + promiseResponse[response.responseObjectType] = response.responseObject - resolver.reject(promiseResponse); + resolver.reject(promiseResponse) } - }; + } - var rewriteRequestToPostIfUrlLengthIsTooLarge = function(options, params) { - var AUTOMATIC_HTTP_METHOD_OVERRIDE = corbel.Config.AUTOMATIC_HTTP_METHOD_OVERRIDE || true; - var HTTP_METHOD_OVERRIDE_WITH_URL_SIZE_BIGGER_THAN = corbel.Config.HTTP_METHOD_OVERRIDE_WITH_URL_SIZE_BIGGER_THAN || 2048; + var rewriteRequestToPostIfUrlLengthIsTooLarge = function (options, params) { + var AUTOMATIC_HTTP_METHOD_OVERRIDE = corbel.Config.AUTOMATIC_HTTP_METHOD_OVERRIDE || true + var HTTP_METHOD_OVERRIDE_WITH_URL_SIZE_BIGGER_THAN = corbel.Config.HTTP_METHOD_OVERRIDE_WITH_URL_SIZE_BIGGER_THAN || 2048 if (AUTOMATIC_HTTP_METHOD_OVERRIDE && params.method === request.method.GET && params.url.length > HTTP_METHOD_OVERRIDE_WITH_URL_SIZE_BIGGER_THAN) { - var url = params.url.split('?'); - params.method = request.method.POST; - params.headers['X-HTTP-Method-Override'] = request.method.GET; - params.url = url[0]; - options.data = encodeUrlToForm(url[1]); - options.contentType = 'application/x-www-form-urlencoded'; + var url = params.url.split('?') + params.method = request.method.POST + params.headers['X-HTTP-Method-Override'] = request.method.GET + params.url = url[0] + options.data = encodeUrlToForm(url[1]) + options.contentType = 'application/x-www-form-urlencoded' } - return params; - }; - - var encodeUrlToForm = function(url) { - var form = {}; - url.split('&').forEach(function(formEntry) { - var formPair = formEntry.split('='); - //value require double encode in Override Method Filter - form[formPair[0]] = formPair[1]; - }); - return form; - }; - - request._getNodeRequestAjax = function(params) { - var requestAjax = require('request'); + return params + } + + var encodeUrlToForm = function (url) { + var form = {} + url.split('&').forEach(function (formEntry) { + var formPair = formEntry.split('=') + // value require double encode in Override Method Filter + form[formPair[0]] = formPair[1] + }) + return form + } + + request._getNodeRequestAjax = function (params) { + var requestAjax = require('request') if (request.isCrossDomain(params.url) && params.withCredentials && params.useCookies) { requestAjax = requestAjax.defaults({ jar: true - }); + }) } - return requestAjax; - }; + return requestAjax + } - request._getNodeRequestCallback = function(context, params, resolver){ - return function(error, response, body) { - var responseType; - var status; + request._getNodeRequestCallback = function (context, params, resolver) { + return function (error, response, body) { + var responseType + var status if (error) { - responseType = undefined; - status = 0; + responseType = undefined + status = 0 } else { - responseType = response.responseType || response.headers['content-type']; - status = response.statusCode; + responseType = response.responseType || response.headers['content-type'] + status = response.statusCode } processResponse.call(context, { @@ -395,93 +391,90 @@ headers: response ? response.headers : {}, responseObjectType: 'response', error: error - }, resolver, params.callbackSuccess, params.callbackError); + }, resolver, params.callbackSuccess, params.callbackError) + } + } - }; - }; - - request._nodeAjax = function(params, resolver) { - var requestAjax = request._getNodeRequestAjax(params); + request._nodeAjax = function (params, resolver) { + var requestAjax = request._getNodeRequestAjax(params) var requestOptions = { method: params.method, url: params.url, - headers: params.headers, - }; + headers: params.headers + } - var data = params.data || ''; + var data = params.data || '' - var callbackRequest = request._getNodeRequestCallback(this, params, resolver); + var callbackRequest = request._getNodeRequestCallback(this, params, resolver) - if(corbel.utils.isStream(data)) { - data.pipe(requestAjax(requestOptions, callbackRequest)); + if (corbel.utils.isStream(data)) { + data.pipe(requestAjax(requestOptions, callbackRequest)) } else { - requestOptions.body = data; - requestAjax(requestOptions, callbackRequest); + requestOptions.body = data + requestAjax(requestOptions, callbackRequest) } - - - }; + } /** * Check if an url should be process as a crossdomain resource. * @param {string} url * @return {Boolean} */ - request.isCrossDomain = function(url) { - if (url && typeof(url) === 'string' && url.indexOf('http') !== -1) { - return true; + request.isCrossDomain = function (url) { + if (url && typeof (url) === 'string' && url.indexOf('http') !== -1) { + return true } else { - return false; + return false } - }; + } /** * https://gist.github.com/monsur/706839 * @param {string} headerStr Headers in string format as returned in xhr.getAllResponseHeaders() * @return {Object} */ - request._parseResponseHeaders = function(headerStr) { - var headers = {}; + request._parseResponseHeaders = function (headerStr) { + var headers = {} if (!headerStr) { - return headers; + return headers } - var headerPairs = headerStr.split('\u000d\u000a'); + var headerPairs = headerStr.split('\u000d\u000a') for (var i = 0; i < headerPairs.length; i++) { - var headerPair = headerPairs[i]; + var headerPair = headerPairs[i] // Can't use split() here because it does the wrong thing // if the header value has the string ": " in it. - var index = headerPair.indexOf('\u003a\u0020'); + var index = headerPair.indexOf('\u003a\u0020') if (index > 0) { - var key = headerPair.substring(0, index); - var val = headerPair.substring(index + 2); - headers[key] = val; + var key = headerPair.substring(0, index) + var val = headerPair.substring(index + 2) + headers[key] = val } } - return headers; - }; + return headers + } - request._browserAjax = function(params, resolver) { - var httpReq = new XMLHttpRequest(); + request._browserAjax = function (params, resolver) { + var httpReq = new XMLHttpRequest() // jshint ignore:line - httpReq.open(params.method, params.url, true); + httpReq.open(params.method, params.url, true) if (request.isCrossDomain(params.url) && params.withCredentials) { - httpReq.withCredentials = true; + httpReq.withCredentials = true } /* add request headers */ for (var header in params.headers) { if (params.headers.hasOwnProperty(header)) { - httpReq.setRequestHeader(header, params.headers[header]); + httpReq.setRequestHeader(header, params.headers[header]) } } // 'blob' support - httpReq.responseType = params.responseType || httpReq.responseType; + httpReq.responseType = params.responseType || httpReq.responseType - httpReq.onload = function(xhr) { - xhr = xhr.target || xhr; // only for mock testing purpose + httpReq.onload = function (xhr) { + xhr = xhr.target || xhr // only for mock testing purpose processResponse.call(this, { responseObject: xhr, @@ -492,17 +485,16 @@ headers: request._parseResponseHeaders(xhr.getAllResponseHeaders()), responseObjectType: 'xhr', error: xhr.error - }, resolver, params.callbackSuccess, params.callbackError); + }, resolver, params.callbackSuccess, params.callbackError) - //delete callbacks - }.bind(this); + // delete callbacks + }.bind(this) - //response fail () - httpReq.onerror = function(xhr) { + // response fail () + httpReq.onerror = function (xhr) { + xhr = xhr.target || xhr // only for fake sinon response xhr - xhr = xhr.target || xhr; // only for fake sinon response xhr - - var error = xhr.error ? xhr.error : true; + var error = xhr.error ? xhr.error : true processResponse.call(this, { responseObject: xhr, @@ -512,19 +504,16 @@ status: xhr.status, responseObjectType: 'xhr', error: error - }, resolver, params.callbackSuccess, params.callbackError); - - }.bind(this); - + }, resolver, params.callbackSuccess, params.callbackError) + }.bind(this) if (params.data) { - httpReq.send(params.data); + httpReq.send(params.data) } else { - //IE fix, send nothing (not null or undefined) - httpReq.send(); + // IE fix, send nothing (not null or undefined) + httpReq.send() } - }; - - return request; + } -})(); + return request +})() diff --git a/src/resources/base-resource.js b/src/resources/base-resource.js index 4bb043d..8d6e4fa 100644 --- a/src/resources/base-resource.js +++ b/src/resources/base-resource.js @@ -1,72 +1,70 @@ -(function() { - //@exclude - 'use strict'; - //@endexclude - - corbel.Resources.BaseResource = corbel.Services.inherit({ - - /** - * Helper function to build the request uri - * @param {String} srcType Type of the resource - * @param {String} srcId Id of the resource - * @param {String} relType Type of the relationed resource - * @param {String} destId Information of the relationed resource - * @return {String} Uri to perform the request - */ - buildUri: function(srcType, srcId, destType, destId) { - - var urlBase = this.driver.config.getCurrentEndpoint(corbel.Resources.moduleName, this._buildPort(this.driver.config)); - - var domain = this.driver.config.get(corbel.Iam.IAM_DOMAIN, 'unauthenticated'); - var customDomain = this.driver.config.get(corbel.Domain.CUSTOM_DOMAIN, domain); - - this.driver.config.set(corbel.Domain.CUSTOM_DOMAIN, undefined); - - var uri = urlBase + customDomain +'/resource/' + srcType; - - if (srcId) { - uri += '/' + srcId; - if (destType) { - uri += '/' + destType; - if (destId) { - uri += ';r=' + destType + '/' + destId; - } - } - } - - return uri; - }, +// @exclude +'use strict' +// @endexclude +/* global corbel */ + +;(function () { + corbel.Resources.BaseResource = corbel.Services.inherit({ + /** + * Helper function to build the request uri + * @param {String} srcType Type of the resource + * @param {String} srcId Id of the resource + * @param {String} relType Type of the relationed resource + * @param {String} destId Information of the relationed resource + * @return {String} Uri to perform the request + */ + buildUri: function (srcType, srcId, destType, destId) { + var urlBase = this.driver.config.getCurrentEndpoint(corbel.Resources.moduleName, this._buildPort(this.driver.config)) + + var domain = this.driver.config.get(corbel.Iam.IAM_DOMAIN, 'unauthenticated') + var customDomain = this.driver.config.get(corbel.Domain.CUSTOM_DOMAIN, domain) + + this.driver.config.set(corbel.Domain.CUSTOM_DOMAIN, undefined) + + var uri = urlBase + customDomain + '/resource/' + srcType + + if (srcId) { + uri += '/' + srcId + if (destType) { + uri += '/' + destType + if (destId) { + uri += ';r=' + destType + '/' + destId + } + } + } - _buildPort: function(config) { - return config.get('resourcesPort', null) || corbel.Resources.defaultPort; - }, + return uri + }, - request: function(args) { - var params = corbel.utils.extend(this.params, args); + _buildPort: function (config) { + return config.get('resourcesPort', null) || corbel.Resources.defaultPort + }, - this.params = {}; //reset instance params + request: function (args) { + var params = corbel.utils.extend(this.params, args) - args.query = corbel.utils.serializeParams(params); + this.params = {} // reset instance params - //call service request implementation - return corbel.Services.prototype.request.apply(this, [args].concat(Array.prototype.slice.call(arguments, 1))); - }, + args.query = corbel.utils.serializeParams(params) - getURL: function(params) { - return this.buildUri(this.type, this.srcId, this.destType) + (params ? '?' + corbel.utils.serializeParams(params) : ''); - }, + // call service request implementation + return corbel.Services.prototype.request.apply(this, [args].concat(Array.prototype.slice.call(arguments, 1))) + }, - getDefaultOptions: function(options) { - var defaultOptions = options ? corbel.utils.clone(options) : {}; + getURL: function (params) { + return this.buildUri(this.type, this.srcId, this.destType) + (params ? '?' + corbel.utils.serializeParams(params) : '') + }, - return defaultOptions; - } + getDefaultOptions: function (options) { + var defaultOptions = options ? corbel.utils.clone(options) : {} - }); + return defaultOptions + } - // extend for inherit requestParamsBuilder methods extensible for all Resources object - corbel.utils.extend(corbel.Resources.BaseResource.prototype, corbel.requestParamsBuilder.prototype); + }) - return corbel.Resources.BaseResource; + // extend for inherit requestParamsBuilder methods extensible for all Resources object + corbel.utils.extend(corbel.Resources.BaseResource.prototype, corbel.requestParamsBuilder.prototype) -})(); + return corbel.Resources.BaseResource +})() diff --git a/src/resources/collection.js b/src/resources/collection.js index 7d5f744..bbff59b 100644 --- a/src/resources/collection.js +++ b/src/resources/collection.js @@ -1,114 +1,111 @@ -(function() { - - //@exclude - 'use strict'; - /*globals corbel */ - //@endexclude +// @exclude +'use strict' +/*globals corbel */ +// @endexclude + +;(function () { + /** + * Collection requests + * @class + * @memberOf Resources + * @param {String} type The collection type + * @param {CorbelDriver} corbel instance + */ + corbel.Resources.Collection = corbel.Resources.BaseResource.inherit({ + constructor: function (type, driver, params) { + this.type = type + corbel.validate.value('type', this.type) + this.driver = driver + this.params = params || {} + }, /** - * Collection requests - * @class - * @memberOf Resources - * @param {String} type The collection type - * @param {CorbelDriver} corbel instance + * Gets a collection of elements, filtered, paginated or sorted + * @method + * @memberOf Resources.CollectionBuilder + * @param {object} options Get options for the request + * @return {Promise} ES6 promise that resolves to an {Array} of Resources or rejects with a {@link CorbelError} + * @see {@link corbel.util.serializeParams} to see a example of the params */ - corbel.Resources.Collection = corbel.Resources.BaseResource.inherit({ - - constructor: function(type, driver, params) { - this.type = type; - corbel.validate.value('type', this.type); - this.driver = driver; - this.params = params || {}; - }, - - /** - * Gets a collection of elements, filtered, paginated or sorted - * @method - * @memberOf Resources.CollectionBuilder - * @param {object} options Get options for the request - * @return {Promise} ES6 promise that resolves to an {Array} of Resources or rejects with a {@link CorbelError} - * @see {@link corbel.util.serializeParams} to see a example of the params - */ - get: function(options) { - options = this.getDefaultOptions(options); - - var args = corbel.utils.extend(options, { - url: this.buildUri(this.type), - method: corbel.request.method.GET, - Accept: options.dataType - }); - - return this.request(args); - }, - - /** - * Adds a new element to a collection - * @method - * @memberOf Resources.CollectionBuilder - * @param {object} data Data array added to the collection - * @param {object} options Options object with dataType request option - * @return {Promise} ES6 promise that resolves to the new resource id or rejects with a {@link CorbelError} - */ - add: function(data, options) { - options = this.getDefaultOptions(options); - - var args = corbel.utils.extend(options, { - url: this.buildUri(this.type), - method: corbel.request.method.POST, - contentType: options.dataType, - Accept: options.dataType, - data: data - }); - - return this.request(args).then(function(res) { - return corbel.Services.getLocationId(res); - }); - }, + get: function (options) { + options = this.getDefaultOptions(options) - /** - * Update every element in a collection, accepts query params - * @method - * @memberOf resources.CollectionBuilder - * @param {Object} data The element to be updated - * @param {Object} options/query Options object with dataType request option - * @return {Promise} ES6 promise that resolves to an {Array} of resources or rejects with a {@link CorbelError} - */ - update: function(data, options) { - options = this.getDefaultOptions(options); + var args = corbel.utils.extend(options, { + url: this.buildUri(this.type), + method: corbel.request.method.GET, + Accept: options.dataType + }) - var args = corbel.utils.extend(options, { - url: this.buildUri(this.type), - method: corbel.request.method.PUT, - contentType: options.dataType, - Accept: options.dataType, - data: data - }); + return this.request(args) + }, - return this.request(args); - }, - - /** - * Delete a collection - * @method - * @memberOf Resources.CollectionBuilder - * @param {object} options Options object with dataType request option - * @return {Promise} ES6 promise that resolves to the new resource id or rejects with a {@link CorbelError} - */ - delete: function(options) { - options = this.getDefaultOptions(options); - - var args = corbel.utils.extend(options, { - url: this.buildUri(this.type), - method: corbel.request.method.DELETE, - contentType: options.dataType, - Accept: options.dataType - }); + /** + * Adds a new element to a collection + * @method + * @memberOf Resources.CollectionBuilder + * @param {object} data Data array added to the collection + * @param {object} options Options object with dataType request option + * @return {Promise} ES6 promise that resolves to the new resource id or rejects with a {@link CorbelError} + */ + add: function (data, options) { + options = this.getDefaultOptions(options) + + var args = corbel.utils.extend(options, { + url: this.buildUri(this.type), + method: corbel.request.method.POST, + contentType: options.dataType, + Accept: options.dataType, + data: data + }) + + return this.request(args).then(function (res) { + return corbel.Services.getLocationId(res) + }) + }, - return this.request(args); - } + /** + * Update every element in a collection, accepts query params + * @method + * @memberOf resources.CollectionBuilder + * @param {Object} data The element to be updated + * @param {Object} options/query Options object with dataType request option + * @return {Promise} ES6 promise that resolves to an {Array} of resources or rejects with a {@link CorbelError} + */ + update: function (data, options) { + options = this.getDefaultOptions(options) - }); + var args = corbel.utils.extend(options, { + url: this.buildUri(this.type), + method: corbel.request.method.PUT, + contentType: options.dataType, + Accept: options.dataType, + data: data + }) - return corbel.Resources.Collection; + return this.request(args) + }, -})(); + /** + * Delete a collection + * @method + * @memberOf Resources.CollectionBuilder + * @param {object} options Options object with dataType request option + * @return {Promise} ES6 promise that resolves to the new resource id or rejects with a {@link CorbelError} + */ + delete: function (options) { + options = this.getDefaultOptions(options) + + var args = corbel.utils.extend(options, { + url: this.buildUri(this.type), + method: corbel.request.method.DELETE, + contentType: options.dataType, + Accept: options.dataType + }) + + return this.request(args) + } + + }) + + return corbel.Resources.Collection +})() diff --git a/src/resources/relation.js b/src/resources/relation.js index 97f8754..25896df 100644 --- a/src/resources/relation.js +++ b/src/resources/relation.js @@ -1,142 +1,140 @@ - (function() { - //@exclude - 'use strict'; - /*globals corbel */ - //@endexclude - - /** - * Relation - * @class - * @memberOf Resources - * @param {String} srcType The source resource type - * @param {String} srcId The source resource id - * @param {String} destType The destination resource type - */ - corbel.Resources.Relation = corbel.Resources.BaseResource.inherit({ - - constructor: function(srcType, srcId, destType, driver, params) { - this.type = srcType; - this.srcId = srcId; - this.destType = destType; - corbel.validate.values(['type', 'srcId', 'destType'],this); - this.driver = driver; - this.params = params || {}; - }, - - /** - * Gets the resources of a relation - * @method - * @memberOf Resources.Relation - * @param {String} dataType Mime type of the expected resource - * @param {String} destId Relationed resource - * @param {Object} params Params of the corbel request - * @return {Promise} ES6 promise that resolves to a relation {Object} or rejects with a {@link CorbelError} - * @see {@link corbel.util.serializeParams} to see a example of the params - */ - get: function(destId, options) { - options = this.getDefaultOptions(options); - var args = corbel.utils.extend(options, { - url: this.buildUri(this.type, this.srcId, this.destType, destId), - method: corbel.request.method.GET, - Accept: options.dataType - }); - - return this.request(args); - }, - - /** - * Adds a new relation between Resources - * @method - * @memberOf Resources.Relation - * @param {String} destId Relationed resource - * @param {Object} relationData Additional data to be added to the relation (in json) - * @return {Promise} ES6 promise that resolves to undefined (void) or rejects with a {@link CorbelError} - * @example uri = '555' - */ - add: function(destId, relationData, options) { - options = this.getDefaultOptions(options); - corbel.validate.value('destId', destId); - - var args = corbel.utils.extend(options, { - url: this.buildUri(this.type, this.srcId, this.destType, destId), - contentType: 'application/json', - data: relationData, - method: corbel.request.method.PUT - }); - - return this.request(args); - }, - - /** - * Adds a new anonymous relation - * @method - * @memberOf Resources.Relation - * @param {Object} relationData Additional data to be added to the relation (in json) - * @return {Promise} ES6 promise that resolves to undefined (void) or rejects with a {@link CorbelError} - * @example uri = '555' - */ - addAnonymous: function(relationData, options) { - options = this.getDefaultOptions(options); - - var args = corbel.utils.extend(options, { - url: this.buildUri(this.type, this.srcId, this.destType), - contentType: 'application/json', - data: relationData, - method: corbel.request.method.POST - }); - - return this.request(args); - }, - - /** - * Move a relation - * @method - * @memberOf Resources.Relation - * @param {Integer} pos The new position - * @return {Promise} ES6 promise that resolves to undefined (void) or rejects with a {@link CorbelError} - */ - move: function(destId, pos, options) { - corbel.validate.value('destId', destId); - var positionStartId = destId.indexOf('/'); - if (positionStartId !== -1){ - destId = destId.substring(positionStartId + 1); - } - - options = this.getDefaultOptions(options); - - var args = corbel.utils.extend(options, { - url: this.buildUri(this.type, this.srcId, this.destType, destId), - contentType: 'application/json', - data: { - '_order': '$pos(' + pos + ')' - }, - method: corbel.request.method.PUT - }); - - return this.request(args); - }, - - /** - * Deletes a relation between Resources - * @method - * @memberOf Resources.Relation - * @param {String} destId Relationed resource - * @return {Promise} ES6 promise that resolves to undefined (void) or rejects with a {@link CorbelError} - * @example - * destId = 'music:Track/555' - */ - delete: function(destId, options) { - options = this.getDefaultOptions(options); - - var args = corbel.utils.extend(options, { - url: this.buildUri(this.type, this.srcId, this.destType, destId), - method: corbel.request.method.DELETE - }); - - return this.request(args); - } - }); - - return corbel.Resources.Relation; - - })(); +;(function () { + // @exclude + 'use strict' + /*globals corbel */ + // @endexclude + + /** + * Relation + * @class + * @memberOf Resources + * @param {String} srcType The source resource type + * @param {String} srcId The source resource id + * @param {String} destType The destination resource type + */ + corbel.Resources.Relation = corbel.Resources.BaseResource.inherit({ + constructor: function (srcType, srcId, destType, driver, params) { + this.type = srcType + this.srcId = srcId + this.destType = destType + corbel.validate.values(['type', 'srcId', 'destType'], this) + this.driver = driver + this.params = params || {} + }, + + /** + * Gets the resources of a relation + * @method + * @memberOf Resources.Relation + * @param {String} dataType Mime type of the expected resource + * @param {String} destId Relationed resource + * @param {Object} params Params of the corbel request + * @return {Promise} ES6 promise that resolves to a relation {Object} or rejects with a {@link CorbelError} + * @see {@link corbel.util.serializeParams} to see a example of the params + */ + get: function (destId, options) { + options = this.getDefaultOptions(options) + var args = corbel.utils.extend(options, { + url: this.buildUri(this.type, this.srcId, this.destType, destId), + method: corbel.request.method.GET, + Accept: options.dataType + }) + + return this.request(args) + }, + + /** + * Adds a new relation between Resources + * @method + * @memberOf Resources.Relation + * @param {String} destId Relationed resource + * @param {Object} relationData Additional data to be added to the relation (in json) + * @return {Promise} ES6 promise that resolves to undefined (void) or rejects with a {@link CorbelError} + * @example uri = '555' + */ + add: function (destId, relationData, options) { + options = this.getDefaultOptions(options) + corbel.validate.value('destId', destId) + + var args = corbel.utils.extend(options, { + url: this.buildUri(this.type, this.srcId, this.destType, destId), + contentType: 'application/json', + data: relationData, + method: corbel.request.method.PUT + }) + + return this.request(args) + }, + + /** + * Adds a new anonymous relation + * @method + * @memberOf Resources.Relation + * @param {Object} relationData Additional data to be added to the relation (in json) + * @return {Promise} ES6 promise that resolves to undefined (void) or rejects with a {@link CorbelError} + * @example uri = '555' + */ + addAnonymous: function (relationData, options) { + options = this.getDefaultOptions(options) + + var args = corbel.utils.extend(options, { + url: this.buildUri(this.type, this.srcId, this.destType), + contentType: 'application/json', + data: relationData, + method: corbel.request.method.POST + }) + + return this.request(args) + }, + + /** + * Move a relation + * @method + * @memberOf Resources.Relation + * @param {Integer} pos The new position + * @return {Promise} ES6 promise that resolves to undefined (void) or rejects with a {@link CorbelError} + */ + move: function (destId, pos, options) { + corbel.validate.value('destId', destId) + var positionStartId = destId.indexOf('/') + if (positionStartId !== -1) { + destId = destId.substring(positionStartId + 1) + } + + options = this.getDefaultOptions(options) + + var args = corbel.utils.extend(options, { + url: this.buildUri(this.type, this.srcId, this.destType, destId), + contentType: 'application/json', + data: { + '_order': '$pos(' + pos + ')' + }, + method: corbel.request.method.PUT + }) + + return this.request(args) + }, + + /** + * Deletes a relation between Resources + * @method + * @memberOf Resources.Relation + * @param {String} destId Relationed resource + * @return {Promise} ES6 promise that resolves to undefined (void) or rejects with a {@link CorbelError} + * @example + * destId = 'music:Track/555' + */ + delete: function (destId, options) { + options = this.getDefaultOptions(options) + + var args = corbel.utils.extend(options, { + url: this.buildUri(this.type, this.srcId, this.destType, destId), + method: corbel.request.method.DELETE + }) + + return this.request(args) + } + }) + + return corbel.Resources.Relation +})() diff --git a/src/resources/resource.js b/src/resources/resource.js index 225f013..68c8e0a 100644 --- a/src/resources/resource.js +++ b/src/resources/resource.js @@ -1,118 +1,113 @@ -(function() { - //@exclude - 'use strict'; - /*globals corbel */ - //@endexclude +;(function () { + // @exclude + 'use strict' + /*globals corbel */ + // @endexclude + + /** + * Builder for resource requests + * @class + * @memberOf resources + * @param {String} type The resource type + * @param {String} id The resource id + */ + corbel.Resources.Resource = corbel.Resources.BaseResource.inherit({ + constructor: function (type, id, driver, params) { + this.type = type + this.id = id + corbel.validate.values(['type', 'id'], this) + + this.driver = driver + this.params = params || {} + }, /** - * Builder for resource requests - * @class - * @memberOf resources - * @param {String} type The resource type - * @param {String} id The resource id + * Gets a resource + * @method + * @memberOf resources.Resource + * @param {Object} options + * @param {String} [options.dataType] Mime type of the expected resource + * @param {Object} [options.params] Additional request parameters + * @return {Promise} ES6 promise that resolves to a Resource {Object} or rejects with a {@link CorbelError} + * @see {@link services.request} to see a example of the params */ - corbel.Resources.Resource = corbel.Resources.BaseResource.inherit({ + get: function (options) { + options = this.getDefaultOptions(options) - constructor: function(type, id, driver, params) { - this.type = type; - this.id = id; - corbel.validate.values(['type', 'id'], this); + var args = corbel.utils.extend(options, { + url: this.buildUri(this.type, this.id), + method: corbel.request.method.GET, + contentType: options.dataType, + Accept: options.dataType + }) - this.driver = driver; - this.params = params || {}; - }, + return this.request(args) + }, - /** - * Gets a resource - * @method - * @memberOf resources.Resource - * @param {Object} options - * @param {String} [options.dataType] Mime type of the expected resource - * @param {Object} [options.params] Additional request parameters - * @return {Promise} ES6 promise that resolves to a Resource {Object} or rejects with a {@link CorbelError} - * @see {@link services.request} to see a example of the params - */ - get: function(options) { - options = this.getDefaultOptions(options); - - - var args = corbel.utils.extend(options, { - url: this.buildUri(this.type, this.id), - method: corbel.request.method.GET, - contentType: options.dataType, - Accept: options.dataType - }); - - return this.request(args); - }, - - - /** - * Updates a resource - * @method - * @memberOf resources.Resource - * @param {Object} data Data to be updated - * @param {Object} options - * @param {String} [options.dataType] Mime tipe of the sent data - * @param {Object} [options.params] Additional request parameters - * @return {Promise} ES6 promise that resolves to undefined (void) or rejects with a {@link CorbelError} - * @see {@link services.request} to see a example of the params - */ - update: function(data, options) { - options = this.getDefaultOptions(options); - - var args = corbel.utils.extend(options, { - url: this.buildUri(this.type, this.id), - method: corbel.request.method.PUT, - data: data, - contentType: options.dataType, - Accept: options.dataType - }); - - return this.request(args); - }, - - - /** - * Updates the ACL of a resource - * @method - * @memberOf resources.Resource - * @param {Object} acl Acl to be updated - * @return {Promise} ES6 promise that resolves to undefined (void) or rejects with a {@link CorbelError} - */ - updateAcl: function(acl) { - var args = { - url: this.buildUri(this.type, this.id), - method: corbel.request.method.PUT, - data: acl, - Accept: 'application/corbel.acl+json' - }; - - return this.request(args); - }, + /** + * Updates a resource + * @method + * @memberOf resources.Resource + * @param {Object} data Data to be updated + * @param {Object} options + * @param {String} [options.dataType] Mime tipe of the sent data + * @param {Object} [options.params] Additional request parameters + * @return {Promise} ES6 promise that resolves to undefined (void) or rejects with a {@link CorbelError} + * @see {@link services.request} to see a example of the params + */ + update: function (data, options) { + options = this.getDefaultOptions(options) - /** - * Deletes a resource - * @method - * @memberOf resources.Resource - * @param {Object} options - * @param {Object} [options.dataType] Mime tipe of the delete data - * @return {Promise} ES6 promise that resolves to undefined (void) or rejects with a {@link CorbelError} - */ - delete: function(options) { - options = this.getDefaultOptions(options); + var args = corbel.utils.extend(options, { + url: this.buildUri(this.type, this.id), + method: corbel.request.method.PUT, + data: data, + contentType: options.dataType, + Accept: options.dataType + }) - var args = corbel.utils.extend(options, { - url: this.buildUri(this.type, this.id), - method: corbel.request.method.DELETE, - contentType: options.dataType, - Accept: options.dataType - }); + return this.request(args) + }, - return this.request(args); - } - }); + /** + * Updates the ACL of a resource + * @method + * @memberOf resources.Resource + * @param {Object} acl Acl to be updated + * @return {Promise} ES6 promise that resolves to undefined (void) or rejects with a {@link CorbelError} + */ + updateAcl: function (acl) { + var args = { + url: this.buildUri(this.type, this.id), + method: corbel.request.method.PUT, + data: acl, + Accept: 'application/corbel.acl+json' + } - return corbel.Resources.Resource; + return this.request(args) + }, -})(); + /** + * Deletes a resource + * @method + * @memberOf resources.Resource + * @param {Object} options + * @param {Object} [options.dataType] Mime tipe of the delete data + * @return {Promise} ES6 promise that resolves to undefined (void) or rejects with a {@link CorbelError} + */ + delete: function (options) { + options = this.getDefaultOptions(options) + + var args = corbel.utils.extend(options, { + url: this.buildUri(this.type, this.id), + method: corbel.request.method.DELETE, + contentType: options.dataType, + Accept: options.dataType + }) + + return this.request(args) + } + }) + + return corbel.Resources.Resource +})() diff --git a/src/resources/resources.js b/src/resources/resources.js index d2f4d15..5c12640 100644 --- a/src/resources/resources.js +++ b/src/resources/resources.js @@ -1,64 +1,60 @@ -(function() { - //@exclude - 'use strict'; - /*globals corbel */ - //@endexclude - - corbel.Resources = corbel.Object.inherit({ - - constructor: function(driver) { - this.driver = driver; - }, - - collection: function(type) { - return new corbel.Resources.Collection(type, this.driver); - }, - - resource: function(type, id) { - return new corbel.Resources.Resource(type, id, this.driver); - }, - - relation: function(srcType, srcId, destType) { - return new corbel.Resources.Relation(srcType, srcId, destType, this.driver); - } - - }, { - - moduleName: 'resources', - defaultPort: 8080, - - sort: { - - /** - * Ascending sort - * @type {String} - * @constant - * @default - */ - ASC: 'asc', - - /** - * Descending sort - * @type {String} - * @constant - * @default - */ - DESC: 'desc' - - }, - - /** - * constant for use to specify all resources wildcard - * @namespace - */ - ALL: '_', - - create: function(driver) { - return new corbel.Resources(driver); - } - - }); - - return corbel.Resources; - -})(); +;(function () { + // @exclude + 'use strict' + /*globals corbel */ + // @endexclude + + corbel.Resources = corbel.Object.inherit({ + constructor: function (driver) { + this.driver = driver + }, + + collection: function (type) { + return new corbel.Resources.Collection(type, this.driver) + }, + + resource: function (type, id) { + return new corbel.Resources.Resource(type, id, this.driver) + }, + + relation: function (srcType, srcId, destType) { + return new corbel.Resources.Relation(srcType, srcId, destType, this.driver) + } + + }, { + moduleName: 'resources', + defaultPort: 8080, + + sort: { + /** + * Ascending sort + * @type {String} + * @constant + * @default + */ + ASC: 'asc', + + /** + * Descending sort + * @type {String} + * @constant + * @default + */ + DESC: 'desc' + + }, + + /** + * constant for use to specify all resources wildcard + * @namespace + */ + ALL: '_', + + create: function (driver) { + return new corbel.Resources(driver) + } + + }) + + return corbel.Resources +})() diff --git a/src/scheduler/scheduler.js b/src/scheduler/scheduler.js index d05bfb9..e229b7d 100644 --- a/src/scheduler/scheduler.js +++ b/src/scheduler/scheduler.js @@ -1,32 +1,30 @@ -(function() { - //@exclude - 'use strict'; - /*globals corbel */ - //@endexclude +;(function () { + // @exclude + 'use strict' + /*globals corbel */ + // @endexclude - corbel.Scheduler = corbel.Object.inherit({ + corbel.Scheduler = corbel.Object.inherit({ + /** + * Create a new SchedulerBuilder + * @param {String} type String + * @return {Scheduler} + */ + constructor: function (driver) { + this.driver = driver + }, - /** - * Create a new SchedulerBuilder - * @param {String} type String - * @return {Scheduler} - */ - constructor: function(driver) { - this.driver = driver; - }, + task: function (id) { + return new corbel.Scheduler.TaskBuilder(this.driver, id) + } + }, { + moduleName: 'scheduler', + defaultPort: 8098, - task: function(id) { - return new corbel.Scheduler.TaskBuilder(this.driver, id); - } - }, { + create: function (driver) { + return new corbel.Scheduler(driver) + } + }) - moduleName: 'scheduler', - defaultPort: 8098, - - create: function(driver) { - return new corbel.Scheduler(driver); - } - }); - - return corbel.Scheduler; -})(); + return corbel.Scheduler +})() diff --git a/src/scheduler/schedulerBuilder.js b/src/scheduler/schedulerBuilder.js index 67067a7..b4c819f 100644 --- a/src/scheduler/schedulerBuilder.js +++ b/src/scheduler/schedulerBuilder.js @@ -1,83 +1,79 @@ -//@exclude -'use strict'; -//@endexclude - -(function() { - - var TaskBuilder = corbel.Scheduler.TaskBuilder = corbel.Services.inherit({ - - constructor: function(driver, id) { - this.uri = 'tasks'; - this.driver = driver; - this.id = id; - }, - - create: function(task) { - console.log('schedulerInterface.task.create', task); - return this.request({ - url: this._buildUri(this.uri), - method: corbel.request.method.POST, - data: task - }). - then(function(res) { - return corbel.Services.getLocationId(res); - }); - }, - - get: function(params) { - console.log('schedulerInterface.task.get', params); - corbel.validate.value('id', this.id); - return this.request({ - url: this._buildUri(this.uri, this.id), - method: corbel.request.method.GET, - query: params ? corbel.utils.serializeParams(params) : null - }); - }, - - update: function(task) { - console.log('schedulerInterface.task.update', task); - corbel.validate.value('id', this.id); - return this.request({ - url: this._buildUri(this.uri, this.id), - method: corbel.request.method.PUT, - data: task - }); - }, - - delete: function() { - console.log('schedulerInterface.task.delete'); - corbel.validate.value('id', this.id); - return this.request({ - url: this._buildUri(this.uri, this.id), - method: corbel.request.method.DELETE - }); - }, - - _buildUri: function(path, id) { - var uri = ''; - var urlBase = this.driver.config.getCurrentEndpoint(corbel.Scheduler.moduleName, this._buildPort(this.driver.config)); - - uri = urlBase + path; - if (id) { - uri += '/' + id; - } - return uri; - }, - - _buildPort: function(config) { - return config.get('schedulerPort', null) || corbel.Notifications.defaultPort; - } - - }, { - - moduleName: 'tasks', - - create: function(driver) { - return new corbel.TaskBuilder(driver); - } - - }); - - return TaskBuilder; - -})(); +// @exclude +'use strict' +// @endexclude +/*globals corbel */ + +;(function () { + var TaskBuilder = corbel.Scheduler.TaskBuilder = corbel.Services.inherit({ + constructor: function (driver, id) { + this.uri = 'tasks' + this.driver = driver + this.id = id + }, + + create: function (task) { + console.log('schedulerInterface.task.create', task) + return this.request({ + url: this._buildUri(this.uri), + method: corbel.request.method.POST, + data: task + }).then(function (res) { + return corbel.Services.getLocationId(res) + }) + }, + + get: function (params) { + console.log('schedulerInterface.task.get', params) + corbel.validate.value('id', this.id) + return this.request({ + url: this._buildUri(this.uri, this.id), + method: corbel.request.method.GET, + query: params ? corbel.utils.serializeParams(params) : null + }) + }, + + update: function (task) { + console.log('schedulerInterface.task.update', task) + corbel.validate.value('id', this.id) + return this.request({ + url: this._buildUri(this.uri, this.id), + method: corbel.request.method.PUT, + data: task + }) + }, + + delete: function () { + console.log('schedulerInterface.task.delete') + corbel.validate.value('id', this.id) + return this.request({ + url: this._buildUri(this.uri, this.id), + method: corbel.request.method.DELETE + }) + }, + + _buildUri: function (path, id) { + var uri = '' + var urlBase = this.driver.config.getCurrentEndpoint(corbel.Scheduler.moduleName, this._buildPort(this.driver.config)) + + uri = urlBase + path + if (id) { + uri += '/' + id + } + return uri + }, + + _buildPort: function (config) { + return config.get('schedulerPort', null) || corbel.Notifications.defaultPort + } + + }, { + moduleName: 'tasks', + + create: function (driver) { + return new corbel.TaskBuilder(driver) + } + + }) + + return TaskBuilder +})() diff --git a/src/services.js b/src/services.js index 01c47e9..8002f9f 100644 --- a/src/services.js +++ b/src/services.js @@ -1,8 +1,9 @@ -//@exclude -'use strict'; -//@endexclude -(function() { +// @exclude +'use strict' +// @endexclude +/*globals corbel */ +;(function () { /** * A base object to inherit from for make corbel-js requests with custom behavior. * @exports Services @@ -10,22 +11,21 @@ * @extends corbel.Object * @memberof corbel */ - var Services = corbel.Services = corbel.Object.inherit({ //instance props - + var Services = corbel.Services = corbel.Object.inherit({ // instance props /** * Creates a new Services * @memberof corbel.Services.prototype * @param {string} id String with the asset id or `all` key * @return {corbel.Services} */ - constructor: function(driver) { - this.driver = driver; + constructor: function (driver) { + this.driver = driver }, - extractLocationId: function(res) { - console.log('corbel-js:service:extractLocationId', res); - var uri = res.jqXHR.getResponseHeader('Location'); - return uri ? uri.substr(uri.lastIndexOf('/') + 1) : undefined; + extractLocationId: function (res) { + console.log('corbel-js:service:extractLocationId', res) + var uri = res.jqXHR.getResponseHeader('Location') + return uri ? uri.substr(uri.lastIndexOf('/') + 1) : undefined }, /** @@ -38,59 +38,53 @@ * @param {Promise} dfd The deferred object to resolve when the ajax request is completed. * @param {object} args The request arguments. */ - request: function(args) { - - this.driver.trigger('service:request:before', args); - - var that = this; - - return this._requestWithRetries(args).then(function(response) { - that.driver.trigger('service:request:after', response); - that.driver.config.set(corbel.Services._UNAUTHORIZED_NUM_RETRIES, 0); - return response; - }).catch(function(error) { - that.driver.trigger('service:request:after', error); - that.driver.config.set(corbel.Services._UNAUTHORIZED_NUM_RETRIES, 0); - throw error; - }); - + request: function (args) { + this.driver.trigger('service:request:before', args) + + var that = this + + return this._requestWithRetries(args).then(function (response) { + that.driver.trigger('service:request:after', response) + that.driver.config.set(corbel.Services._UNAUTHORIZED_NUM_RETRIES, 0) + return response + }).catch(function (error) { + that.driver.trigger('service:request:after', error) + that.driver.config.set(corbel.Services._UNAUTHORIZED_NUM_RETRIES, 0) + throw error + }) }, - _requestWithRetries : function(args){ - var that = this; - var maxRetries = corbel.Services._UNAUTHORIZED_MAX_RETRIES; - var requestParameters = that._buildParams(args); + _requestWithRetries: function (args) { + var that = this + var maxRetries = corbel.Services._UNAUTHORIZED_MAX_RETRIES + var requestParameters = that._buildParams(args) return that._doRequest(requestParameters) - .catch(function(response) { - - var retries = that.driver.config.get(corbel.Services._UNAUTHORIZED_NUM_RETRIES, 0); + .catch(function (response) { + var retries = that.driver.config.get(corbel.Services._UNAUTHORIZED_NUM_RETRIES, 0) if (retries < maxRetries && response.status === corbel.Services._UNAUTHORIZED_STATUS_CODE) { - - //A 401 request within, refresh the token and retry the request. + // A 401 request within, refresh the token and retry the request. return that._refreshToken() - .then(function() { - - that.driver.config.set(corbel.Services._UNAUTHORIZED_NUM_RETRIES, retries + 1); - //@TODO: see if we need to upgrade the token to access assets. - return that._requestWithRetries(args).catch(function(retryResponse) { - // rejects whole promise with the retry response - response = retryResponse; - throw response; - }); - }).catch(function() { - //Has failed refreshing, reject request - console.log('corbeljs:services:token:refresh:fail'); - - throw response; - }); - + .then(function () { + that.driver.config.set(corbel.Services._UNAUTHORIZED_NUM_RETRIES, retries + 1) + // @TODO: see if we need to upgrade the token to access assets. + return that._requestWithRetries(args).catch(function (retryResponse) { + // rejects whole promise with the retry response + response = retryResponse + throw response + }) + }) + .catch(function () { + // Has failed refreshing, reject request + console.log('corbeljs:services:token:refresh:fail') + + throw response + }) } else { - console.log('corbeljs:services:token:no_refresh', response.status); - throw response; + console.log('corbeljs:services:token:no_refresh', response.status) + throw response } - - }); + }) }, /** @@ -99,93 +93,87 @@ * @param {object} params * @return {Promise} */ - _doRequest: function(params) { - var that = this; - return corbel.request.send(params, that.driver).then(function(response) { - - that.driver.config.set(corbel.Services._FORCE_UPDATE_STATUS, 0); - that.driver.config.set(corbel.Services._UNAUTHORIZED_NUM_RETRIES, 0); - - return response; - - }).catch(function(response) { + _doRequest: function (params) { + var that = this + return corbel.request.send(params, that.driver).then(function (response) { + that.driver.config.set(corbel.Services._FORCE_UPDATE_STATUS, 0) + that.driver.config.set(corbel.Services._UNAUTHORIZED_NUM_RETRIES, 0) + + return response + }).catch(function (response) { // Force update if (response.status === corbel.Services._FORCE_UPDATE_STATUS_CODE && response.textStatus === corbel.Services._FORCE_UPDATE_TEXT) { - - var retries = that.driver.config.get(corbel.Services._FORCE_UPDATE_STATUS, 0); + var retries = that.driver.config.get(corbel.Services._FORCE_UPDATE_STATUS, 0) if (retries < corbel.Services._FORCE_UPDATE_MAX_RETRIES) { - retries++; - that.driver.config.set(corbel.Services._FORCE_UPDATE_STATUS, retries); + retries++ + that.driver.config.set(corbel.Services._FORCE_UPDATE_STATUS, retries) - that.driver.trigger('force:update', response); + that.driver.trigger('force:update', response) - throw response; + throw response } else { - throw response; + throw response } } else { - throw response; + throw response } - - }); + }) }, + _refreshToken: function () { + var tokenObject = this.driver.config.get(corbel.Iam.IAM_TOKEN, {}) - _refreshToken : function(){ - var tokenObject = this.driver.config.get(corbel.Iam.IAM_TOKEN, {}); - - return this._refreshHandler(tokenObject); + return this._refreshHandler(tokenObject) }, /** * Default token refresh handler * Only requested once at the same time * @return {Promise} */ - _refreshHandler: function(tokenObject) { - var that = this; + _refreshHandler: function (tokenObject) { + var that = this if (this.driver._refreshHandlerPromise) { - return this.driver._refreshHandlerPromise; + return this.driver._refreshHandlerPromise } if (tokenObject.refreshToken) { - console.log('corbeljs:services:token:refresh'); + console.log('corbeljs:services:token:refresh') this.driver._refreshHandlerPromise = this.driver.iam.token().refresh( tokenObject.refreshToken, - this.driver.config.get(corbel.Iam.IAM_TOKEN_SCOPES, '') - ); - + this.driver.config.get(corbel.Iam.IAM_TOKEN_SCOPES, '')) } else { - console.log('corbeljs:services:token:create'); - this.driver._refreshHandlerPromise = this.driver.iam.token().create(); + console.log('corbeljs:services:token:create') + this.driver._refreshHandlerPromise = this.driver.iam.token().create() } return this.driver._refreshHandlerPromise - .then(function(response) { - that.driver.trigger('token:refresh', response.data); - that.driver._refreshHandlerPromise = null; - return response; - }).catch(function(err) { - that.driver._refreshHandlerPromise = null; - throw err; - }); + .then(function (response) { + that.driver.trigger('token:refresh', response.data) + that.driver._refreshHandlerPromise = null + return response + }) + .catch(function (err) { + that.driver._refreshHandlerPromise = null + throw err + }) }, /** * Add Authorization header with default tokenObject * @param {object} params request builded params */ - _addAuthorization: function(params) { + _addAuthorization: function (params) { // @todo: support to oauth token and custom handlers - var accessToken = this.driver.config.get(corbel.Iam.IAM_TOKEN, {}).accessToken; + var accessToken = this.driver.config.get(corbel.Iam.IAM_TOKEN, {}).accessToken // Use access access token if exists if (accessToken) { - params.headers.Authorization = 'Bearer ' + accessToken; - params.withCredentials = true; + params.headers.Authorization = 'Bearer ' + accessToken + params.withCredentials = true } - return params; + return params }, /** @@ -198,8 +186,7 @@ * @param {object} args * @return {object} */ - _buildParams: function(args) { - + _buildParams: function (args) { // Default values var defaults = { dataType: 'json', @@ -209,69 +196,67 @@ Accept: 'application/json' }, method: corbel.request.method.GET - }; + } // do not modify args object - var params = corbel.utils.defaults({}, args); - params = corbel.utils.defaults(params, defaults); - + var params = corbel.utils.defaults({}, args) + params = corbel.utils.defaults(params, defaults) + if (!params.url) { - throw new Error('You must define an url'); + throw new Error('You must define an url') } if (params.query) { - params.url += '?' + params.query; + params.url += '?' + params.query } - + if (params.noRedirect) { - params.headers['No-Redirect'] = true; + params.headers['No-Redirect'] = true } if (params.Accept) { - params.headers.Accept = params.Accept; - params.dataType = undefined; // Accept & dataType are incompatibles + params.headers.Accept = params.Accept + params.dataType = undefined // Accept & dataType are incompatibles } // set correct accept & contentType in case of blob // @todo: remove contentType+accept same-type constraint if (params.dataType === 'blob') { if (corbel.Config.isBrowser) { - params.headers.Accept = params.data.type; - params.contentType = params.data.type; - params.dataType = undefined; // Accept & dataType are incompatibles + params.headers.Accept = params.data.type + params.contentType = params.data.type + params.dataType = undefined // Accept & dataType are incompatibles } } - params = this._addAuthorization(params); + params = this._addAuthorization(params) - return corbel.utils.pick(params, ['url', 'dataType', 'contentType', 'method', 'headers', 'data', 'dataFilter', 'responseType', 'withCredentials', 'success', 'error']); + return corbel.utils.pick(params, ['url', 'dataType', 'contentType', 'method', 'headers', 'data', 'dataFilter', 'responseType', 'withCredentials', 'success', 'error']) }, /** * @memberof corbel.Services.prototype * @return {string} */ - _buildUri: function() { - - var uri = ''; + _buildUri: function () { + var uri = '' if (this.urlBase.slice(-1) !== '/') { - uri += '/'; + uri += '/' } - Array.prototype.slice.call(arguments).forEach(function(argument) { + Array.prototype.slice.call(arguments).forEach(function (argument) { if (argument) { - uri += argument + '/'; + uri += argument + '/' } - }); + }) // remove last '/' - uri = uri.slice(0, -1); + uri = uri.slice(0, -1) - return this.urlBase + uri; + return this.urlBase + uri } }, { - /** * _FORCE_UPDATE_TEXT constant * @constant @@ -340,16 +325,16 @@ * @param {Promise} res response from a requestXHR * @return {String} id from the Location */ - getLocationId: function(responseObject) { - responseObject = responseObject || {}; - var location; + getLocationId: function (responseObject) { + responseObject = responseObject || {} + var location if (responseObject.xhr) { - location = responseObject.xhr.getResponseHeader('location'); + location = responseObject.xhr.getResponseHeader('location') } else if (responseObject.response && responseObject.response.headers.location) { - location = responseObject.response.headers.location; + location = responseObject.response.headers.location } - return location ? location.substr(location.lastIndexOf('/') + 1) : undefined; + return location ? location.substr(location.lastIndexOf('/') + 1) : undefined }, /** @@ -358,14 +343,13 @@ * @param {string} type * @return {midex} */ - addEmptyJson: function(response, type) { + addEmptyJson: function (response, type) { if (!response && type === 'json') { - response = '{}'; + response = '{}' } - return response; + return response } - }); - - return Services; + }) -})(); + return Services +})() diff --git a/src/utils.js b/src/utils.js index 09ccbaa..129316c 100644 --- a/src/utils.js +++ b/src/utils.js @@ -1,34 +1,33 @@ -//@exclude -'use strict'; -//@endexclude - -(function() { +// @exclude +'use strict' +// @endexclude +/*globals corbel */ +;(function () { /** * A module to some library corbel.utils * @exports utils * @namespace * @memberof corbel */ - var utils = corbel.utils = {}; + var utils = corbel.utils = {} /** * Extend a given object with all the properties in passed-in object(s). * @param {Object} obj * @return {Object} */ - utils.extend = function(obj) { - - Array.prototype.slice.call(arguments, 1).forEach(function(source) { + utils.extend = function (obj) { + Array.prototype.slice.call(arguments, 1).forEach(function (source) { if (source) { for (var prop in source) { - obj[prop] = source[prop]; + obj[prop] = source[prop] } } - }); + }) - return obj; - }; + return obj + } /** * Set up the prototype chain, for subclasses. Uses a hash of prototype properties and class properties to be extended. @@ -36,88 +35,83 @@ * @param {Object} Static object properties * @return {Object} Return a new object that inherit from the context object */ - utils.inherit = function(prototypeProperties, staticProperties) { - var parent = this, - child; - + utils.inherit = function (prototypeProperties, staticProperties) { + var parent = this + var child if (prototypeProperties && prototypeProperties.hasOwnProperty('constructor')) { - child = prototypeProperties.constructor; + child = prototypeProperties.constructor } else { - child = function() { - return parent.apply(this, arguments); - }; + child = function () { + return parent.apply(this, arguments) + } } - utils.extend(child, parent, staticProperties); + utils.extend(child, parent, staticProperties) - var Surrogate = function() { - this.constructor = child; - }; + var Surrogate = function () { + this.constructor = child + } - Surrogate.prototype = parent.prototype; - child.prototype = new Surrogate; // jshint ignore:line + Surrogate.prototype = parent.prototype + child.prototype = new Surrogate() if (prototypeProperties) { - utils.extend(child.prototype, prototypeProperties); + utils.extend(child.prototype, prototypeProperties) } - child.__super__ = parent.prototype; - - return child; - - }; + child.__super__ = parent.prototype + return child + } /** * Generate a uniq random GUID */ - utils.guid = function() { - - function s4() { + utils.guid = function () { + function s4 () { return Math.floor((1 + Math.random()) * 0x10000) .toString(16) - .substring(1); + .substring(1) } return s4() + s4() + '-' + s4() + '-' + s4() + '-' + - s4() + '-' + s4() + s4() + s4(); - }; + s4() + '-' + s4() + s4() + s4() + } /** * Reload browser */ - utils.reload = function() { + utils.reload = function () { if (window !== undefined) { - window.location.reload(); + window.location.reload() } - }; + } /** * Serialize a plain object to query string * @param {Object} obj Plain object to serialize * @return {String} */ - utils.param = function(obj) { - var str = []; + utils.param = function (obj) { + var str = [] for (var p in obj) { if (obj.hasOwnProperty(p)) { - str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p])); + str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p])) } } - return str.join('&'); - }; - + return str.join('&') + } - utils.toURLEncoded = function(obj) { - var str = []; + utils.toURLEncoded = function (obj) { + var str = [] for (var p in obj) { if (obj.hasOwnProperty(p)) { - str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p])); + str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p])) } } - return str.join('&'); - }; + return str.join('&') + } /** * Translate this full exampe query to a Corbel Compliant QueryString @@ -184,175 +178,175 @@ * aggregation: { * '$count': '*' * } - * }; + * } */ - utils.serializeParams = function(params) { - var result = ''; + utils.serializeParams = function (params) { + var result = '' if (params === undefined || params === null) { - return result; + return result } if (!(params instanceof Object) && (typeof params !== 'object')) { - throw new Error('expected params to be an Object type, but got ' + typeof params); + throw new Error('expected params to be an Object type, but got ' + typeof params) } - function getJsonEncodedStringify(param) { - return encodeURIComponent(JSON.stringify(param)); + function getJsonEncodedStringify (param) { + return encodeURIComponent(JSON.stringify(param)) } if (params.aggregation) { - result = 'api:aggregation=' + getJsonEncodedStringify(params.aggregation); + result = 'api:aggregation=' + getJsonEncodedStringify(params.aggregation) } - function queryObjectToString(params, key) { - var result = ''; - var query; - params.queryDomain = params.queryDomain || 'api'; - result += params.queryDomain + ':' + key + '='; + function queryObjectToString (params, key) { + var result = '' + var query + params.queryDomain = params.queryDomain || 'api' + result += params.queryDomain + ':' + key + '=' try { if (typeof params[key] === 'string') { - query = JSON.parse(params[key]); + query = JSON.parse(params[key]) } else { - //Clone the object we don't want to modify the original query object - query = JSON.parse(JSON.stringify(params[key])); - } + // Clone the object we don't want to modify the original query object + query = JSON.parse(JSON.stringify(params[key])) + } - result += getJsonEncodedStringify(query); + result += getJsonEncodedStringify(query) - return result; + return result } catch (e) { - //Return the query even if it is not a valid object - return result + params[key]; + // Return the query even if it is not a valid object + return result + params[key] } } if (params.query) { - params.queryDomain = params.queryDomain || 'api'; - result += result ? '&' : ''; - result += queryObjectToString(params, 'query'); + params.queryDomain = params.queryDomain || 'api' + result += result ? '&' : '' + result += queryObjectToString(params, 'query') } if (params.queries) { - params.queries.forEach(function(query) { - result += result ? '&' : ''; - result += queryObjectToString(query, 'query'); - }); + params.queries.forEach(function (query) { + result += result ? '&' : '' + result += queryObjectToString(query, 'query') + }) } if (params.condition) { - params.queryDomain = params.queryDomain || 'api'; - result += result ? '&' : ''; - result += queryObjectToString(params, 'condition'); + params.queryDomain = params.queryDomain || 'api' + result += result ? '&' : '' + result += queryObjectToString(params, 'condition') } if (params.conditions) { - params.conditions.forEach(function(condition) { - result += result ? '&' : ''; - result += queryObjectToString(condition, 'condition'); - }); + params.conditions.forEach(function (condition) { + result += result ? '&' : '' + result += queryObjectToString(condition, 'condition') + }) } if (params.search) { - result += result ? '&' : ''; + result += result ? '&' : '' - result += 'api:search='; + result += 'api:search=' if (params.search instanceof Object) { - result += getJsonEncodedStringify(params.search); + result += getJsonEncodedStringify(params.search) } else { - result += encodeURIComponent(params.search); + result += encodeURIComponent(params.search) } if (params.hasOwnProperty('indexFieldsOnly')) { - result += '&api:indexFieldsOnly=' + getJsonEncodedStringify(params.indexFieldsOnly); + result += '&api:indexFieldsOnly=' + getJsonEncodedStringify(params.indexFieldsOnly) } } if (params.distinct) { - result += result ? '&' : ''; - result += 'api:distinct=' + encodeURIComponent((params.distinct instanceof Array ? params.distinct.join(',') : params.distinct)); + result += result ? '&' : '' + result += 'api:distinct=' + encodeURIComponent((params.distinct instanceof Array ? params.distinct.join(',') : params.distinct)) } if (params.sort) { - result += result ? '&' : ''; - result += 'api:sort=' + getJsonEncodedStringify(params.sort); + result += result ? '&' : '' + result += 'api:sort=' + getJsonEncodedStringify(params.sort) } if (params.pagination) { if (params.pagination.page || params.pagination.page === 0) { - result += result ? '&' : ''; - result += 'api:page=' + params.pagination.page; + result += result ? '&' : '' + result += 'api:page=' + params.pagination.page } if (params.pagination.pageSize || params.pagination.pageSize === 0) { - result += result ? '&' : ''; - result += 'api:pageSize=' + params.pagination.pageSize; + result += result ? '&' : '' + result += 'api:pageSize=' + params.pagination.pageSize } } if (params.customQueryParams) { - Object.keys(params.customQueryParams).forEach(function(param) { - result += result ? '&' : ''; - result += param + '=' + encodeURIComponent(params.customQueryParams[param]); - }); + Object.keys(params.customQueryParams).forEach(function (param) { + result += result ? '&' : '' + result += param + '=' + encodeURIComponent(params.customQueryParams[param]) + }) } - return result; - }; + return result + } - utils.defaults = function(destiny, defaults) { - Object.keys(defaults).forEach(function(key) { - if (typeof(destiny[key]) === 'undefined') { - destiny[key] = defaults[key]; + utils.defaults = function (destiny, defaults) { + Object.keys(defaults).forEach(function (key) { + if (typeof (destiny[key]) === 'undefined') { + destiny[key] = defaults[key] } - }); + }) - return destiny; - }; + return destiny + } - utils.pick = function(object, keys) { - var destiny = {}; + utils.pick = function (object, keys) { + var destiny = {} - keys.forEach(function(key) { - destiny[key] = object[key]; - }); + keys.forEach(function (key) { + destiny[key] = object[key] + }) - return destiny; - }; + return destiny + } - utils.clone = function clone(item) { + utils.clone = function clone (item) { if (!item) { - return item; + return item } // null, undefined values check - var types = [Number, String, Boolean], - result; + var types = [Number, String, Boolean] + var result - // normalizing primitives if someone did new String('aaa'), or new Number('444'); - types.forEach(function(type) { + // normalizing primitives if someone did new String('aaa'), or new Number('444') + types.forEach(function (type) { if (item instanceof type) { - result = type(item); + result = type(item) } - }); + }) if (typeof result === 'undefined') { if (Object.prototype.toString.call(item) === '[object Array]') { - result = []; - item.forEach(function(child, index) { - result[index] = clone(child); - }); + result = [] + item.forEach(function (child, index) { + result[index] = clone(child) + }) } else if (typeof item === 'object') { // testing that this is DOM if (item.nodeType && typeof item.cloneNode === 'function') { - result = item.cloneNode(true); + result = item.cloneNode(true) } else if (!item.prototype) { // check that this is a literal if (item instanceof Date) { - result = new Date(item); + result = new Date(item) } else { // it is an object literal - result = {}; + result = {} for (var i in item) { - result[i] = clone(item[i]); + result[i] = clone(item[i]) } } } else { @@ -360,18 +354,18 @@ // just keep the reference, or create new object if (false && item.constructor) { // would not advice to do that, reason? Read below - result = new item.constructor(); + result = new item.constructor() } else { - result = item; + result = item } } } else { - result = item; + result = item } } - return result; - }; + return result + } /** * Change the keys of the object to lowercase due to @@ -379,61 +373,61 @@ * @param {Object} obj object which keys will converted to lowercase * @return {Object} */ - utils.keysToLowerCase = function(obj) { - if (obj === undefined || obj === null){ - return obj; + utils.keysToLowerCase = function (obj) { + if (obj === undefined || obj === null) { + return obj } else { - var key; - var keys = Object.keys(obj); - var n = keys.length; - var newobj = {}; + var key + var keys = Object.keys(obj) + var n = keys.length + var newobj = {} while (n--) { - key = keys[n]; - newobj[key.toLowerCase()] = obj[key]; + key = keys[n] + newobj[key.toLowerCase()] = obj[key] } - return newobj; + return newobj } - }; + } - utils.isJSON = function(string) { + utils.isJSON = function (string) { try { - JSON.parse(string); + JSON.parse(string) } catch (e) { - return false; + return false } - return true; - }; + return true + } - utils.isStream = function(data){ + utils.isStream = function (data) { if (data.pipe && typeof data.pipe === 'function') { - return true; + return true } else { - return false; + return false } - }; + } - utils.arrayToObject = function(array) { - var object = {}; - array.map(function(element, index){ - object[index] = element; - }); - return object; - }; + utils.arrayToObject = function (array) { + var object = {} + array.map(function (element, index) { + object[index] = element + }) + return object + } /** * Creates a copy of Array with the same inner elements * @param {Array} list The original array to copy * @return {Array} A copy version of the array */ - utils.copyArray = function(list) { - var newList = new Array(list.length); - var i = list.length; - while(i--) { - newList[i] = list[i]; + utils.copyArray = function (list) { + var newList = new Array(list.length) + var i = list.length + while (i--) { + newList[i] = list[i] } - return newList; - }; + return newList + } /** * Convert data URI to Blob. @@ -441,16 +435,15 @@ * @param {string} dataURI * @return {Blob} */ - utils.dataURItoBlob = function(dataURI) { - - var serialize; + utils.dataURItoBlob = function (dataURI) { + var serialize if (corbel.Config.isNode) { - console.log('NODE'); + console.log('NODE') // node environment - serialize = require('atob'); + serialize = require('atob') } else { - console.log('BROWSER'); - serialize = root.atob; + console.log('BROWSER') + serialize = root.atob } /* @@ -461,41 +454,40 @@ * Phrantom has ton Blob() constructor support, * use BlobBuilder instead. */ - var BlobBuilder; - var BlobConstructor; + var BlobBuilder + var BlobConstructor if (corbel.Config.isBrowser) { BlobBuilder = window.BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || - window.MSBlobBuilder; - BlobConstructor = window.Blob; + window.MSBlobBuilder + BlobConstructor = window.Blob } // convert base64 to raw binary data held in a string - var byteString = serialize(dataURI.split(',')[1]); + var byteString = serialize(dataURI.split(',')[1]) // separate out the mime component - var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]; + var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0] // write the bytes of the string to an ArrayBuffer - var arrayBuffer = new ArrayBuffer(byteString.length); - var _ia = new Uint8Array(arrayBuffer); + var arrayBuffer = new ArrayBuffer(byteString.length) + var _ia = new Uint8Array(arrayBuffer) for (var i = 0; i < byteString.length; i++) { - _ia[i] = byteString.charCodeAt(i); + _ia[i] = byteString.charCodeAt(i) } - var blob; + var blob if (BlobBuilder) { - blob = new BlobBuilder(); - blob.append(arrayBuffer); - blob = blob.getBlob(mimeString); + blob = new BlobBuilder() + blob.append(arrayBuffer) + blob = blob.getBlob(mimeString) } else { blob = new BlobConstructor([_ia], { type: mimeString - }); + }) } - return blob; - }; - - return utils; + return blob + } -})(); + return utils +})() diff --git a/src/validate.js b/src/validate.js index cef640f..fb6cf6b 100644 --- a/src/validate.js +++ b/src/validate.js @@ -1,133 +1,129 @@ -//@exclude -'use strict'; -//@endexclude - -(function() { - - - - /** - * A module to make values validation. - * @exports validate - * @namespace - * @memberof app - */ - corbel.validate = {}; - - corbel.validate.values = function(keys, obj){ - var that = this; - keys.forEach(function(key){ - that.value(key, obj[key]); - }); - return true; - }; - - corbel.validate.value = function(key, value){ - return this.isDefined(value, key + ' value is mandatory and cannot be undefined'); - }; - - - /** - * Checks if some value is not undefined - * @param {Mixed} value - * @param {String} [message] - * @throws {Error} If return value is false and message are defined - * @return {Boolean} - */ - corbel.validate.isDefined = function(value, message) { - var isUndefined = value === undefined; - - if (isUndefined && message) { - throw new Error(message); - } - return !isUndefined; - }; - - /** - * Checks if some value is defined and throw error - * @param {Mixed} value - * @param {String} [message] - * @throws {Error} If return value is false and message are defined - * @return {Boolean} - */ - - corbel.validate.failIfIsDefined = function(value, message) { - var isDefined = value !== undefined; - - if (isDefined && message) { - throw new Error(message); - } - return !isDefined; - }; - - /** - * Checks whenever value are null or not - * @param {Mixed} value - * @param {String} [message] - * @throws {Error} If return value is false and message are defined - * @return {Boolean} - */ - corbel.validate.isNotNull = function(value, message) { - var isNull = value === null; - - if (isNull && message) { - throw new Error(message); - } - return !isNull; - }; - - /** - * Checks whenever a value is not null and not undefined - * @param {Mixed} value - * @param {String} [message] - * @throws {Error} If return value is false and message are defined - * @return {Boolean} - */ - corbel.validate.isValue = function(value, message) { - return this.isDefined(value, message) && this.isNotNull(value, message); - }; - - /** - * Checks if a variable is a type of object - * @param {object} test object - * @return {Boolean} - */ - corbel.validate.isObject = function(obj) { - return typeof obj === 'object'; - }; - - /** - * Checks whenever a value is greater than other - * @param {Mixed} value - * @param {Mixed} greaterThan - * @param {String} [message] - * @throws {Error} If return value is false and message are defined - * @return {Boolean} - */ - corbel.validate.isGreaterThan = function(value, greaterThan, message) { - var gt = this.isValue(value) && value > greaterThan; - - if (!gt && message) { - throw new Error(message); - } - return gt; - }; - - /** - * Checks whenever a value is greater or equal than other - * @param {Mixed} value - * @param {Mixed} isGreaterThanOrEqual - * @param {String} [message] - * @throws {Error} If return value is false and message are defined - * @return {Boolean} - */ - corbel.validate.isGreaterThanOrEqual = function(value, isGreaterThanOrEqual, message) { - var gte = this.isValue(value) && value >= isGreaterThanOrEqual; - - if (!gte && message) { - throw new Error(message); - } - return gte; - }; - -})(); \ No newline at end of file +// @exclude +'use strict' +// @endexclude +/*globals corbel */ + +;(function () { + /** + * A module to make values validation. + * @exports validate + * @namespace + * @memberof app + */ + corbel.validate = {} + + corbel.validate.values = function (keys, obj) { + var that = this + keys.forEach(function (key) { + that.value(key, obj[key]) + }) + return true + } + + corbel.validate.value = function (key, value) { + return this.isDefined(value, key + ' value is mandatory and cannot be undefined') + } + + /** + * Checks if some value is not undefined + * @param {Mixed} value + * @param {String} [message] + * @throws {Error} If return value is false and message are defined + * @return {Boolean} + */ + corbel.validate.isDefined = function (value, message) { + var isUndefined = value === undefined + + if (isUndefined && message) { + throw new Error(message) + } + return !isUndefined + } + + /** + * Checks if some value is defined and throw error + * @param {Mixed} value + * @param {String} [message] + * @throws {Error} If return value is false and message are defined + * @return {Boolean} + */ + + corbel.validate.failIfIsDefined = function (value, message) { + var isDefined = value !== undefined + + if (isDefined && message) { + throw new Error(message) + } + return !isDefined + } + + /** + * Checks whenever value are null or not + * @param {Mixed} value + * @param {String} [message] + * @throws {Error} If return value is false and message are defined + * @return {Boolean} + */ + corbel.validate.isNotNull = function (value, message) { + var isNull = value === null + + if (isNull && message) { + throw new Error(message) + } + return !isNull + } + + /** + * Checks whenever a value is not null and not undefined + * @param {Mixed} value + * @param {String} [message] + * @throws {Error} If return value is false and message are defined + * @return {Boolean} + */ + corbel.validate.isValue = function (value, message) { + return this.isDefined(value, message) && this.isNotNull(value, message) + } + + /** + * Checks if a variable is a type of object + * @param {object} test object + * @return {Boolean} + */ + corbel.validate.isObject = function (obj) { + return typeof obj === 'object' + } + + /** + * Checks whenever a value is greater than other + * @param {Mixed} value + * @param {Mixed} greaterThan + * @param {String} [message] + * @throws {Error} If return value is false and message are defined + * @return {Boolean} + */ + corbel.validate.isGreaterThan = function (value, greaterThan, message) { + var gt = this.isValue(value) && value > greaterThan + + if (!gt && message) { + throw new Error(message) + } + return gt + } + + /** + * Checks whenever a value is greater or equal than other + * @param {Mixed} value + * @param {Mixed} isGreaterThanOrEqual + * @param {String} [message] + * @throws {Error} If return value is false and message are defined + * @return {Boolean} + */ + corbel.validate.isGreaterThanOrEqual = function (value, isGreaterThanOrEqual, message) { + var gte = this.isValue(value) && value >= isGreaterThanOrEqual + + if (!gte && message) { + throw new Error(message) + } + return gte + } +})() diff --git a/src/webfs/webfs.js b/src/webfs/webfs.js index bb6b2dc..d11ff21 100644 --- a/src/webfs/webfs.js +++ b/src/webfs/webfs.js @@ -1,8 +1,9 @@ -(function() { - //@exclude - 'use strict'; - //@endexclude +// @exclude +'use strict' +// @endexclude +/*globals corbel */ +;(function () { /** * A webfs API factory * @exports corbel.Webfs @@ -11,23 +12,21 @@ * @memberof corbel */ corbel.Webfs = corbel.Object.inherit({ - - /** + /* * Creates a new WebfsBuilder * @memberof corbel.Webfs.prototype - * @param {string} id String with the resource id + * @param {string} id String with the resource id * @return {corbel.Webfs.WebfsBuilder} */ - constructor: function(driver) { - this.driver = driver; + constructor: function (driver) { + this.driver = driver }, - webfs: function(id) { - return new corbel.Webfs.WebfsBuilder(this.driver, id); + webfs: function (id) { + return new corbel.Webfs.WebfsBuilder(this.driver, id) } }, { - /** * moduleName constant * @constant @@ -52,12 +51,11 @@ * @param {corbel} corbel instance driver * @return {corbel.Webfs.WebfsBuilder} */ - create: function(driver) { - return new corbel.Webfs(driver); + create: function (driver) { + return new corbel.Webfs(driver) } - }); - - return corbel.Webfs; + }) -})(); + return corbel.Webfs +})() diff --git a/src/webfs/webfsBuilder.js b/src/webfs/webfsBuilder.js index 53b6982..bc9e312 100644 --- a/src/webfs/webfsBuilder.js +++ b/src/webfs/webfsBuilder.js @@ -1,9 +1,9 @@ -//@exclude -'use strict'; -//@endexclude - -(function() { +// @exclude +'use strict' +// @endexclude +/*globals corbel */ +;(function () { /** * Module for retrieve content of S3 * @exports WebfsBuilder @@ -12,15 +12,14 @@ * @memberof corbel.Webfs */ var WebfsBuilder = corbel.Webfs.WebfsBuilder = corbel.Services.inherit({ - /** * Creates a new WebfsBuilder * @memberof corbel.Webfs.WebfsBuilder.prototype * @return {corbel.Webfs.WebfsBuilder} */ - constructor: function(driver, id) { - this.driver = driver; - this.id = id; + constructor: function (driver, id) { + this.driver = driver + this.id = id }, /** @@ -29,34 +28,31 @@ * @param {object} [params] Params of a {@link corbel.request} * @return {Promise} Promise that resolves with a resource or rejects with a {@link CorbelError} */ - get: function(params) { - - corbel.validate.value('id', this.id); + get: function (params) { + corbel.validate.value('id', this.id) - var options = params ? corbel.utils.clone(params) : {}; + var options = params ? corbel.utils.clone(params) : {} var args = corbel.utils.extend(options, { url: this._buildUri(this.id), method: corbel.request.method.GET, query: params ? corbel.utils.serializeParams(params) : null - }); - - return this.request(args); + }) + return this.request(args) }, - _buildUri: function(id) { - var urlBase = this.driver.config.getCurrentEndpoint(corbel.Webfs.moduleName, this._buildPort(this.driver.config)); + _buildUri: function (id) { + var urlBase = this.driver.config.getCurrentEndpoint(corbel.Webfs.moduleName, this._buildPort(this.driver.config)) - return urlBase + id; + return urlBase + id }, - _buildPort: function(config) { - return config.get('webfsPort', null) || corbel.Webfs.defaultPort; + _buildPort: function (config) { + return config.get('webfsPort', null) || corbel.Webfs.defaultPort } }, { - /** * GET constant * @constant @@ -72,12 +68,11 @@ * @type {string} * @default */ - create: function(driver) { - return new corbel.Webfs.WebfsBuilder(driver); + create: function (driver) { + return new corbel.Webfs.WebfsBuilder(driver) } - }); - - return WebfsBuilder; + }) -})(); + return WebfsBuilder +})() diff --git a/test/browser/test-suite.js b/test/browser/test-suite.js index 7836185..b87f247 100644 --- a/test/browser/test-suite.js +++ b/test/browser/test-suite.js @@ -1,8 +1,7 @@ -'use strict'; +'use strict' -(function() { +;(function () { + // @include ./unit/request.js + // @include ./unit/resource-binary.js - // @include ./unit/request.js - // @include ./unit/resource-binary.js - -})(); \ No newline at end of file +})() diff --git a/test/browser/unit/request.js b/test/browser/unit/request.js index a31e08a..6627f9d 100644 --- a/test/browser/unit/request.js +++ b/test/browser/unit/request.js @@ -1,421 +1,408 @@ -'use strict'; - -describe('corbel-js browser', function() { - - var sandbox; - this.timeout(4000); - var fakeServer; - - beforeEach(function() { - sandbox = sinon.sandbox.create(); - fakeServer = sinon.fakeServer.create(); - fakeServer.autoRespond = true; - }); - - afterEach(function() { - sandbox.restore(); - fakeServer.restore(); - }); - - it('corbel-js contains all modules', function() { - expect(corbel).to.include.keys('request'); - }); - - describe('request module', function() { - - var url = '/url', - request; - - before(function() { - request = corbel.request; - }); - - it('should has own properties', function() { - expect(request).to.include.keys('method'); - expect(request.method).to.include.keys('GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'PATCH', 'HEAD'); - }); - - it('expected methods are available', function() { - expect(request).to.respondTo('send'); - }); - - ['GET', 'POST', 'PATCH', 'PUT', 'HEAD'].forEach(function(verb) { - it('send method accepts http ' + verb + ' verb', function(done) { +'use strict' +/* globals describe it before beforeEach afterEach sinon corbel expect Blob*/ + +describe('corbel-js browser', function () { + var sandbox + this.timeout(4000) + var fakeServer + + beforeEach(function () { + sandbox = sinon.sandbox.create() + fakeServer = sinon.fakeServer.create() + fakeServer.autoRespond = true + }) + + afterEach(function () { + sandbox.restore() + fakeServer.restore() + }) + + it('corbel-js contains all modules', function () { + expect(corbel).to.include.keys('request') + }) + + describe('request module', function () { + var url = '/url' + var request + + before(function () { + request = corbel.request + }) + + it('should has own properties', function () { + expect(request).to.include.keys('method') + expect(request.method).to.include.keys('GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'PATCH', 'HEAD') + }) + + it('expected methods are available', function () { + expect(request).to.respondTo('send') + }) + + ;['GET', 'POST', 'PATCH', 'PUT', 'HEAD'].forEach(function (verb) { + it('send method accepts http ' + verb + ' verb', function (done) { var fakeResponse = [ 200, { 'Content-type': 'application/json' }, '{}' - ]; + ] - fakeServer.respondWith(verb, url, fakeResponse); + fakeServer.respondWith(verb, url, fakeResponse) var promise = request.send({ method: verb, url: url - }); - - expect(promise).to.be.fulfilled.and.should.notify(done); - - }); - }); - + }) - it('send method throws an error if no url setting', function() { + expect(promise).to.be.fulfilled.and.should.notify(done) + }) + }) - var fn = function() { + it('send method throws an error if no url setting', function () { + var fn = function () { return request.send({ method: 'GET' - }); - }; - - expect(fn).to.throw('undefined:url'); - }); + }) + } - it('send mehtod returns a promise', function() { + expect(fn).to.throw('undefined:url') + }) + it('send mehtod returns a promise', function () { var promise = request.send({ method: 'GET', url: url - }); + }) - expect(promise).to.be.instanceof(Promise); - }); + expect(promise).to.be.instanceof(Promise) + }) - it('send mehtod 200 returns a promise and it resolves', function(done) { + it('send mehtod 200 returns a promise and it resolves', function (done) { var fakeResponse = [ 200, { 'Content-type': 'application/json' }, '{}' - ]; + ] - fakeServer.respondWith('GET', url, fakeResponse); + fakeServer.respondWith('GET', url, fakeResponse) expect(request.send({ method: 'GET', url: url - })).to.be.fulfilled.and.should.notify(done); - - }); + })).to.be.fulfilled.and.should.notify(done) + }) - it('send mehtod 404 returns a promise and reject it', function(done) { + it('send mehtod 404 returns a promise and reject it', function (done) { var fakeResponse = [ 404, { 'Content-type': 'application/json' }, '{}' - ]; + ] - fakeServer.respondWith('GET', url, fakeResponse); + fakeServer.respondWith('GET', url, fakeResponse) var promise = request.send({ method: 'GET', url: url - }); + }) - expect(promise).to.be.rejected.then(function(error) { - expect(error.status).to.be.equal(404); - }).should.notify(done); + expect(promise).to.be.rejected.then(function (error) { + expect(error.status).to.be.equal(404) + }).should.notify(done) + }) - }); - - it('send mehtod 500 returns a promise and reject it', function(done) { + it('send mehtod 500 returns a promise and reject it', function (done) { var fakeResponse = [ 500, { 'Content-type': 'application/json' }, '{}' - ]; + ] - fakeServer.respondWith('GET', url, fakeResponse); + fakeServer.respondWith('GET', url, fakeResponse) var promise = request.send({ method: 'GET', url: url - }); - - promise.catch(function(error) { - expect(error.status).to.be.equal(500); - done(); - }); - }); + }) + promise.catch(function (error) { + expect(error.status).to.be.equal(500) + done() + }) + }) - it('send method returns a promise and it reject when client is disconnected', function(done) { - - fakeServer.respondWith('GET', url, function(request) { - request.error = true; + it('send method returns a promise and it reject when client is disconnected', function (done) { + fakeServer.respondWith('GET', url, function (request) { + request.error = true request.setResponseHeaders({ 'Content-Type': 'text/html', status: 0 - }); - request.setResponseBody(''); - }); + }) + request.setResponseBody('') + }) var promise = request.send({ method: 'GET', url: url - }); - - expect(promise).to.be.rejected.then(function(error) { - expect(error.status).to.be.equal(0); - }).should.notify(done); - - }); + }) - it('send method returns a promise and it returns status 200 when client status 0 but there is no disconnection error', function(done) { - - fakeServer.respondWith('GET', url, function(request) { + expect(promise).to.be.rejected.then(function (error) { + expect(error.status).to.be.equal(0) + }).should.notify(done) + }) + it('send method returns a promise and it returns status 200 when client status 0 but there is no disconnection error', function (done) { + fakeServer.respondWith('GET', url, function (request) { request.setResponseHeaders({ 'Content-Type': 'text/html', status: 0 - }); - request.setResponseBody(''); - }); + }) + request.setResponseBody('') + }) var promise = request.send({ method: 'GET', url: url - }); + }) - expect(promise).to.be.fulfilled.then(function(response) { - expect(response.status).to.be.equal(200); - }).should.notify(done); + expect(promise).to.be.fulfilled.then(function (response) { + expect(response.status).to.be.equal(200) + }).should.notify(done) + }) - }); - - it('send mehtod accepts a success callback', function(done) { + it('send mehtod accepts a success callback', function (done) { var fakeResponse = [ 200, { 'Content-type': 'application/json' }, '{}' - ]; + ] - fakeServer.respondWith('GET', url, fakeResponse); + fakeServer.respondWith('GET', url, fakeResponse) request.send({ method: 'GET', url: url, - success: function() { - done(); - }, - error: function(error) { - done(error); + success: function () { + done() }, - }); - }); + error: function (error) { + done(error) + } + }) + }) - it('success callback expect responseText, status , incoming message object', function(done) { + it('success callback expect responseText, status , incoming message object', function (done) { var responseData = { DATA: 'DATA' - }; + } var fakeResponse = [ 200, { 'Content-type': 'application/json' }, JSON.stringify(responseData) - ]; + ] - fakeServer.respondWith('GET', url, fakeResponse); + fakeServer.respondWith('GET', url, fakeResponse) request.send({ method: 'GET', url: url, - success: function(data, status, httpResponse) { - expect(data).to.be.a('object'); - expect(data).to.deep.equal(responseData); - expect(status).to.be.a('number'); - expect(httpResponse).to.be.an('object'); - done(); + success: function (data, status, httpResponse) { + expect(data).to.be.a('object') + expect(data).to.deep.equal(responseData) + expect(status).to.be.a('number') + expect(httpResponse).to.be.an('object') + done() } - }); - }); + }) + }) - it('send mehtod accepts an error callback', function(done) { + it('send mehtod accepts an error callback', function (done) { var fakeResponse = [ 404, { 'Content-type': 'application/json' }, '{}' - ]; + ] - fakeServer.respondWith('GET', url, fakeResponse); + fakeServer.respondWith('GET', url, fakeResponse) request.send({ method: 'GET', url: url, - error: function(data, status) { - expect(status).to.be.equal(404); - done(); + error: function (data, status) { + expect(status).to.be.equal(404) + done() } - }); - }); + }) + }) - it.skip('send too large GET rewrite to POST and active override method header', function(done) { + it.skip('send too large GET rewrite to POST and active override method header', function (done) { var responseData = { DATA: 'DATA' - }; + } var okResponse = [ 200, { 'Content-type': 'application/json' }, JSON.stringify(responseData) - ]; + ] - fakeServer.respondWith('POST', url, okResponse); + fakeServer.respondWith('POST', url, okResponse) - var largeUrl = url + '?' + new Array(5000).join('a'); + var largeUrl = url + '?' + new Array(5000).join('a') request.send({ method: 'GET', url: largeUrl, - success: function(data, status) { - expect(data).to.deep.equal(responseData); - expect(status).to.be.equal(200); - expect(fakeServer.requests[0]).to.have.deep.property('requestHeaders.X-HTTP-Method-Override', 'GET'); - expect(fakeServer.requests[0]).to.have.deep.property('requestHeaders.content-type', 'application/x-www-form-urlencoded;charset=utf-8'); - done(); + success: function (data, status) { + expect(data).to.deep.equal(responseData) + expect(status).to.be.equal(200) + expect(fakeServer.requests[0]).to.have.deep.property('requestHeaders.X-HTTP-Method-Override', 'GET') + expect(fakeServer.requests[0]).to.have.deep.property('requestHeaders.content-type', 'application/x-www-form-urlencoded;charset=utf-8') + done() } - }); - }); - - it('send method sends a String as application/octet-stream', function(done) { - var _browserAjaxStub = sandbox.stub(request, '_browserAjax', function(params, resolver) { - resolver.resolve(); - }); - var testText = 'Test'; - + }) + }) + + it('send method sends a String as application/octet-stream', function (done) { + var _browserAjaxStub = sandbox.stub(request, '_browserAjax', function (params, resolver) { + resolver.resolve() + }) + var testText = 'Test' + + request.send({ + method: 'POST', + url: url, + contentType: 'application/octet-stream', + data: testText + }) + .should.be.eventually.fulfilled + .then(function () { + expect(typeof (_browserAjaxStub.getCall(0).args[0].data)).to.be.equal('string') + }) + .should.notify(done) + }) + + it('send method sends a byteArray as application/octet-stream', function (done) { + var _browserAjaxStub = sandbox.stub(request, '_browserAjax', function (params, resolver) { + resolver.resolve() + }) + var testText = 'Test' + var byteText = [] + for (var i = 0; i < testText.length; i++) { + byteText.push(testText.charCodeAt(i)) + } + + request.send({ + method: 'POST', + url: url, + contentType: 'application/octet-stream', + data: byteText + }) + .should.be.eventually.fulfilled + .then(function () { + var dataSended = _browserAjaxStub.getCall(0).args[0].data + + byteText.forEach(function (element, index) { + expect(dataSended[index]).to.be.equal(element) + }) + expect(typeof (_browserAjaxStub.getCall(0).args[0].data)).to.be.equal('object') + }) + .should.notify(done) + }) + + it('send method sends an Uint8Array as application/octet-stream', function (done) { + var _browserAjaxStub = sandbox.stub(request, '_browserAjax', function (params, resolver) { + resolver.resolve() + }) + var testText = 'Test' + var ui8arr = new Uint8Array(testText.length) + for (var i = 0; i < testText.length; i++) { + ui8arr[i] = testText.charCodeAt(i) + } + + request.send({ + method: 'POST', + url: url, + contentType: 'application/octet-stream', + data: ui8arr + }) + .should.be.eventually.fulfilled + .then(function () { + var dataSended = _browserAjaxStub.getCall(0).args[0].data + for (var key in dataSended) { + if (dataSended.hasOwnProperty(key)) { + expect(dataSended[key]).to.be.equal(ui8arr[key]) + } + } + expect(typeof (_browserAjaxStub.getCall(0).args[0].data)).to.be.equal('object') + }) + .should.notify(done) + }) + + it('send method throws an error if try to send an ArrayBuffer as application/octet-stream', function () { + var testText = 'Test' + var buffer = new ArrayBuffer(testText.length) + + expect(function () { request.send({ method: 'POST', url: url, - contentType : 'application/octet-stream', - data: testText - }) - .should.be.eventually.fulfilled - .then(function() { - expect(typeof(_browserAjaxStub.getCall(0).args[0].data)).to.be.equal('string'); + contentType: 'application/octet-stream', + data: buffer }) - .should.notify(done); - }); - - it('send method sends a byteArray as application/octet-stream', function(done) { - var _browserAjaxStub = sandbox.stub(request, '_browserAjax', function(params, resolver) { - resolver.resolve(); - }); - var testText = 'Test'; - var byteText = []; - for(var i = 0; i < testText.length; i++){ - byteText.push(testText.charCodeAt(i)); - } - + }).to.throw('ArrayBuffer is not supported, please use Blob, File, Stream or ArrayBufferView') + }) + + it('send method throws an error if try to send an ArrayBuffer as application/blob', function () { + var testText = 'Test' + var buffer = new ArrayBuffer(testText.length) + + expect(function () { request.send({ method: 'POST', url: url, - contentType : 'application/octet-stream', - data: byteText + contentType: 'application/blob', + data: buffer }) - .should.be.eventually.fulfilled - .then(function() { - var dataSended = _browserAjaxStub.getCall(0).args[0].data; + }).to.throw('ArrayBuffer is not supported, please use Blob') + }) - byteText.forEach(function(element, index) { - expect(dataSended[index]).to.be.equal(element); - }); - expect(typeof(_browserAjaxStub.getCall(0).args[0].data)).to.be.equal('object'); + // Phantom creates problem in this test using new Blob() constructor + if (window.chrome) { + it('send method sends a blob, parse not necessary', function (done) { + var _browserAjaxStub = sandbox.stub(request, '_browserAjax', function (params, resolver) { + resolver.resolve() }) - .should.notify(done); - }); - - it('send method sends an Uint8Array as application/octet-stream', function(done) { - var _browserAjaxStub = sandbox.stub(request, '_browserAjax', function(params, resolver) { - resolver.resolve(); - }); - var testText = 'Test'; - var ui8arr = new Uint8Array(testText.length); - for(var i = 0; i < testText.length; i++){ - ui8arr[i] = testText.charCodeAt(i); + var testText = 'Test' + var byteText = [] + for (var i = 0; i < testText.length; i++) { + byteText.push(testText.charCodeAt(i)) } - + var blobText = new Blob(byteText) + request.send({ method: 'POST', url: url, - contentType : 'application/octet-stream', - data: ui8arr - }) - .should.be.eventually.fulfilled - .then(function() { - var dataSended = _browserAjaxStub.getCall(0).args[0].data; - for(var key in dataSended ) { - if (dataSended.hasOwnProperty(key)) { - expect(dataSended[key]).to.be.equal(ui8arr[key]); - } - } - expect(typeof(_browserAjaxStub.getCall(0).args[0].data)).to.be.equal('object'); + contentType: 'application/blob', + data: blobText }) - .should.notify(done); - }); - - it('send method throws an error if try to send an ArrayBuffer as application/octet-stream', function() { - var testText = 'Test'; - var buffer = new ArrayBuffer(testText.length); - - expect(function() { - request.send({ - method: 'POST', - url: url, - contentType : 'application/octet-stream', - data: buffer - }); - }).to.throw('ArrayBuffer is not supported, please use Blob, File, Stream or ArrayBufferView'); - }); - - it('send method throws an error if try to send an ArrayBuffer as application/blob', function() { - var testText = 'Test'; - var buffer = new ArrayBuffer(testText.length); - - expect(function() { - request.send({ - method: 'POST', - url: url, - contentType : 'application/blob', - data: buffer - }); - }).to.throw('ArrayBuffer is not supported, please use Blob'); - }); + .should.be.eventually.fulfilled + .then(function () { + var dataSended = _browserAjaxStub.getCall(0).args[0].data - // Phantom creates problem in this test using new Blob() constructor - if(window.chrome) { - it('send method sends a blob, parse not necessary', function(done) { - var _browserAjaxStub = sandbox.stub(request, '_browserAjax', function(params, resolver) { - resolver.resolve(); - }); - var testText = 'Test'; - var byteText = []; - for(var i = 0; i < testText.length; i++){ - byteText.push(testText.charCodeAt(i)); - } - var blobText = new Blob(byteText); - - request.send({ - method: 'POST', - url: url, - contentType : 'application/blob', - data: blobText - }) - .should.be.eventually.fulfilled - .then(function() { - var dataSended = _browserAjaxStub.getCall(0).args[0].data; - - Object.keys(dataSended).map(function(key) { - expect(dataSended[key]).to.be.equal(blobText[key]); - }); - expect(typeof(_browserAjaxStub.getCall(0).args[0].data)).to.be.equal('object'); + Object.keys(dataSended).map(function (key) { + expect(dataSended[key]).to.be.equal(blobText[key]) }) - .should.notify(done); - }); + expect(typeof (_browserAjaxStub.getCall(0).args[0].data)).to.be.equal('object') + }) + .should.notify(done) + }) } - }); -}); + }) +}) diff --git a/test/browser/unit/resource-binary.js b/test/browser/unit/resource-binary.js index f6341cb..ea55399 100644 --- a/test/browser/unit/resource-binary.js +++ b/test/browser/unit/resource-binary.js @@ -1,5 +1,6 @@ -/*jshint newcap: false */ -'use strict'; +/* jshint newcap: false */ +'use strict' +/* globals describe it before after beforeEach afterEach expect sinon Image Blob corbel */ var CONFIG = { clientId: 'clientId', @@ -9,85 +10,82 @@ var CONFIG = { domain: 'domain-example', urlBase: 'https://{{module}}-qa.bqws.io/v1.0/' -}; -var TEST_ENDPOINT = CONFIG.urlBase.replace('{{module}}', 'resources') + CONFIG.domain + '/'; +} +var TEST_ENDPOINT = CONFIG.urlBase.replace('{{module}}', 'resources') + CONFIG.domain + '/' -describe('corbel resources module', function() { - - var sandbox = sinon.sandbox.create(), - corbelDriver, - resources; +describe('corbel resources module', function () { + var sandbox = sinon.sandbox.create() + var corbelDriver + var resources // crete test blob - var canvas = document.createElement('canvas'); - canvas.id = 'myCanvas'; - canvas.width = '626'; - canvas.height = '626'; + var canvas = document.createElement('canvas') + canvas.id = 'myCanvas' + canvas.width = '626' + canvas.height = '626' - var testElement =document.createElement('div'); - testElement.setAttribute('id', 'test'); - document.body.appendChild(testElement); + var testElement = document.createElement('div') + testElement.setAttribute('id', 'test') + document.body.appendChild(testElement) - document.getElementById('test').appendChild(canvas); - var context = canvas.getContext('2d'); - var imageObj = new Image(); + document.getElementById('test').appendChild(canvas) + var context = canvas.getContext('2d') + var imageObj = new Image() - context.drawImage(imageObj, 0, 0); - var blob = corbel.utils.dataURItoBlob(canvas.toDataURL()); + context.drawImage(imageObj, 0, 0) + var blob = corbel.utils.dataURItoBlob(canvas.toDataURL()) // phantom hack - if(canvas.remove) { - canvas.remove(); + if (canvas.remove) { + canvas.remove() } - before(function() { - corbelDriver = corbel.getDriver(CONFIG); - resources = corbelDriver.resources; - }); - - after(function() {}); + before(function () { + corbelDriver = corbel.getDriver(CONFIG) + resources = corbelDriver.resources + }) - beforeEach(function() { - sandbox.stub(corbel.request, 'send').returns(Promise.resolve()); - }); + after(function () {}) - afterEach(function() { - sandbox.restore(); - }); + beforeEach(function () { + sandbox.stub(corbel.request, 'send').returns(Promise.resolve()) + }) + afterEach(function () { + sandbox.restore() + }) - it('update/create a binary resource', function() { + it('update/create a binary resource', function () { resources.resource('books:Book', '123').update(blob, { dataType: 'image/png' - }); - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(TEST_ENDPOINT + 'resource/books:Book/123'); - expect(callRequestParam.method).to.be.equal('PUT'); - expect(callRequestParam.headers.Accept).to.be.equal('image/png'); - expect(callRequestParam.data instanceof Blob).to.be.equal(true); - }); - - it('delete a binary resource', function() { + }) + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(TEST_ENDPOINT + 'resource/books:Book/123') + expect(callRequestParam.method).to.be.equal('PUT') + expect(callRequestParam.headers.Accept).to.be.equal('image/png') + expect(callRequestParam.data instanceof Blob).to.be.equal(true) + }) + + it('delete a binary resource', function () { resources.resource('books:Book', '123').delete({ dataType: 'image/png' - }); - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(TEST_ENDPOINT + 'resource/books:Book/123'); - expect(callRequestParam.method).to.be.equal('DELETE'); - expect(callRequestParam.headers.Accept).to.be.equal('image/png'); - }); - - it('get a binary resource with mediaType and noContent', function() { + }) + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(TEST_ENDPOINT + 'resource/books:Book/123') + expect(callRequestParam.method).to.be.equal('DELETE') + expect(callRequestParam.headers.Accept).to.be.equal('image/png') + }) + + it('get a binary resource with mediaType and noContent', function () { resources.resource('books:Book', '123').get({ dataType: 'image/png', responseType: 'blob', noRedirect: true - }); - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(TEST_ENDPOINT + 'resource/books:Book/123'); - expect(callRequestParam.method).to.be.equal('GET'); - expect(callRequestParam.headers.Accept).to.be.equal('image/png'); - expect(callRequestParam.responseType).to.be.equal('blob'); - expect(callRequestParam.headers['No-Redirect']).to.be.equal(true); - }); - -}); + }) + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(TEST_ENDPOINT + 'resource/books:Book/123') + expect(callRequestParam.method).to.be.equal('GET') + expect(callRequestParam.headers.Accept).to.be.equal('image/png') + expect(callRequestParam.responseType).to.be.equal('blob') + expect(callRequestParam.headers['No-Redirect']).to.be.equal(true) + }) +}) diff --git a/test/karma.conf.js b/test/karma.conf.js index 2742221..39c518f 100644 --- a/test/karma.conf.js +++ b/test/karma.conf.js @@ -3,94 +3,94 @@ // Generated on 2014-10-22 using // generator-karma 0.8.3 -module.exports = function(config) { - 'use strict'; - - config.set({ - // enable / disable watching file and executing tests whenever any file changes - autoWatch: true, - - // base path, that will be used to resolve files and exclude - basePath: '../', - - // testing framework to use (jasmine/mocha/qunit/...) - frameworks: ['mocha-debug', 'mocha', 'chai', 'chai-as-promised', 'sinon'], - - // list of files / patterns to load in the browser - files: [ - 'dist/corbel.with-polyfills.js', - '.tmp/test/browser/**/*.js', - 'bower_components/', - 'vendor/' - ], - - // list of files / patterns to exclude - exclude: ['express/server.js'], - - // web server port - port: 8080, - - // Start these browsers, currently available: - // - Chrome - // - ChromeCanary - // - Firefox - // - Opera - // - Safari (only Mac) - // - PhantomJS - // - IE (only Windows) - browsers: [ - 'PhantomJS' - ], - - // Which plugins to enable - plugins: [ - 'karma-phantomjs-launcher', - 'karma-chrome-launcher', - 'karma-mocha', - 'karma-mocha-debug', - 'karma-mocha-reporter', - 'karma-chai-plugins', - 'karma-sinon', - 'karma-tap-reporter' - ], - phantomjsLauncher: { - flags: [ - '--web-security=no', - '--ignore-ssl-errors=no' - ] - }, - - // Continuous Integration mode - // if true, it capture browsers, run tests and exit - singleRun: false, - - colors: true, - - browserNoActivityTimeout: 95000, - - client: { - mocha: { - reporter: 'html' // change Karma's debug.html to the mocha web reporter - } - }, - - // test results reporter to use - // possible values: 'dots', 'progress', 'junit', 'growl', 'coverage' - reporters: ['tap', 'mocha'], - - tapReporter: { - outputFile: '.report/report.tap' - }, - - // level of logging - // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG - logLevel: config.LOG_INFO, - - // Uncomment the following lines if you are using grunt's server to run the tests - // proxies: { - // '/': 'http://localhost:9000/' - // }, - // URL root prevent conflicts with the site root - // urlRoot: '_karma_' - }); -}; +module.exports = function (config) { + 'use strict' + + config.set({ + // enable / disable watching file and executing tests whenever any file changes + autoWatch: true, + + // base path, that will be used to resolve files and exclude + basePath: '../', + + // testing framework to use (jasmine/mocha/qunit/...) + frameworks: ['mocha-debug', 'mocha', 'chai', 'chai-as-promised', 'sinon'], + + // list of files / patterns to load in the browser + files: [ + 'dist/corbel.with-polyfills.js', + '.tmp/test/browser/**/*.js', + 'bower_components/', + 'vendor/' + ], + + // list of files / patterns to exclude + exclude: ['express/server.js'], + + // web server port + port: 8080, + + // Start these browsers, currently available: + // - Chrome + // - ChromeCanary + // - Firefox + // - Opera + // - Safari (only Mac) + // - PhantomJS + // - IE (only Windows) + browsers: [ + 'PhantomJS' + ], + + // Which plugins to enable + plugins: [ + 'karma-phantomjs-launcher', + 'karma-chrome-launcher', + 'karma-mocha', + 'karma-mocha-debug', + 'karma-mocha-reporter', + 'karma-chai-plugins', + 'karma-sinon', + 'karma-tap-reporter' + ], + phantomjsLauncher: { + flags: [ + '--web-security=no', + '--ignore-ssl-errors=no' + ] + }, + + // Continuous Integration mode + // if true, it capture browsers, run tests and exit + singleRun: false, + + colors: true, + + browserNoActivityTimeout: 95000, + + client: { + mocha: { + reporter: 'html' // change Karma's debug.html to the mocha web reporter + } + }, + + // test results reporter to use + // possible values: 'dots', 'progress', 'junit', 'growl', 'coverage' + reporters: ['tap', 'mocha'], + + tapReporter: { + outputFile: '.report/report.tap' + }, + + // level of logging + // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG + logLevel: config.LOG_INFO + + // Uncomment the following lines if you are using grunt's server to run the tests + // proxies: { + // '/': 'http://localhost:9000/' + // }, + // URL root prevent conflicts with the site root + // urlRoot: '_karma_' + }) +} diff --git a/test/node/test-suite.js b/test/node/test-suite.js index db4f923..ada8259 100644 --- a/test/node/test-suite.js +++ b/test/node/test-suite.js @@ -1,30 +1,30 @@ -'use strict'; +'use strict' -global.Promise = require('es6-promise').Promise; +global.Promise = require('es6-promise').Promise -var chai = require('chai'); -var chaiAsPromised = require('chai-as-promised'); -chai.use(chaiAsPromised); -chai.should(); +var chai = require('chai') +var chaiAsPromised = require('chai-as-promised') +chai.use(chaiAsPromised) +chai.should() -require('./unit/config.js'); -require('./unit/baseUrlIntegrity.js'); -require('./unit/corbel.js'); -require('./unit/domain.js'); -require('./unit/validate.js'); -require('./unit/request.js'); -require('./unit/jwt.js'); -require('./unit/iam.js'); -require('./unit/resources.js'); -require('./unit/resources-request-params.js'); -require('./unit/services.js'); -require('./unit/assets.js'); -require('./unit/oauth.js'); -require('./unit/notifications.js'); -require('./unit/ec.js'); -require('./unit/evci.js'); -require('./unit/scheduler.js'); -require('./unit/borrow.js'); -require('./unit/composr.js'); -require('./unit/webfs.js'); -require('./unit/utils.js'); +require('./unit/config.js') +require('./unit/baseUrlIntegrity.js') +require('./unit/corbel.js') +require('./unit/domain.js') +require('./unit/validate.js') +require('./unit/request.js') +require('./unit/jwt.js') +require('./unit/iam.js') +require('./unit/resources.js') +require('./unit/resources-request-params.js') +require('./unit/services.js') +require('./unit/assets.js') +require('./unit/oauth.js') +require('./unit/notifications.js') +require('./unit/ec.js') +require('./unit/evci.js') +require('./unit/scheduler.js') +require('./unit/borrow.js') +require('./unit/composr.js') +require('./unit/webfs.js') +require('./unit/utils.js') diff --git a/test/node/unit/assets.js b/test/node/unit/assets.js index d29e9cc..9e25594 100644 --- a/test/node/unit/assets.js +++ b/test/node/unit/assets.js @@ -1,159 +1,157 @@ -'use strict'; +'use strict' /* jshint camelcase:false */ - -var corbel = require('../../../dist/corbel.js'), - chai = require('chai'), - sinon = require('sinon'), - expect = chai.expect; - -describe('In Assets module we can', function() { - - var sandbox = sinon.sandbox.create(); - var CONFIG = { - - clientId: 'clientId', - clientSecret: 'clientSecret', - - scopes: ['silkroad-qa:client', 'resources:send_event_bus', 'resources:test:test_operations', 'resources:music:read_catalog', 'resources:music:streaming'], - - urlBase: 'https://{{module}}-corbel.io/' - - }; - - var ASSET_URL = CONFIG.urlBase.replace('{{module}}', 'assets') + 'asset'; - - var corbelDriver = corbel.getDriver(CONFIG); - - var corbelRequestStub; - - beforeEach(function() { - corbelRequestStub = sandbox.stub(corbel.request, 'send'); - }); - - afterEach(function() { - sandbox.restore(); - }); - - it('create one asset', function() { - corbelRequestStub.returns(Promise.resolve()); - var testData = '{\'test_object\':\'test\'}'; - corbelDriver.assets.asset().create(testData); - - var callRequestParam = corbelRequestStub.getCall(0).args[0]; - expect(callRequestParam.url).to.be.equal(ASSET_URL); - expect(callRequestParam.method).to.be.equal('POST'); - expect(callRequestParam.data).to.be.equal(testData); - }); - - it('get my user assets', function() { - corbelRequestStub.returns(Promise.resolve('OK')); - - corbelDriver.assets.asset().get(); - - var callRequestParam = corbelRequestStub.getCall(0).args[0]; - expect(callRequestParam.url).to.be.equal(ASSET_URL); - expect(callRequestParam.method).to.be.equal('GET'); - }); - - it('get my user assets all with params', function() { - corbelRequestStub.returns(Promise.resolve('OK')); - var params = { - query: [{ - '$eq': { - field: 'value' - } - }], - pagination: { - pageSize: 2, - page: 3 - }, - sort: { - field: 'asc' - } - }; - - corbelDriver.assets.asset().get(params); - - var callRequestParam = corbelRequestStub.getCall(0).args[0]; - expect(callRequestParam.url).to.be.equal(ASSET_URL + '?api:query=' + encodeURIComponent('[{"$eq":{"field":"value"}}]') + '&api:sort=' + encodeURIComponent('{"field":"asc"}') + '&api:page=3&api:pageSize=2'); - expect(callRequestParam.query).to.be.equal(); - expect(callRequestParam.method).to.be.equal('GET'); - }); - - it('get all assets', function() { - corbelRequestStub.returns(Promise.resolve('OK')); - - corbelDriver.assets.asset('all').get(); - - var callRequestParam = corbelRequestStub.getCall(0).args[0]; - expect(callRequestParam.url).to.be.equal(ASSET_URL + '/all'); - expect(callRequestParam.method).to.be.equal('GET'); - }); - - it('get all with params', function() { - corbelRequestStub.returns(Promise.resolve('OK')); - var params = { - query: [{ - '$eq': { - field: 'value' - } - }], - pagination: { - pageSize: 2, - page: 3 - }, - sort: { - field: 'asc' - } - }; - - corbelDriver.assets.asset('all').get(params); - - var callRequestParam = corbelRequestStub.getCall(0).args[0]; - expect(callRequestParam.url).to.be.equal(ASSET_URL + '/all?' + 'api:query=' + encodeURIComponent('[{"$eq":{"field":"value"}}]') + '&api:sort=' + encodeURIComponent('{"field":"asc"}') + '&api:page=3&api:pageSize=2'); - expect(callRequestParam.method).to.be.equal('GET'); - }); - - it('get aggregated count', function() { - corbelRequestStub.returns(Promise.resolve('OK')); - var params = { - aggregation : { '$count' : '*'} - }; - - corbelDriver.assets.asset('all').get(params); - - var callRequestParam = corbelRequestStub.getCall(0).args[0]; - expect(callRequestParam.url).to.be.equal(ASSET_URL + '/all?' + 'api:aggregation=' + encodeURIComponent('{\"$count\":\"*\"}')); - expect(callRequestParam.method).to.be.equal('GET'); - }); - - it('delete an undefinded asset', function() { - corbelRequestStub.returns(Promise.resolve('OK')); - - expect(function(){ - corbelDriver.assets.asset().delete(); - }).to.throw('id value is mandatory and cannot be undefined'); - }); - - it('delete one asset', function() { - corbelRequestStub.returns(Promise.resolve()); - var assetId = 1; - - corbelDriver.assets.asset(assetId).delete(); - - var callRequestParam = corbelRequestStub.getCall(0).args[0]; - expect(callRequestParam.url).to.be.equal(ASSET_URL + '/' + assetId); - expect(callRequestParam.method).to.be.equal('DELETE'); - }); - - it('get access', function() { - corbelRequestStub.returns(Promise.resolve()); - corbelDriver.assets.asset().access(); - - var callRequestParam = corbelRequestStub.getCall(0).args[0]; - expect(callRequestParam.url).to.be.equal(ASSET_URL + '/access'); - expect(callRequestParam.method).to.be.equal('GET'); - expect(callRequestParam.headers['No-Redirect']).to.be.equal(true); - }); - -}); +/* globals describe it beforeEach afterEach */ + +var corbel = require('../../../dist/corbel.js') +var chai = require('chai') +var sinon = require('sinon') +var expect = chai.expect + +describe('In Assets module we can', function () { + var sandbox = sinon.sandbox.create() + var CONFIG = { + clientId: 'clientId', + clientSecret: 'clientSecret', + + scopes: ['silkroad-qa:client', 'resources:send_event_bus', 'resources:test:test_operations', 'resources:music:read_catalog', 'resources:music:streaming'], + + urlBase: 'https://{{module}}-corbel.io/' + + } + + var ASSET_URL = CONFIG.urlBase.replace('{{module}}', 'assets') + 'asset' + + var corbelDriver = corbel.getDriver(CONFIG) + + var corbelRequestStub + + beforeEach(function () { + corbelRequestStub = sandbox.stub(corbel.request, 'send') + }) + + afterEach(function () { + sandbox.restore() + }) + + it('create one asset', function () { + corbelRequestStub.returns(Promise.resolve()) + var testData = "{'test_object':'test'}" + corbelDriver.assets.asset().create(testData) + + var callRequestParam = corbelRequestStub.getCall(0).args[0] + expect(callRequestParam.url).to.be.equal(ASSET_URL) + expect(callRequestParam.method).to.be.equal('POST') + expect(callRequestParam.data).to.be.equal(testData) + }) + + it('get my user assets', function () { + corbelRequestStub.returns(Promise.resolve('OK')) + + corbelDriver.assets.asset().get() + + var callRequestParam = corbelRequestStub.getCall(0).args[0] + expect(callRequestParam.url).to.be.equal(ASSET_URL) + expect(callRequestParam.method).to.be.equal('GET') + }) + + it('get my user assets all with params', function () { + corbelRequestStub.returns(Promise.resolve('OK')) + var params = { + query: [{ + '$eq': { + field: 'value' + } + }], + pagination: { + pageSize: 2, + page: 3 + }, + sort: { + field: 'asc' + } + } + + corbelDriver.assets.asset().get(params) + + var callRequestParam = corbelRequestStub.getCall(0).args[0] + expect(callRequestParam.url).to.be.equal(ASSET_URL + '?api:query=' + encodeURIComponent('[{"$eq":{"field":"value"}}]') + '&api:sort=' + encodeURIComponent('{"field":"asc"}') + '&api:page=3&api:pageSize=2') + expect(callRequestParam.query).to.be.equal() + expect(callRequestParam.method).to.be.equal('GET') + }) + + it('get all assets', function () { + corbelRequestStub.returns(Promise.resolve('OK')) + + corbelDriver.assets.asset('all').get() + + var callRequestParam = corbelRequestStub.getCall(0).args[0] + expect(callRequestParam.url).to.be.equal(ASSET_URL + '/all') + expect(callRequestParam.method).to.be.equal('GET') + }) + + it('get all with params', function () { + corbelRequestStub.returns(Promise.resolve('OK')) + var params = { + query: [{ + '$eq': { + field: 'value' + } + }], + pagination: { + pageSize: 2, + page: 3 + }, + sort: { + field: 'asc' + } + } + + corbelDriver.assets.asset('all').get(params) + + var callRequestParam = corbelRequestStub.getCall(0).args[0] + expect(callRequestParam.url).to.be.equal(ASSET_URL + '/all?' + 'api:query=' + encodeURIComponent('[{"$eq":{"field":"value"}}]') + '&api:sort=' + encodeURIComponent('{"field":"asc"}') + '&api:page=3&api:pageSize=2') + expect(callRequestParam.method).to.be.equal('GET') + }) + + it('get aggregated count', function () { + corbelRequestStub.returns(Promise.resolve('OK')) + var params = { + aggregation: {'$count': '*'} + } + + corbelDriver.assets.asset('all').get(params) + + var callRequestParam = corbelRequestStub.getCall(0).args[0] + expect(callRequestParam.url).to.be.equal(ASSET_URL + '/all?' + 'api:aggregation=' + encodeURIComponent('{"$count":"*"}')) + expect(callRequestParam.method).to.be.equal('GET') + }) + + it('delete an undefinded asset', function () { + corbelRequestStub.returns(Promise.resolve('OK')) + + expect(function () { + corbelDriver.assets.asset().delete() + }).to.throw('id value is mandatory and cannot be undefined') + }) + + it('delete one asset', function () { + corbelRequestStub.returns(Promise.resolve()) + var assetId = 1 + + corbelDriver.assets.asset(assetId).delete() + + var callRequestParam = corbelRequestStub.getCall(0).args[0] + expect(callRequestParam.url).to.be.equal(ASSET_URL + '/' + assetId) + expect(callRequestParam.method).to.be.equal('DELETE') + }) + + it('get access', function () { + corbelRequestStub.returns(Promise.resolve()) + corbelDriver.assets.asset().access() + + var callRequestParam = corbelRequestStub.getCall(0).args[0] + expect(callRequestParam.url).to.be.equal(ASSET_URL + '/access') + expect(callRequestParam.method).to.be.equal('GET') + expect(callRequestParam.headers['No-Redirect']).to.be.equal(true) + }) +}) diff --git a/test/node/unit/baseUrlIntegrity.js b/test/node/unit/baseUrlIntegrity.js index 93af031..9df1a8f 100644 --- a/test/node/unit/baseUrlIntegrity.js +++ b/test/node/unit/baseUrlIntegrity.js @@ -1,14 +1,14 @@ -/*jshint newcap: false */ -'use strict'; +/* jshint newcap: false */ +'use strict' +/* globals describe it before after beforeEach afterEach */ -var corbel = require('../../../dist/corbel.js'), - chai = require('chai'), - sinon = require('sinon'), - expect = chai.expect; +var corbel = require('../../../dist/corbel.js') +var chai = require('chai') +var sinon = require('sinon') +var expect = chai.expect -var TEST_ENDPOINT = 'https://resources-mycorbel.com/v1.0/domain-example/', - - URL_EXAMPLE_RESOURCES = TEST_ENDPOINT + 'resource/resource:entity?api:search=' + encodeURIComponent('{"text":"test"}'); +var TEST_ENDPOINT = 'https://resources-mycorbel.com/v1.0/domain-example/' +var URL_EXAMPLE_RESOURCES = TEST_ENDPOINT + 'resource/resource:entity?api:search=' + encodeURIComponent('{"text":"test"}') var CONFIG = { clientId: 'clientId', @@ -16,54 +16,52 @@ var CONFIG = { scopes: 'scopes', domain: 'domain-example', urlBase: 'https://{{module}}-mycorbel.com/v1.0/' -}; - -describe('corbel resources module', function() { +} - var sandbox = sinon.sandbox.create(), - corbelDriver, - resources; +describe('corbel resources module', function () { + var sandbox = sinon.sandbox.create() + var corbelDriver + var resources - before(function() { - corbelDriver = corbel.getDriver(CONFIG); - resources = corbelDriver.resources; - }); + before(function () { + corbelDriver = corbel.getDriver(CONFIG) + resources = corbelDriver.resources + }) - after(function() {}); + after(function () {}) - beforeEach(function() { - sandbox.stub(corbel.request, 'send').returns(Promise.resolve()); - }); + beforeEach(function () { + sandbox.stub(corbel.request, 'send').returns(Promise.resolve()) + }) - afterEach(function() { - sandbox.restore(); - }); + afterEach(function () { + sandbox.restore() + }) - describe('url integrity', function() { - this.timeout(10000); + describe('url integrity', function () { + this.timeout(10000) - it('does not stack multiple api:definitions', function(done) { + it('does not stack multiple api:definitions', function (done) { var params = { - search : { + search: { text: 'test' } - }; + } + + expect(resources.collection('resource:entity').getURL(params)).to.be.equal(URL_EXAMPLE_RESOURCES) - expect(resources.collection('resource:entity').getURL(params)).to.be.equal(URL_EXAMPLE_RESOURCES); - - //After N calls the params object does not get modified by reference. - var promises = [resources.collection('resource:entity').get(params), resources.collection('resource:entity').get(params)]; + // After N calls the params object does not get modified by reference. + var promises = [resources.collection('resource:entity').get(params), resources.collection('resource:entity').get(params)] Promise.all(promises) - .then(function(){ - expect(resources.collection('resource:entity').getURL(params)).to.be.equal(URL_EXAMPLE_RESOURCES); - done(); + .then(function () { + expect(resources.collection('resource:entity').getURL(params)).to.be.equal(URL_EXAMPLE_RESOURCES) + done() }) - .catch(function(err){ - console.log(err); - done(err); - }); - }); - - }); -}); \ No newline at end of file + .catch(function (err) { + console.log(err) + done(err) + }) + }) + }) +}) diff --git a/test/node/unit/borrow.js b/test/node/unit/borrow.js index 7a1c9be..16ef048 100644 --- a/test/node/unit/borrow.js +++ b/test/node/unit/borrow.js @@ -1,554 +1,548 @@ -'use strict'; +'use strict' /* jshint camelcase:false */ +/* globals describe it beforeEach afterEach */ -var corbel = require('../../../dist/corbel.js'), - chai = require('chai'), - sinon = require('sinon'), - expect = chai.expect; +var corbel = require('../../../dist/corbel.js') +var chai = require('chai') +var sinon = require('sinon') +var expect = chai.expect -describe('corbel BORROW module', function() { +describe('corbel BORROW module', function () { + var sandbox = sinon.sandbox.create() + var CONFIG = { + clientId: 'clientId', + clientSecret: 'clientSecret', - var sandbox = sinon.sandbox.create(); - var CONFIG = { + scopes: ['silkroad-qa:client', 'resources:send_event_bus', 'resources:test:test_operations', 'resources:music:read_catalog', 'resources:music:streaming'], - clientId: 'clientId', - clientSecret: 'clientSecret', + urlBase: 'https://{{module}}-corbel.io/' - scopes: ['silkroad-qa:client', 'resources:send_event_bus', 'resources:test:test_operations', 'resources:music:read_catalog', 'resources:music:streaming'], + } - urlBase: 'https://{{module}}-corbel.io/' + var BORROW_END_POINT = CONFIG.urlBase.replace('{{module}}', 'borrow') + 'resource' - }; + var USER_BORROW_END_POINT = CONFIG.urlBase.replace('{{module}}', 'borrow') + 'user' - var BORROW_END_POINT = CONFIG.urlBase.replace('{{module}}', 'borrow') + 'resource'; + var LENDER_BORROW_END_POINT = CONFIG.urlBase.replace('{{module}}', 'borrow') + 'lender' - var USER_BORROW_END_POINT = CONFIG.urlBase.replace('{{module}}', 'borrow') + 'user'; + var corbelDriver = corbel.getDriver(CONFIG) - var LENDER_BORROW_END_POINT = CONFIG.urlBase.replace('{{module}}', 'borrow') + 'lender'; + var corbelRequestStub + var borrow - var corbelDriver = corbel.getDriver(CONFIG); + beforeEach(function () { + corbelDriver = corbel.getDriver(CONFIG) + borrow = corbelDriver.borrow + corbelRequestStub = sandbox.stub(corbel.request, 'send').returns(Promise.resolve()) + }) - var corbelRequestStub; - var borrow; + afterEach(function () { + sandbox.restore() + }) - beforeEach(function() { - corbelDriver = corbel.getDriver(CONFIG); - borrow = corbelDriver.borrow; - corbelRequestStub = sandbox.stub(corbel.request, 'send').returns(Promise.resolve()); - }); + describe('we can with a loanable resources', function () { + it('add loanable resource', function () { + corbelRequestStub.returns(Promise.resolve()) + var loanableResource = {} - afterEach(function() { - sandbox.restore(); - }); + corbelDriver.borrow.resource().add(loanableResource) - describe('we can with a loanable resources', function() { + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(BORROW_END_POINT) + expect(callRequestParam.method).to.be.equal('POST') + }) - it('add loanable resource', function() { - corbelRequestStub.returns(Promise.resolve()); - var loanableResource = {}; + it('get (undefined) loanable resource', function () { + corbelRequestStub.returns(Promise.resolve('OK')) + expect(function () { + corbelDriver.borrow.resource().get() + }).to.throw('id value is mandatory and cannot be undefined') + }) - corbelDriver.borrow.resource().add(loanableResource); + it('get loanable resource', function () { + corbelRequestStub.returns(Promise.resolve('OK')) - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(BORROW_END_POINT); - expect(callRequestParam.method).to.be.equal('POST'); - }); + corbelDriver.borrow.resource('idResource').get() - it('get (undefined) loanable resource', function() { - corbelRequestStub.returns(Promise.resolve('OK')); - expect(function(){ - corbelDriver.borrow.resource().get(); - }).to.throw('id value is mandatory and cannot be undefined'); - }); + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(BORROW_END_POINT + '/idResource') + expect(callRequestParam.method).to.be.equal('GET') + }) - it('get loanable resource', function() { - corbelRequestStub.returns(Promise.resolve('OK')); + it('delete (undefined) loanable resource', function () { + corbelRequestStub.returns(Promise.resolve('OK')) + expect(function () { + corbelDriver.borrow.resource().delete() + }).to.throw('id value is mandatory and cannot be undefined') + }) - corbelDriver.borrow.resource('idResource').get(); + it('delete loanable resource', function () { + corbelRequestStub.returns(Promise.resolve('OK')) - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(BORROW_END_POINT + '/idResource'); - expect(callRequestParam.method).to.be.equal('GET'); - }); + corbelDriver.borrow.resource('idResource').delete() - it('delete (undefined) loanable resource', function() { - corbelRequestStub.returns(Promise.resolve('OK')); - expect(function(){ - corbelDriver.borrow.resource().delete(); - }).to.throw('id value is mandatory and cannot be undefined'); - }); + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(BORROW_END_POINT + '/idResource') + expect(callRequestParam.method).to.be.equal('DELETE') + }) - it('delete loanable resource', function() { - corbelRequestStub.returns(Promise.resolve('OK')); + it('add license to (undefined) loanable resource', function () { + corbelRequestStub.returns(Promise.resolve('OK')) + var license = {} - corbelDriver.borrow.resource('idResource').delete(); + expect(function () { + corbelDriver.borrow.resource().addLicense(license) + }).to.throw('id value is mandatory and cannot be undefined') + }) - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(BORROW_END_POINT + '/idResource'); - expect(callRequestParam.method).to.be.equal('DELETE'); - }); + it('add license to loanable resource', function () { + corbelRequestStub.returns(Promise.resolve()) + var license = {} - it('add license to (undefined) loanable resource', function() { - corbelRequestStub.returns(Promise.resolve('OK')); - var license = {}; + corbelDriver.borrow.resource('idResource').addLicense(license) - expect(function(){ - corbelDriver.borrow.resource().addLicense(license); - }).to.throw('id value is mandatory and cannot be undefined'); - }); + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(BORROW_END_POINT + '/idResource/license') + expect(callRequestParam.method).to.be.equal('POST') + }) - it('add license to loanable resource', function() { - corbelRequestStub.returns(Promise.resolve()); - var license = {}; + it('apply for any user using an undefined resourceId', function () { + corbelRequestStub.returns(Promise.resolve('OK')) - corbelDriver.borrow.resource('idResource').addLicense(license); + expect(function () { + corbelDriver.borrow.resource().applyFor('userId') + }).to.throw('id value is mandatory and cannot be undefined') + }) - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(BORROW_END_POINT + '/idResource/license'); - expect(callRequestParam.method).to.be.equal('POST'); - }); + it('apply for any user using an undefined userId', function () { + corbelRequestStub.returns(Promise.resolve('OK')) - it('apply for any user using an undefined resourceId', function() { - corbelRequestStub.returns(Promise.resolve('OK')); + expect(function () { + corbelDriver.borrow.resource('resourceId').applyFor() + }).to.throw('userId value is mandatory and cannot be undefined') + }) - expect(function(){ - corbelDriver.borrow.resource().applyFor('userId'); - }).to.throw('id value is mandatory and cannot be undefined'); - }); + it('apply for any user', function () { + corbelRequestStub.returns(Promise.resolve('OK')) - it('apply for any user using an undefined userId', function() { - corbelRequestStub.returns(Promise.resolve('OK')); + corbelDriver.borrow.resource('idResource').applyFor('userId') - expect(function(){ - corbelDriver.borrow.resource('resourceId').applyFor(); - }).to.throw('userId value is mandatory and cannot be undefined'); - }); + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(BORROW_END_POINT + '/idResource/loan/userId') + expect(callRequestParam.method).to.be.equal('PUT') + }) - it('apply for any user', function() { - corbelRequestStub.returns(Promise.resolve('OK')); + it('apply for logged user using an undefined resourceId', function () { + corbelRequestStub.returns(Promise.resolve('OK')) - corbelDriver.borrow.resource('idResource').applyFor('userId'); + expect(function () { + corbelDriver.borrow.resource().applyForMe() + }).to.throw('id value is mandatory and cannot be undefined') + }) - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(BORROW_END_POINT + '/idResource/loan/userId'); - expect(callRequestParam.method).to.be.equal('PUT'); - }); + it('apply for logged user', function () { + corbelRequestStub.returns(Promise.resolve('OK')) - it('apply for logged user using an undefined resourceId', function() { - corbelRequestStub.returns(Promise.resolve('OK')); + corbelDriver.borrow.resource('idResource').applyForMe() - expect(function(){ - corbelDriver.borrow.resource().applyForMe(); - }).to.throw('id value is mandatory and cannot be undefined'); - }); + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(BORROW_END_POINT + '/idResource/loan/me') + expect(callRequestParam.method).to.be.equal('PUT') + }) - it('apply for logged user', function() { - corbelRequestStub.returns(Promise.resolve('OK')); + it('get lent of any user using an undefined resourceId', function () { + corbelRequestStub.returns(Promise.resolve('OK')) - corbelDriver.borrow.resource('idResource').applyForMe(); + expect(function () { + corbelDriver.borrow.resource().getLentOf('userId') + }).to.throw('id value is mandatory and cannot be undefined') + }) - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(BORROW_END_POINT + '/idResource/loan/me'); - expect(callRequestParam.method).to.be.equal('PUT'); - }); + it('get lent of any user using an undefined userId', function () { + corbelRequestStub.returns(Promise.resolve('OK')) - it('get lent of any user using an undefined resourceId', function() { - corbelRequestStub.returns(Promise.resolve('OK')); + expect(function () { + corbelDriver.borrow.resource('resourceId').getLentOf() + }).to.throw('userId value is mandatory and cannot be undefined') + }) - expect(function(){ - corbelDriver.borrow.resource().getLentOf('userId'); - }).to.throw('id value is mandatory and cannot be undefined'); - }); + it('get lent of any user', function () { + corbelRequestStub.returns(Promise.resolve('OK')) - it('get lent of any user using an undefined userId', function() { - corbelRequestStub.returns(Promise.resolve('OK')); + corbelDriver.borrow.resource('idResource').getLentOf('userId') - expect(function(){ - corbelDriver.borrow.resource('resourceId').getLentOf(); - }).to.throw('userId value is mandatory and cannot be undefined'); - }); + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(BORROW_END_POINT + '/idResource/loan/userId') + expect(callRequestParam.method).to.be.equal('GET') + }) - it('get lent of any user', function() { - corbelRequestStub.returns(Promise.resolve('OK')); + it('get lent of logged user using an undefined resourceId', function () { + corbelRequestStub.returns(Promise.resolve('OK')) - corbelDriver.borrow.resource('idResource').getLentOf('userId'); + expect(function () { + corbelDriver.borrow.resource().getMyLent() + }).to.throw('id value is mandatory and cannot be undefined') + }) - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(BORROW_END_POINT + '/idResource/loan/userId'); - expect(callRequestParam.method).to.be.equal('GET'); - }); + it('get lent of logged user', function () { + corbelRequestStub.returns(Promise.resolve('OK')) - it('get lent of logged user using an undefined resourceId', function() { - corbelRequestStub.returns(Promise.resolve('OK')); + corbelDriver.borrow.resource('idResource').getMyLent() - expect(function(){ - corbelDriver.borrow.resource().getMyLent(); - }).to.throw('id value is mandatory and cannot be undefined'); - }); + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(BORROW_END_POINT + '/idResource/loan/me') + expect(callRequestParam.method).to.be.equal('GET') + }) - it('get lent of logged user', function() { - corbelRequestStub.returns(Promise.resolve('OK')); + it('return loan of any user using an undefined resourceId', function () { + corbelRequestStub.returns(Promise.resolve('OK')) - corbelDriver.borrow.resource('idResource').getMyLent(); + expect(function () { + corbelDriver.borrow.resource().returnLoanOf('userId') + }).to.throw('id value is mandatory and cannot be undefined') + }) - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(BORROW_END_POINT + '/idResource/loan/me'); - expect(callRequestParam.method).to.be.equal('GET'); - }); + it('return loan of any user using an undefined userId', function () { + corbelRequestStub.returns(Promise.resolve('OK')) - it('return loan of any user using an undefined resourceId', function() { - corbelRequestStub.returns(Promise.resolve('OK')); + expect(function () { + corbelDriver.borrow.resource('resourceId').returnLoanOf() + }).to.throw('userId value is mandatory and cannot be undefined') + }) - expect(function(){ - corbelDriver.borrow.resource().returnLoanOf('userId'); - }).to.throw('id value is mandatory and cannot be undefined'); - }); + it('return loan of any user', function () { + corbelRequestStub.returns(Promise.resolve('OK')) - it('return loan of any user using an undefined userId', function() { - corbelRequestStub.returns(Promise.resolve('OK')); + corbelDriver.borrow.resource('idResource').returnLoanOf('userId') - expect(function(){ - corbelDriver.borrow.resource('resourceId').returnLoanOf(); - }).to.throw('userId value is mandatory and cannot be undefined'); - }); + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(BORROW_END_POINT + '/idResource/loan/userId') + expect(callRequestParam.method).to.be.equal('DELETE') + }) - it('return loan of any user', function() { - corbelRequestStub.returns(Promise.resolve('OK')); + it('return loan of logged user using an undefined resourceId', function () { + corbelRequestStub.returns(Promise.resolve('OK')) - corbelDriver.borrow.resource('idResource').returnLoanOf('userId'); + expect(function () { + corbelDriver.borrow.resource().returnMyLoan() + }).to.throw('id value is mandatory and cannot be undefined') + }) - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(BORROW_END_POINT + '/idResource/loan/userId'); - expect(callRequestParam.method).to.be.equal('DELETE'); - }); + it('return loan of logged user', function () { + corbelRequestStub.returns(Promise.resolve('OK')) - it('return loan of logged user using an undefined resourceId', function() { - corbelRequestStub.returns(Promise.resolve('OK')); + corbelDriver.borrow.resource('idResource').returnMyLoan() - expect(function(){ - corbelDriver.borrow.resource().returnMyLoan(); - }).to.throw('id value is mandatory and cannot be undefined'); - }); + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(BORROW_END_POINT + '/idResource/loan/me') + expect(callRequestParam.method).to.be.equal('DELETE') + }) - it('return loan of logged user', function() { - corbelRequestStub.returns(Promise.resolve('OK')); + it('renew loan for any user using an undefined resourceId', function () { + corbelRequestStub.returns(Promise.resolve('OK')) - corbelDriver.borrow.resource('idResource').returnMyLoan(); + expect(function () { + corbelDriver.borrow.resource().renewFor('userId') + }).to.throw('id value is mandatory and cannot be undefined') + }) - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(BORROW_END_POINT + '/idResource/loan/me'); - expect(callRequestParam.method).to.be.equal('DELETE'); - }); + it('renew loan for any user using an undefined userId', function () { + corbelRequestStub.returns(Promise.resolve('OK')) - it('renew loan for any user using an undefined resourceId', function() { - corbelRequestStub.returns(Promise.resolve('OK')); + expect(function () { + corbelDriver.borrow.resource('idResource').renewFor() + }).to.throw('userId value is mandatory and cannot be undefined') + }) - expect(function(){ - corbelDriver.borrow.resource().renewFor('userId'); - }).to.throw('id value is mandatory and cannot be undefined'); - }); + it('renew loan for any user', function () { + corbelRequestStub.returns(Promise.resolve('OK')) - it('renew loan for any user using an undefined userId', function() { - corbelRequestStub.returns(Promise.resolve('OK')); + corbelDriver.borrow.resource('idResource').renewFor('userId') - expect(function(){ - corbelDriver.borrow.resource('idResource').renewFor(); - }).to.throw('userId value is mandatory and cannot be undefined'); - }); + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(BORROW_END_POINT + '/idResource/renewal/userId') + expect(callRequestParam.method).to.be.equal('PUT') + }) - it('renew loan for any user', function() { - corbelRequestStub.returns(Promise.resolve('OK')); + it('renew loan for logged user using an undefined resourceId', function () { + corbelRequestStub.returns(Promise.resolve('OK')) - corbelDriver.borrow.resource('idResource').renewFor('userId'); + expect(function () { + corbelDriver.borrow.resource().renewForMe() + }).to.throw('id value is mandatory and cannot be undefined') + }) - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(BORROW_END_POINT + '/idResource/renewal/userId'); - expect(callRequestParam.method).to.be.equal('PUT'); - }); + it('renew loan for logged user', function () { + corbelRequestStub.returns(Promise.resolve('OK')) - it('renew loan for logged user using an undefined resourceId', function() { - corbelRequestStub.returns(Promise.resolve('OK')); + corbelDriver.borrow.resource('idResource').renewForMe() - expect(function(){ - corbelDriver.borrow.resource().renewForMe(); - }).to.throw('id value is mandatory and cannot be undefined'); - }); + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(BORROW_END_POINT + '/idResource/renewal/me') + expect(callRequestParam.method).to.be.equal('PUT') + }) - it('renew loan for logged user', function() { - corbelRequestStub.returns(Promise.resolve('OK')); + it('reserve for any user using an undefined resourceId', function () { + corbelRequestStub.returns(Promise.resolve('OK')) - corbelDriver.borrow.resource('idResource').renewForMe(); + expect(function () { + corbelDriver.borrow.resource().reserveFor('userId') + }).to.throw('id value is mandatory and cannot be undefined') + }) - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(BORROW_END_POINT + '/idResource/renewal/me'); - expect(callRequestParam.method).to.be.equal('PUT'); - }); + it('reserve for any user using an undefined userId', function () { + corbelRequestStub.returns(Promise.resolve('OK')) - it('reserve for any user using an undefined resourceId', function() { - corbelRequestStub.returns(Promise.resolve('OK')); + expect(function () { + corbelDriver.borrow.resource('idResource').reserveFor() + }).to.throw('userId value is mandatory and cannot be undefined') + }) - expect(function(){ - corbelDriver.borrow.resource().reserveFor('userId'); - }).to.throw('id value is mandatory and cannot be undefined'); - }); + it('reserve for any user', function () { + corbelRequestStub.returns(Promise.resolve('OK')) - it('reserve for any user using an undefined userId', function() { - corbelRequestStub.returns(Promise.resolve('OK')); + corbelDriver.borrow.resource('idResource').reserveFor('userId') - expect(function(){ - corbelDriver.borrow.resource('idResource').reserveFor(); - }).to.throw('userId value is mandatory and cannot be undefined'); - }); + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(BORROW_END_POINT + '/idResource/reservation/userId') + expect(callRequestParam.method).to.be.equal('PUT') + }) - it('reserve for any user', function() { - corbelRequestStub.returns(Promise.resolve('OK')); + it('reserve for me user using an undefined resourceId', function () { + corbelRequestStub.returns(Promise.resolve('OK')) - corbelDriver.borrow.resource('idResource').reserveFor('userId'); + expect(function () { + corbelDriver.borrow.resource().reserveForMe() + }).to.throw('id value is mandatory and cannot be undefined') + }) - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(BORROW_END_POINT + '/idResource/reservation/userId'); - expect(callRequestParam.method).to.be.equal('PUT'); - }); + it('reserve for me user', function () { + corbelRequestStub.returns(Promise.resolve('OK')) - it('reserve for me user using an undefined resourceId', function() { - corbelRequestStub.returns(Promise.resolve('OK')); + corbelDriver.borrow.resource('idResource').reserveForMe() - expect(function(){ - corbelDriver.borrow.resource().reserveForMe(); - }).to.throw('id value is mandatory and cannot be undefined'); - }); + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(BORROW_END_POINT + '/idResource/reservation/me') + expect(callRequestParam.method).to.be.equal('PUT') + }) - it('reserve for me user', function() { - corbelRequestStub.returns(Promise.resolve('OK')); + it('cancel reservation for any user using an undefined resourceId', function () { + corbelRequestStub.returns(Promise.resolve('OK')) - corbelDriver.borrow.resource('idResource').reserveForMe(); + expect(function () { + corbelDriver.borrow.resource().cancelReservationFor('userId') + }).to.throw('id value is mandatory and cannot be undefined') + }) - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(BORROW_END_POINT + '/idResource/reservation/me'); - expect(callRequestParam.method).to.be.equal('PUT'); - }); + it('cancel reservation for any user using an undefined userId', function () { + corbelRequestStub.returns(Promise.resolve('OK')) - it('cancel reservation for any user using an undefined resourceId', function() { - corbelRequestStub.returns(Promise.resolve('OK')); + expect(function () { + corbelDriver.borrow.resource('idResource').cancelReservationFor() + }).to.throw('userId value is mandatory and cannot be undefined') + }) - expect(function(){ - corbelDriver.borrow.resource().cancelReservationFor('userId'); - }).to.throw('id value is mandatory and cannot be undefined'); - }); + it('cancel reservation for any user', function () { + corbelRequestStub.returns(Promise.resolve('OK')) - it('cancel reservation for any user using an undefined userId', function() { - corbelRequestStub.returns(Promise.resolve('OK')); + corbelDriver.borrow.resource('idResource').cancelReservationFor('userId') - expect(function(){ - corbelDriver.borrow.resource('idResource').cancelReservationFor(); - }).to.throw('userId value is mandatory and cannot be undefined'); - }); + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(BORROW_END_POINT + '/idResource/reservation/userId') + expect(callRequestParam.method).to.be.equal('DELETE') + }) - it('cancel reservation for any user', function() { - corbelRequestStub.returns(Promise.resolve('OK')); + it('cancel reservation for logged user using an undefined resourceId', function () { + corbelRequestStub.returns(Promise.resolve('OK')) - corbelDriver.borrow.resource('idResource').cancelReservationFor('userId'); + expect(function () { + corbelDriver.borrow.resource().cancelMyReservation() + }).to.throw('id value is mandatory and cannot be undefined') + }) - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(BORROW_END_POINT + '/idResource/reservation/userId'); - expect(callRequestParam.method).to.be.equal('DELETE'); - }); + it('cancel reservation for logged user', function () { + corbelRequestStub.returns(Promise.resolve('OK')) - it('cancel reservation for logged user using an undefined resourceId', function() { - corbelRequestStub.returns(Promise.resolve('OK')); + corbelDriver.borrow.resource('idResource').cancelMyReservation() - expect(function(){ - corbelDriver.borrow.resource().cancelMyReservation(); - }).to.throw('id value is mandatory and cannot be undefined'); - }); + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(BORROW_END_POINT + '/idResource/reservation/me') + expect(callRequestParam.method).to.be.equal('DELETE') + }) - it('cancel reservation for logged user', function() { - corbelRequestStub.returns(Promise.resolve('OK')); + it('get history for any user using an undefined userId', function () { + corbelRequestStub.returns(Promise.resolve('OK')) - corbelDriver.borrow.resource('idResource').cancelMyReservation(); + expect(function () { + corbelDriver.borrow.resource('idResource').getHistoryOf() + }).to.throw('userId value is mandatory and cannot be undefined') + }) - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(BORROW_END_POINT + '/idResource/reservation/me'); - expect(callRequestParam.method).to.be.equal('DELETE'); - }); + it('get history for any user', function () { + corbelRequestStub.returns(Promise.resolve('OK')) - it('get history for any user using an undefined userId', function() { - corbelRequestStub.returns(Promise.resolve('OK')); + corbelDriver.borrow.resource().getHistoryOf('userId') - expect(function(){ - corbelDriver.borrow.resource('idResource').getHistoryOf(); - }).to.throw('userId value is mandatory and cannot be undefined'); - }); + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(BORROW_END_POINT + '/history/userId') + expect(callRequestParam.method).to.be.equal('GET') + }) - it('get history for any user', function() { - corbelRequestStub.returns(Promise.resolve('OK')); + it('get history for logged user', function () { + corbelRequestStub.returns(Promise.resolve('OK')) - corbelDriver.borrow.resource().getHistoryOf('userId'); + corbelDriver.borrow.resource().getMyHistory() - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(BORROW_END_POINT + '/history/userId'); - expect(callRequestParam.method).to.be.equal('GET'); - }); + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(BORROW_END_POINT + '/history/me') + expect(callRequestParam.method).to.be.equal('GET') + }) - it('get history for logged user', function() { - corbelRequestStub.returns(Promise.resolve('OK')); + it('get full history', function () { + corbelRequestStub.returns(Promise.resolve('OK')) - corbelDriver.borrow.resource().getMyHistory(); + corbelDriver.borrow.resource().getFullHistory() - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(BORROW_END_POINT + '/history/me'); - expect(callRequestParam.method).to.be.equal('GET'); - }); + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(BORROW_END_POINT + '/history/') + expect(callRequestParam.method).to.be.equal('GET') + }) + }) - it('get full history', function() { - corbelRequestStub.returns(Promise.resolve('OK')); + describe('we can like a user', function () { + it('get all reservations of any user', function () { + corbelRequestStub.returns(Promise.resolve('OK')) - corbelDriver.borrow.resource().getFullHistory(); + corbelDriver.borrow.user('userId').getAllReservations() - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(BORROW_END_POINT + '/history/'); - expect(callRequestParam.method).to.be.equal('GET'); - }); - }); + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(USER_BORROW_END_POINT + '/userId/reservation') + expect(callRequestParam.method).to.be.equal('GET') + }) - describe('we can like a user', function() { + it('get all reservations of logged user', function () { + corbelRequestStub.returns(Promise.resolve('OK')) - it('get all reservations of any user', function() { - corbelRequestStub.returns(Promise.resolve('OK')); + corbelDriver.borrow.user().getAllReservations() - corbelDriver.borrow.user('userId').getAllReservations(); + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(USER_BORROW_END_POINT + '/me/reservation') + expect(callRequestParam.method).to.be.equal('GET') + }) - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(USER_BORROW_END_POINT + '/userId/reservation'); - expect(callRequestParam.method).to.be.equal('GET'); - }); + it('get all loans of any user', function () { + corbelRequestStub.returns(Promise.resolve('OK')) - it('get all reservations of logged user', function() { - corbelRequestStub.returns(Promise.resolve('OK')); + corbelDriver.borrow.user('userId').getAllLoans() - corbelDriver.borrow.user().getAllReservations(); + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(USER_BORROW_END_POINT + '/userId/loan') + expect(callRequestParam.method).to.be.equal('GET') + }) - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(USER_BORROW_END_POINT + '/me/reservation'); - expect(callRequestParam.method).to.be.equal('GET'); - }); + it('get all loans of logged user', function () { + corbelRequestStub.returns(Promise.resolve('OK')) - it('get all loans of any user', function() { - corbelRequestStub.returns(Promise.resolve('OK')); + corbelDriver.borrow.user().getAllLoans() - corbelDriver.borrow.user('userId').getAllLoans(); + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(USER_BORROW_END_POINT + '/me/loan') + expect(callRequestParam.method).to.be.equal('GET') + }) + }) - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(USER_BORROW_END_POINT + '/userId/loan'); - expect(callRequestParam.method).to.be.equal('GET'); - }); + describe('we can lender operations', function () { + it('add lender', function () { + corbelRequestStub.returns(Promise.resolve()) + var lender = {} - it('get all loans of logged user', function() { - corbelRequestStub.returns(Promise.resolve('OK')); + corbelDriver.borrow.lender().create(lender) - corbelDriver.borrow.user().getAllLoans(); + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(LENDER_BORROW_END_POINT) + expect(callRequestParam.method).to.be.equal('POST') + }) - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(USER_BORROW_END_POINT + '/me/loan'); - expect(callRequestParam.method).to.be.equal('GET'); - }); - }); + it('get lender', function () { + corbelRequestStub.returns(Promise.resolve('OK')) - describe('we can lender operations', function() { - it('add lender', function() { - corbelRequestStub.returns(Promise.resolve()); - var lender = {}; + corbelDriver.borrow.lender('lenderId').get() - corbelDriver.borrow.lender().create(lender); + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(LENDER_BORROW_END_POINT + '/lenderId') + expect(callRequestParam.method).to.be.equal('GET') + }) - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(LENDER_BORROW_END_POINT); - expect(callRequestParam.method).to.be.equal('POST'); - }); + it('get all lender', function () { + corbelRequestStub.returns(Promise.resolve('OK')) - it('get lender', function() { - corbelRequestStub.returns(Promise.resolve('OK')); + corbelDriver.borrow.lender().getAll() - corbelDriver.borrow.lender('lenderId').get(); + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(LENDER_BORROW_END_POINT + '/all') + expect(callRequestParam.method).to.be.equal('GET') + }) - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(LENDER_BORROW_END_POINT + '/lenderId'); - expect(callRequestParam.method).to.be.equal('GET'); - }); + it('get my lender', function () { + corbelRequestStub.returns(Promise.resolve('OK')) - it('get all lender', function() { - corbelRequestStub.returns(Promise.resolve('OK')); + corbelDriver.borrow.lender().get() - corbelDriver.borrow.lender().getAll(); + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(LENDER_BORROW_END_POINT) + expect(callRequestParam.method).to.be.equal('GET') + }) - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(LENDER_BORROW_END_POINT + '/all'); - expect(callRequestParam.method).to.be.equal('GET'); - }); + it('update lender', function () { + corbelRequestStub.returns(Promise.resolve('OK')) + var lender = {} - it('get my lender', function() { - corbelRequestStub.returns(Promise.resolve('OK')); + corbelDriver.borrow.lender('lenderId').update(lender) - corbelDriver.borrow.lender().get(); + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(LENDER_BORROW_END_POINT + '/lenderId') + expect(callRequestParam.method).to.be.equal('PUT') + }) - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(LENDER_BORROW_END_POINT); - expect(callRequestParam.method).to.be.equal('GET'); - }); + it('update my lender', function () { + corbelRequestStub.returns(Promise.resolve('OK')) + var lender = {} + corbelDriver.borrow.lender().update(lender) - it('update lender', function() { - corbelRequestStub.returns(Promise.resolve('OK')); - var lender = {}; + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(LENDER_BORROW_END_POINT) + expect(callRequestParam.method).to.be.equal('PUT') + }) - corbelDriver.borrow.lender('lenderId').update(lender); + it('delete lender', function () { + corbelRequestStub.returns(Promise.resolve('OK')) - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(LENDER_BORROW_END_POINT + '/lenderId'); - expect(callRequestParam.method).to.be.equal('PUT'); - }); + corbelDriver.borrow.lender('lenderId').delete() - it('update my lender', function() { - corbelRequestStub.returns(Promise.resolve('OK')); - var lender = {}; + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(LENDER_BORROW_END_POINT + '/lenderId') + expect(callRequestParam.method).to.be.equal('DELETE') + }) - corbelDriver.borrow.lender().update(lender); + it('delete my lender', function () { + corbelRequestStub.returns(Promise.resolve('OK')) - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(LENDER_BORROW_END_POINT ); - expect(callRequestParam.method).to.be.equal('PUT'); - }); + corbelDriver.borrow.lender().delete() - it('delete lender', function() { - corbelRequestStub.returns(Promise.resolve('OK')); + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(LENDER_BORROW_END_POINT) + expect(callRequestParam.method).to.be.equal('DELETE') + }) - corbelDriver.borrow.lender('lenderId').delete(); + it('get all reservations', function () { + corbelRequestStub.returns(Promise.resolve('OK')) - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(LENDER_BORROW_END_POINT + '/lenderId'); - expect(callRequestParam.method).to.be.equal('DELETE'); - }); + borrow.lender().getAllReservations() - it('delete my lender', function() { - corbelRequestStub.returns(Promise.resolve('OK')); - - corbelDriver.borrow.lender().delete(); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(LENDER_BORROW_END_POINT); - expect(callRequestParam.method).to.be.equal('DELETE'); - }); - - it('get all reservations', function() { - corbelRequestStub.returns(Promise.resolve('OK')); - - borrow.lender().getAllReservations(); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(LENDER_BORROW_END_POINT + '/reservation'); - expect(callRequestParam.method).to.be.equal('GET'); - }); - - }); - -}); + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(LENDER_BORROW_END_POINT + '/reservation') + expect(callRequestParam.method).to.be.equal('GET') + }) + }) +}) diff --git a/test/node/unit/composr.js b/test/node/unit/composr.js index 0b86586..5ad181d 100644 --- a/test/node/unit/composr.js +++ b/test/node/unit/composr.js @@ -1,197 +1,180 @@ -'use strict'; +'use strict' /* jshint camelcase:false */ - -var corbel = require('../../../dist/corbel.js'), - chai = require('chai'), - sinon = require('sinon'), - expect = chai.expect; - -describe('corbel compoSR module', function() { - - var sandbox = sinon.sandbox.create(); - var CONFIG = { - - clientId: 'clientId', - clientSecret: 'clientSecret', - - scopes: ['silkroad-qa:client'], - - urlBase: 'https://{{module}}-corbel.io/' - - }; - - var COMPOSR_END_POINT = CONFIG.urlBase.replace('{{module}}', 'composr'); - - var corbelDriver = corbel.getDriver(CONFIG); - - var corbelRequestStub; - var composr; - - beforeEach(function() { - corbelDriver = corbel.getDriver(CONFIG); - composr = corbelDriver.composr; - corbelRequestStub = sandbox.stub(corbel.request, 'send').returns(Promise.resolve()); - - this.options = { - headers: '', - // body: '', - // data: '', - queryParams: '' - }; - - }); - - afterEach(function() { - sandbox.restore(); - }); - - - - describe('With compoSR module', function() { - - describe('request', function() { - it('the client can do request to some phrase with POST method', function() { - corbelRequestStub.returns(Promise.resolve('OK')); - - var body = { - att: 1, - att2: 'stringValue' - }; - - composr.request('phrase/Id').post(body, this.options); - - var paramsReceived = corbel.request.send.firstCall.args[0]; - expect(paramsReceived.url).to.be.equal(COMPOSR_END_POINT + 'phrase/Id'); - expect(paramsReceived.method).to.be.equal('POST'); - expect(JSON.stringify(paramsReceived.data)).to.be.equal(JSON.stringify(body)); - }); - - it('the client can do request to some phrase with POST method, path and query params', function() { - corbelRequestStub.returns(Promise.resolve('OK')); - - var body = { - att: 1, - att2: 'stringValue' - }; - - this.options.queryParams = { - att: 1 - }; - - composr.request('phrase/Id', 'param1', 'param2').post(body, this.options); - - var paramsReceived = corbel.request.send.firstCall.args[0]; - expect(paramsReceived.url).to.be.equal(COMPOSR_END_POINT + 'phrase/Id/param1/param2?att=1'); - expect(paramsReceived.method).to.be.equal('POST'); - expect(JSON.stringify(paramsReceived.data)).to.be.equal(JSON.stringify(body)); - }); - - it('the client can do request to some phrase with GET method', function() { - corbelRequestStub.returns(Promise.resolve('OK')); - - composr.request('phrase/Id?att=1&att2="stringValue"').get(this.options); - - var paramsReceived = corbel.request.send.firstCall.args[0]; - expect(paramsReceived.url).to.be.equal(COMPOSR_END_POINT + 'phrase/Id?att=1&att2="stringValue"'); - expect(paramsReceived.method).to.be.equal('GET'); - }); - - it('the client can do request to some phrase with PUT method', function() { - corbelRequestStub.returns(Promise.resolve('OK')); - - var body = { - att: 1, - att2: 'stringValue' - }; - - composr.request('phrase/Id').put(body, this.options); - - var paramsReceived = corbel.request.send.firstCall.args[0]; - expect(paramsReceived.url).to.be.equal(COMPOSR_END_POINT + 'phrase/Id'); - expect(paramsReceived.method).to.be.equal('PUT'); - expect(JSON.stringify(paramsReceived.data)).to.be.equal(JSON.stringify(body)); - }); - - it('the client can do request to some phrase with DELETE method', function() { - corbelRequestStub.returns(Promise.resolve('OK')); - - composr.request('phrase/Id').delete(this.options); - - var paramsReceived = corbel.request.send.firstCall.args[0]; - expect(paramsReceived.url).to.be.equal(COMPOSR_END_POINT + 'phrase/Id'); - expect(paramsReceived.method).to.be.equal('DELETE'); - }); - - - }); - - describe('phrases', function() { - - it('its possible add phrases', function() { - corbelRequestStub.returns(Promise.resolve('OK')); - - var phrase = { - id: 'id', - method: 'GET', - code: 'test code', - url: 'http//:test' - }; - - composr.phrase().put(phrase); - - var paramsReceived = corbel.request.send.firstCall.args[0]; - expect(paramsReceived.url).to.be.equal(COMPOSR_END_POINT + 'phrase'); - expect(paramsReceived.method).to.be.equal('PUT'); - expect(JSON.stringify(paramsReceived.data)).to.be.equal(JSON.stringify(phrase)); - }); - - it('it is not possible to get phrases without an id', function() { - corbelRequestStub.returns(Promise.resolve('OK')); - expect(function(){ - composr.phrase().get(); - }).to.throw('id value is mandatory and cannot be undefined'); - }); - - it('its possible get phrases', function() { - corbelRequestStub.returns(Promise.resolve('OK')); - - composr.phrase('phrase/Id').get(); - - var paramsReceived = corbel.request.send.firstCall.args[0]; - expect(paramsReceived.url).to.be.equal(COMPOSR_END_POINT + 'phrase/phrase/Id'); - expect(paramsReceived.method).to.be.equal('GET'); - }); - - it('its possible get all phrases by domain', function() { - corbelRequestStub.returns(Promise.resolve('OK')); - - composr.phrase().getAll(); - - var paramsReceived = corbel.request.send.firstCall.args[0]; - expect(paramsReceived.url).to.be.equal(COMPOSR_END_POINT + 'phrase'); - expect(paramsReceived.method).to.be.equal('GET'); - }); - - it('it is not possible to delete phrases without an id', function() { - corbelRequestStub.returns(Promise.resolve('OK')); - expect(function(){ - composr.phrase().delete(); - }).to.throw('id value is mandatory and cannot be undefined'); - }); - - it('its possible delete phrases', function() { - corbelRequestStub.returns(Promise.resolve('OK')); - - composr.phrase('phrase/Id').delete(); - - var paramsReceived = corbel.request.send.firstCall.args[0]; - expect(paramsReceived.url).to.be.equal(COMPOSR_END_POINT + 'phrase/phrase/Id'); - expect(paramsReceived.method).to.be.equal('DELETE'); - }); - }); - - - }); - - -}); +/* globals describe it beforeEach afterEach */ + +var corbel = require('../../../dist/corbel.js') +var chai = require('chai') +var sinon = require('sinon') +var expect = chai.expect + +describe('corbel compoSR module', function () { + var sandbox = sinon.sandbox.create() + var CONFIG = { + clientId: 'clientId', + clientSecret: 'clientSecret', + scopes: ['silkroad-qa:client'], + urlBase: 'https://{{module}}-corbel.io/' + } + + var COMPOSR_END_POINT = CONFIG.urlBase.replace('{{module}}', 'composr') + var corbelDriver = corbel.getDriver(CONFIG) + var corbelRequestStub + var composr + + beforeEach(function () { + corbelDriver = corbel.getDriver(CONFIG) + composr = corbelDriver.composr + corbelRequestStub = sandbox.stub(corbel.request, 'send').returns(Promise.resolve()) + + this.options = { + headers: '', + // body: '', + // data: '', + queryParams: '' + } + }) + + afterEach(function () { + sandbox.restore() + }) + + describe('With compoSR module', function () { + describe('request', function () { + it('the client can do request to some phrase with POST method', function () { + corbelRequestStub.returns(Promise.resolve('OK')) + + var body = { + att: 1, + att2: 'stringValue' + } + + composr.request('phrase/Id').post(body, this.options) + + var paramsReceived = corbel.request.send.firstCall.args[0] + expect(paramsReceived.url).to.be.equal(COMPOSR_END_POINT + 'phrase/Id') + expect(paramsReceived.method).to.be.equal('POST') + expect(JSON.stringify(paramsReceived.data)).to.be.equal(JSON.stringify(body)) + }) + + it('the client can do request to some phrase with POST method, path and query params', function () { + corbelRequestStub.returns(Promise.resolve('OK')) + + var body = { + att: 1, + att2: 'stringValue' + } + + this.options.queryParams = { + att: 1 + } + + composr.request('phrase/Id', 'param1', 'param2').post(body, this.options) + + var paramsReceived = corbel.request.send.firstCall.args[0] + expect(paramsReceived.url).to.be.equal(COMPOSR_END_POINT + 'phrase/Id/param1/param2?att=1') + expect(paramsReceived.method).to.be.equal('POST') + expect(JSON.stringify(paramsReceived.data)).to.be.equal(JSON.stringify(body)) + }) + + it('the client can do request to some phrase with GET method', function () { + corbelRequestStub.returns(Promise.resolve('OK')) + + composr.request('phrase/Id?att=1&att2="stringValue"').get(this.options) + + var paramsReceived = corbel.request.send.firstCall.args[0] + expect(paramsReceived.url).to.be.equal(COMPOSR_END_POINT + 'phrase/Id?att=1&att2="stringValue"') + expect(paramsReceived.method).to.be.equal('GET') + }) + + it('the client can do request to some phrase with PUT method', function () { + corbelRequestStub.returns(Promise.resolve('OK')) + + var body = { + att: 1, + att2: 'stringValue' + } + + composr.request('phrase/Id').put(body, this.options) + + var paramsReceived = corbel.request.send.firstCall.args[0] + expect(paramsReceived.url).to.be.equal(COMPOSR_END_POINT + 'phrase/Id') + expect(paramsReceived.method).to.be.equal('PUT') + expect(JSON.stringify(paramsReceived.data)).to.be.equal(JSON.stringify(body)) + }) + + it('the client can do request to some phrase with DELETE method', function () { + corbelRequestStub.returns(Promise.resolve('OK')) + + composr.request('phrase/Id').delete(this.options) + + var paramsReceived = corbel.request.send.firstCall.args[0] + expect(paramsReceived.url).to.be.equal(COMPOSR_END_POINT + 'phrase/Id') + expect(paramsReceived.method).to.be.equal('DELETE') + }) + }) + + describe('phrases', function () { + it('its possible add phrases', function () { + corbelRequestStub.returns(Promise.resolve('OK')) + + var phrase = { + id: 'id', + method: 'GET', + code: 'test code', + url: 'http//:test' + } + + composr.phrase().put(phrase) + + var paramsReceived = corbel.request.send.firstCall.args[0] + expect(paramsReceived.url).to.be.equal(COMPOSR_END_POINT + 'phrase') + expect(paramsReceived.method).to.be.equal('PUT') + expect(JSON.stringify(paramsReceived.data)).to.be.equal(JSON.stringify(phrase)) + }) + + it('it is not possible to get phrases without an id', function () { + corbelRequestStub.returns(Promise.resolve('OK')) + expect(function () { + composr.phrase().get() + }).to.throw('id value is mandatory and cannot be undefined') + }) + + it('its possible get phrases', function () { + corbelRequestStub.returns(Promise.resolve('OK')) + + composr.phrase('phrase/Id').get() + + var paramsReceived = corbel.request.send.firstCall.args[0] + expect(paramsReceived.url).to.be.equal(COMPOSR_END_POINT + 'phrase/phrase/Id') + expect(paramsReceived.method).to.be.equal('GET') + }) + + it('its possible get all phrases by domain', function () { + corbelRequestStub.returns(Promise.resolve('OK')) + + composr.phrase().getAll() + + var paramsReceived = corbel.request.send.firstCall.args[0] + expect(paramsReceived.url).to.be.equal(COMPOSR_END_POINT + 'phrase') + expect(paramsReceived.method).to.be.equal('GET') + }) + + it('it is not possible to delete phrases without an id', function () { + corbelRequestStub.returns(Promise.resolve('OK')) + expect(function () { + composr.phrase().delete() + }).to.throw('id value is mandatory and cannot be undefined') + }) + + it('its possible delete phrases', function () { + corbelRequestStub.returns(Promise.resolve('OK')) + + composr.phrase('phrase/Id').delete() + + var paramsReceived = corbel.request.send.firstCall.args[0] + expect(paramsReceived.url).to.be.equal(COMPOSR_END_POINT + 'phrase/phrase/Id') + expect(paramsReceived.method).to.be.equal('DELETE') + }) + }) + }) +}) diff --git a/test/node/unit/config.js b/test/node/unit/config.js index 1452c67..d395c26 100644 --- a/test/node/unit/config.js +++ b/test/node/unit/config.js @@ -1,187 +1,175 @@ -'use strict'; - -var corbel = require('../../../dist/corbel.js'), - chai = require('chai'), - expect = chai.expect; - - -describe('In corbel.Config', function() { - - it('is defined and is a function', function() { - expect(corbel.Config).to.be.a('function'); - }); - - it('has all properties defined', function() { - expect(corbel.Config).to.have.ownProperty('create'); - expect(corbel.Config).to.have.ownProperty('isNode'); - expect(corbel.Config).to.have.ownProperty('clientType'); - expect(corbel.Config).to.have.ownProperty('wwwRoot'); - }); - - it('can be created with "create" method', function() { - expect(corbel.Config.create()).to.be.an.instanceOf(corbel.Config); - }); - - describe('with a config instance', function() { - - it('has all expected methods', function() { - var config = corbel.Config.create(); - expect(config).to.respondTo('getConfig'); - expect(config).to.respondTo('setConfig'); - expect(config).to.respondTo('get'); - expect(config).to.respondTo('set'); - }); - - it('can be created with default config values', function() { - var config = corbel.Config.create({ - key: 'value' - }); - expect(config.get('key')).to.be.equal('value'); - }); - - it('can update config values', function() { - var config = corbel.Config.create({ - key: 'value' - }); - - config.set('key', 'newvalue'); - - expect(config.get('key')).to.be.equal('newvalue'); - }); - - it('can set new config values', function() { - var config = corbel.Config.create({ - key: 'value' - }); - - config.set('key2', 'newvalue'); - - expect(config.get('key')).to.be.equal('value'); - expect(config.get('key2')).to.be.equal('newvalue'); - }); - - it('can set config values in bulk', function() { - var config = corbel.Config.create({ - key: 'value' - }); - - config.setConfig({ - 'key2': 'newvalue', - 'key3': 100 - }); - - expect(config.get('key')).to.be.equal('value'); - expect(config.get('key2')).to.be.equal('newvalue'); - expect(config.get('key3')).to.be.equal(100); - }); - - it('can retrieve all config values', function() { - var config = corbel.Config.create({ - key: 'value' - }); - - config.set('key2', 'newvalue'); - - config = config.getConfig(); - - expect(config).to.have.ownProperty('key'); - expect(config).to.have.ownProperty('key2'); - - expect(config.key).to.be.equal('value'); - expect(config.key2).to.be.equal('newvalue'); - }); - - describe('when getting a value', function() { - - it('throws an error if no default value is defined', function() { - var config = corbel.Config.create({ - key: 'value' - }); - - expect(function() { - config.get('key2'); - }).to.throw('config:undefined:key2'); - }); - - it('returns an error if default value is defined', function() { - var config = corbel.Config.create({ - key: 'value' - }); - - expect(config.get('key2', 'value2')).to.be.equal('value2'); - }); - - }); - - - describe('get current endpoint', function() { - it('constructs the url correctly if no local endpoint is provided', function(){ - var driver = corbel.getDriver({ - urlBase : 'https://{{module}}-int.bqws.io/v1.0/' - }); - var schedulerEndpoint = 'https://scheduler-int.bqws.io/v1.0/'; - var schedulerConstructedEndpoint = driver.config.getCurrentEndpoint(corbel.Scheduler.moduleName); - expect(schedulerConstructedEndpoint).to.equals(schedulerEndpoint); - }); - - it('constructs the url correctly with modulePort placeholder', function(){ - var driver = corbel.getDriver({ - urlBase : 'https://{{module}}-int.bqws.io/{{modulePort}}/v1.0/' - }); - var schedulerPort = driver.scheduler.task()._buildPort(driver.config); - var schedulerEndpoint = 'https://scheduler-int.bqws.io/8094/v1.0/'; - var schedulerConstructedEndpoint = driver.config.getCurrentEndpoint(corbel.Scheduler.moduleName, schedulerPort); - expect(schedulerConstructedEndpoint).to.equals(schedulerEndpoint); - }); - - it('returns the custom endpoint if it is provided', function(){ - var schedulerEndpoint = 'http://www.schedulers.com'; - var driver = corbel.getDriver({ - urlBase : 'https://{{module}}-int.bqws.io/{{modulePort}}/v1.0/', - schedulerEndpoint : schedulerEndpoint - }); - var schedulerPort = driver.scheduler.task()._buildPort(driver.config); - var schedulerConstructedEndpoint = driver.config.getCurrentEndpoint(corbel.Scheduler.moduleName, schedulerPort); - expect(schedulerConstructedEndpoint).to.equals(schedulerEndpoint); - }); - - it('works for any module', function(){ - var modules = { - 'oauth': 'http://localhost:8084/v1.0/', - 'resources': 'http://localhost:8080/v1.0/', - 'iam': 'http://localhost:8082/v1.0/', - 'evci': 'http://localhost:8086/v1.0/', - 'ec': 'http://localhost:8088/v1.0/', - 'assets': 'http://localhost:8092/v1.0/', - 'notifications': 'http://localhost:8094/v1.0/', - 'bqpon': 'http://localhost:8090/v1.0/', - 'webfs': 'http://localhost:8096/v1.0/', - 'scheduler': 'http://localhost:8098/v1.0/', - 'borrow': 'http://localhost:8100/v1.0/', - 'composr': 'http://localhost:3000/' - }; - - var driverConfig = { - urlBase : 'https://{{module}}-int.bqws.io/{{modulePort}}/v1.0/' - }; - - Object.keys(modules).forEach(function(moduleName){ - driverConfig[moduleName+'Endpoint'] = modules[moduleName]; - }); - - var driver = corbel.getDriver(driverConfig); - - Object.keys(modules).forEach(function(moduleName){ - expect(driver.config.getCurrentEndpoint(moduleName)).to.equals(modules[moduleName]); - }); - - }); - - - }); - - }); - - - -}); +'use strict' +/* globals describe it */ + +var corbel = require('../../../dist/corbel.js') +var chai = require('chai') +var expect = chai.expect + +describe('In corbel.Config', function () { + it('is defined and is a function', function () { + expect(corbel.Config).to.be.a('function') + }) + + it('has all properties defined', function () { + expect(corbel.Config).to.have.ownProperty('create') + expect(corbel.Config).to.have.ownProperty('isNode') + expect(corbel.Config).to.have.ownProperty('clientType') + expect(corbel.Config).to.have.ownProperty('wwwRoot') + }) + + it('can be created with "create" method', function () { + expect(corbel.Config.create()).to.be.an.instanceOf(corbel.Config) + }) + + describe('with a config instance', function () { + it('has all expected methods', function () { + var config = corbel.Config.create() + expect(config).to.respondTo('getConfig') + expect(config).to.respondTo('setConfig') + expect(config).to.respondTo('get') + expect(config).to.respondTo('set') + }) + + it('can be created with default config values', function () { + var config = corbel.Config.create({ + key: 'value' + }) + expect(config.get('key')).to.be.equal('value') + }) + + it('can update config values', function () { + var config = corbel.Config.create({ + key: 'value' + }) + + config.set('key', 'newvalue') + + expect(config.get('key')).to.be.equal('newvalue') + }) + + it('can set new config values', function () { + var config = corbel.Config.create({ + key: 'value' + }) + + config.set('key2', 'newvalue') + + expect(config.get('key')).to.be.equal('value') + expect(config.get('key2')).to.be.equal('newvalue') + }) + + it('can set config values in bulk', function () { + var config = corbel.Config.create({ + key: 'value' + }) + + config.setConfig({ + 'key2': 'newvalue', + 'key3': 100 + }) + + expect(config.get('key')).to.be.equal('value') + expect(config.get('key2')).to.be.equal('newvalue') + expect(config.get('key3')).to.be.equal(100) + }) + + it('can retrieve all config values', function () { + var config = corbel.Config.create({ + key: 'value' + }) + + config.set('key2', 'newvalue') + + config = config.getConfig() + + expect(config).to.have.ownProperty('key') + expect(config).to.have.ownProperty('key2') + + expect(config.key).to.be.equal('value') + expect(config.key2).to.be.equal('newvalue') + }) + + describe('when getting a value', function () { + it('throws an error if no default value is defined', function () { + var config = corbel.Config.create({ + key: 'value' + }) + + expect(function () { + config.get('key2') + }).to.throw('config:undefined:key2') + }) + + it('returns an error if default value is defined', function () { + var config = corbel.Config.create({ + key: 'value' + }) + + expect(config.get('key2', 'value2')).to.be.equal('value2') + }) + }) + + describe('get current endpoint', function () { + it('constructs the url correctly if no local endpoint is provided', function () { + var driver = corbel.getDriver({ + urlBase: 'https://{{module}}-int.bqws.io/v1.0/' + }) + var schedulerEndpoint = 'https://scheduler-int.bqws.io/v1.0/' + var schedulerConstructedEndpoint = driver.config.getCurrentEndpoint(corbel.Scheduler.moduleName) + expect(schedulerConstructedEndpoint).to.equals(schedulerEndpoint) + }) + + it('constructs the url correctly with modulePort placeholder', function () { + var driver = corbel.getDriver({ + urlBase: 'https://{{module}}-int.bqws.io/{{modulePort}}/v1.0/' + }) + var schedulerPort = driver.scheduler.task()._buildPort(driver.config) + var schedulerEndpoint = 'https://scheduler-int.bqws.io/8094/v1.0/' + var schedulerConstructedEndpoint = driver.config.getCurrentEndpoint(corbel.Scheduler.moduleName, schedulerPort) + expect(schedulerConstructedEndpoint).to.equals(schedulerEndpoint) + }) + + it('returns the custom endpoint if it is provided', function () { + var schedulerEndpoint = 'http://www.schedulers.com' + var driver = corbel.getDriver({ + urlBase: 'https://{{module}}-int.bqws.io/{{modulePort}}/v1.0/', + schedulerEndpoint: schedulerEndpoint + }) + var schedulerPort = driver.scheduler.task()._buildPort(driver.config) + var schedulerConstructedEndpoint = driver.config.getCurrentEndpoint(corbel.Scheduler.moduleName, schedulerPort) + expect(schedulerConstructedEndpoint).to.equals(schedulerEndpoint) + }) + + it('works for any module', function () { + var modules = { + 'oauth': 'http://localhost:8084/v1.0/', + 'resources': 'http://localhost:8080/v1.0/', + 'iam': 'http://localhost:8082/v1.0/', + 'evci': 'http://localhost:8086/v1.0/', + 'ec': 'http://localhost:8088/v1.0/', + 'assets': 'http://localhost:8092/v1.0/', + 'notifications': 'http://localhost:8094/v1.0/', + 'bqpon': 'http://localhost:8090/v1.0/', + 'webfs': 'http://localhost:8096/v1.0/', + 'scheduler': 'http://localhost:8098/v1.0/', + 'borrow': 'http://localhost:8100/v1.0/', + 'composr': 'http://localhost:3000/' + } + + var driverConfig = { + urlBase: 'https://{{module}}-int.bqws.io/{{modulePort}}/v1.0/' + } + + Object.keys(modules).forEach(function (moduleName) { + driverConfig[moduleName + 'Endpoint'] = modules[moduleName] + }) + + var driver = corbel.getDriver(driverConfig) + + Object.keys(modules).forEach(function (moduleName) { + expect(driver.config.getCurrentEndpoint(moduleName)).to.equals(modules[moduleName]) + }) + }) + }) + }) +}) diff --git a/test/node/unit/corbel.js b/test/node/unit/corbel.js index 728b237..767e622 100644 --- a/test/node/unit/corbel.js +++ b/test/node/unit/corbel.js @@ -1,296 +1,264 @@ -'use strict'; +'use strict' +/* globals describe it beforeEach afterEach */ -var corbel = require('../../../dist/corbel.js'), - chai = require('chai'), - sinon = require('sinon'), - expect = chai.expect; +var corbel = require('../../../dist/corbel.js') +var chai = require('chai') +var sinon = require('sinon') +var expect = chai.expect +describe('in corbel module', function () { + var sandbox = sinon.sandbox.create() + var corbelDriver -describe('in corbel module', function() { - - var sandbox = sinon.sandbox.create(); - var corbelDriver; - - function createDriver() { + function createDriver () { return corbel.getDriver({ clientId: 'clientId', clientSecret: 'clientSecret', scopes: 'scopesApp', urlBase: 'https://{{module}}-qa.bqws.io/v1.0/' - }); + }) } - beforeEach(function() { - corbelDriver = createDriver(); - }); - - afterEach(function() { - sandbox.restore(); - }); + beforeEach(function () { + corbelDriver = createDriver() + }) - it('is defined and is an object', function() { - expect(corbel).to.be.an('object'); - }); + afterEach(function () { + sandbox.restore() + }) - it('expected methods are available', function() { - expect(corbel).to.respondTo('getDriver'); - }); + it('is defined and is an object', function () { + expect(corbel).to.be.an('object') + }) - it('expected static modules are available', function() { - expect(corbel).to.have.ownProperty('jwt'); - expect(corbel).to.have.ownProperty('request'); - expect(corbel).to.have.ownProperty('utils'); - expect(corbel).to.have.ownProperty('cryptography'); - }); + it('expected methods are available', function () { + expect(corbel).to.respondTo('getDriver') + }) - describe('when generating a new driver', function() { + it('expected static modules are available', function () { + expect(corbel).to.have.ownProperty('jwt') + expect(corbel).to.have.ownProperty('request') + expect(corbel).to.have.ownProperty('utils') + expect(corbel).to.have.ownProperty('cryptography') + }) - it('urlBase is required', function() { - expect(function() { + describe('when generating a new driver', function () { + it('urlBase is required', function () { + expect(function () { corbel.getDriver({ clientId: 'clientId', clientSecret: 'clientSecret', scopes: 'scopesApp' - }); - }).to.throw('error:undefined:urlbase'); - }); - - describe('with all parametes', function() { - - it('it creates a CorbelDriver', function() { - expect(corbelDriver).to.be.an.instanceof(corbel.CorbelDriver); - }); - - }); - - describe('with a CorbelDriver instance', function() { - - it('has all members', function() { - expect(corbelDriver).to.have.ownProperty('config'); - expect(corbelDriver).to.have.property('clone'); - expect(corbelDriver.config).to.be.an.instanceof(corbel.Config); - expect(corbelDriver.iam).to.be.an.instanceof(corbel.Iam); - expect(corbel).to.have.ownProperty('Iam'); - }); - - }); - - }); - - it('can clone a new driver with the same config', function() { - - var clonedDriver = corbelDriver.clone(); - expect(clonedDriver !== corbelDriver).to.be.equal(true); - - var driverConfig = corbelDriver.config.getConfig(); - var clonedConfig = clonedDriver.config.getConfig(); - - expect(driverConfig !== clonedConfig).to.be.equal(true); - expect(driverConfig.clientId).to.be.equal(clonedConfig.clientId); - expect(driverConfig.clientSecret).to.be.equal(clonedConfig.clientSecret); - expect(driverConfig.scopes).to.be.equal(clonedConfig.scopes); - expect(driverConfig.urlBase).to.be.equal(clonedConfig.urlBase); - - }); - - it('clone a new driver with different guid', function() { - - var clonedDriver = corbelDriver.clone({ preserveGuid : true }); - expect(clonedDriver !== corbelDriver).to.be.equal(true); - - expect(clonedDriver.guid).not.to.equals(corbelDriver.guid); - }); - - describe('Event system', function() { - - it('can register new handler', function() { - - var stub = sandbox.stub(); - - expect(corbelDriver._events['custom:event:name']).to.be.equal(undefined); - corbelDriver.addEventListener('custom:event:name', stub); - - expect(corbelDriver._events['custom:event:name'].length).to.be.equal(1); + }) + }).to.throw('error:undefined:urlbase') + }) + + describe('with all parametes', function () { + it('it creates a CorbelDriver', function () { + expect(corbelDriver).to.be.an.instanceof(corbel.CorbelDriver) + }) + }) + + describe('with a CorbelDriver instance', function () { + it('has all members', function () { + expect(corbelDriver).to.have.ownProperty('config') + expect(corbelDriver).to.have.property('clone') + expect(corbelDriver.config).to.be.an.instanceof(corbel.Config) + expect(corbelDriver.iam).to.be.an.instanceof(corbel.Iam) + expect(corbel).to.have.ownProperty('Iam') + }) + }) + }) + + it('can clone a new driver with the same config', function () { + var clonedDriver = corbelDriver.clone() + expect(clonedDriver !== corbelDriver).to.be.equal(true) + + var driverConfig = corbelDriver.config.getConfig() + var clonedConfig = clonedDriver.config.getConfig() + + expect(driverConfig !== clonedConfig).to.be.equal(true) + expect(driverConfig.clientId).to.be.equal(clonedConfig.clientId) + expect(driverConfig.clientSecret).to.be.equal(clonedConfig.clientSecret) + expect(driverConfig.scopes).to.be.equal(clonedConfig.scopes) + expect(driverConfig.urlBase).to.be.equal(clonedConfig.urlBase) + }) + + it('clone a new driver with different guid', function () { + var clonedDriver = corbelDriver.clone({ preserveGuid: true }) + expect(clonedDriver !== corbelDriver).to.be.equal(true) + + expect(clonedDriver.guid).not.to.equals(corbelDriver.guid) + }) + + describe('Event system', function () { + it('can register new handler', function () { + var stub = sandbox.stub() + + expect(corbelDriver._events['custom:event:name']).to.be.equal(undefined) + corbelDriver.addEventListener('custom:event:name', stub) + + expect(corbelDriver._events['custom:event:name'].length).to.be.equal(1) corbelDriver.dispatch('custom:event:name', { params: true - }); - - expect(stub.calledOnce).to.be.equal(true); - expect(stub.getCall(0).args[0]).to.be.an('object'); - expect(stub.getCall(0).args[0].params).to.be.equal(true); - - }); + }) - it('is cloned by the clone function', function() { + expect(stub.calledOnce).to.be.equal(true) + expect(stub.getCall(0).args[0]).to.be.an('object') + expect(stub.getCall(0).args[0].params).to.be.equal(true) + }) - var stub = sandbox.stub(); + it('is cloned by the clone function', function () { + var stub = sandbox.stub() - expect(corbelDriver._events['custom:event:name']).to.be.equal(undefined); - corbelDriver.addEventListener('custom:event:name', stub); + expect(corbelDriver._events['custom:event:name']).to.be.equal(undefined) + corbelDriver.addEventListener('custom:event:name', stub) - expect(corbelDriver._events['custom:event:name'].length).to.be.equal(1); + expect(corbelDriver._events['custom:event:name'].length).to.be.equal(1) - var clonedDriver = corbelDriver.clone(); - expect(clonedDriver._events['custom:event:name'].length).to.be.equal(1); + var clonedDriver = corbelDriver.clone() + expect(clonedDriver._events['custom:event:name'].length).to.be.equal(1) - corbelDriver.dispatch('custom:event:name', true); + corbelDriver.dispatch('custom:event:name', true) - expect(stub.calledOnce).to.be.equal(true); + expect(stub.calledOnce).to.be.equal(true) - clonedDriver.dispatch('custom:event:name', true); + clonedDriver.dispatch('custom:event:name', true) - expect(stub.calledTwice).to.be.equal(true); - }); + expect(stub.calledTwice).to.be.equal(true) + }) - it('register same handler once', function() { + it('register same handler once', function () { + var stub = sandbox.stub() - var stub = sandbox.stub(); + expect(corbelDriver._events['custom:event:name']).to.be.equal(undefined) + corbelDriver.addEventListener('custom:event:name', stub) + corbelDriver.addEventListener('custom:event:name', stub) + corbelDriver.addEventListener('custom:event:name', stub) - expect(corbelDriver._events['custom:event:name']).to.be.equal(undefined); - corbelDriver.addEventListener('custom:event:name', stub); - corbelDriver.addEventListener('custom:event:name', stub); - corbelDriver.addEventListener('custom:event:name', stub); - - expect(corbelDriver._events['custom:event:name'].length).to.be.equal(1); + expect(corbelDriver._events['custom:event:name'].length).to.be.equal(1) corbelDriver.dispatch('custom:event:name', { params: true - }); - - expect(stub.calledOnce).to.be.equal(true); - expect(stub.getCall(0).args[0]).to.be.an('object'); - expect(stub.getCall(0).args[0].params).to.be.equal(true); - - }); + }) - it('can remove a handler', function() { + expect(stub.calledOnce).to.be.equal(true) + expect(stub.getCall(0).args[0]).to.be.an('object') + expect(stub.getCall(0).args[0].params).to.be.equal(true) + }) - var stub = sandbox.stub(); + it('can remove a handler', function () { + var stub = sandbox.stub() - expect(corbelDriver._events['custom:event:name']).to.be.equal(undefined); - corbelDriver.addEventListener('custom:event:name', stub); - corbelDriver.removeEventListener('custom:event:name', stub); + expect(corbelDriver._events['custom:event:name']).to.be.equal(undefined) + corbelDriver.addEventListener('custom:event:name', stub) + corbelDriver.removeEventListener('custom:event:name', stub) - expect(corbelDriver._events['custom:event:name'].length).to.be.equal(0); + expect(corbelDriver._events['custom:event:name'].length).to.be.equal(0) corbelDriver.dispatch('custom:event:name', { params: true - }); + }) - expect(stub.callCount).to.be.equal(0); + expect(stub.callCount).to.be.equal(0) + }) - }); + it('does not remove the handler in the clone', function () { + var stub = sandbox.stub() - it('does not remove the handler in the clone', function() { + expect(corbelDriver._events['custom:event:name']).to.be.equal(undefined) + corbelDriver.addEventListener('custom:event:name', stub) - var stub = sandbox.stub(); + var clonedDriver = corbelDriver.clone() + expect(corbelDriver._events['custom:event:name'].length).to.be.equal(1) + expect(clonedDriver._events['custom:event:name'].length).to.be.equal(1) - expect(corbelDriver._events['custom:event:name']).to.be.equal(undefined); - corbelDriver.addEventListener('custom:event:name', stub); + corbelDriver.removeEventListener('custom:event:name', stub) - var clonedDriver = corbelDriver.clone(); - expect(corbelDriver._events['custom:event:name'].length).to.be.equal(1); - expect(clonedDriver._events['custom:event:name'].length).to.be.equal(1); - - corbelDriver.removeEventListener('custom:event:name', stub); - - expect(corbelDriver._events['custom:event:name'].length).to.be.equal(0); - expect(clonedDriver._events['custom:event:name'].length).to.be.equal(1); + expect(corbelDriver._events['custom:event:name'].length).to.be.equal(0) + expect(clonedDriver._events['custom:event:name'].length).to.be.equal(1) corbelDriver.dispatch('custom:event:name', { params: true - }); - - expect(stub.callCount).to.be.equal(0); - - }); - - it('can remove a non existing handler', function() { + }) - var stub = sandbox.stub(); + expect(stub.callCount).to.be.equal(0) + }) - expect(corbelDriver._events['custom:event:name']).to.be.equal(undefined); - corbelDriver.removeEventListener('custom:event:name', stub); + it('can remove a non existing handler', function () { + var stub = sandbox.stub() - expect(corbelDriver._events['custom:event:name']).to.be.equal(undefined); + expect(corbelDriver._events['custom:event:name']).to.be.equal(undefined) + corbelDriver.removeEventListener('custom:event:name', stub) - }); + expect(corbelDriver._events['custom:event:name']).to.be.equal(undefined) + }) - describe('trigger an event', function() { + describe('trigger an event', function () { + it('fires handlers as expected', function () { + var stub = sandbox.stub() - it('fires handlers as expected', function() { + expect(corbelDriver._events['custom:event:name']).to.be.equal(undefined) + corbelDriver.addEventListener('custom:event:name', stub) - var stub = sandbox.stub(); - - expect(corbelDriver._events['custom:event:name']).to.be.equal(undefined); - corbelDriver.addEventListener('custom:event:name', stub); - - expect(corbelDriver._events['custom:event:name'].length).to.be.equal(1); + expect(corbelDriver._events['custom:event:name'].length).to.be.equal(1) corbelDriver.dispatch('custom:event:name', { params: true - }); - - expect(stub.calledOnce).to.be.equal(true); - expect(stub.getCall(0).args[0]).to.be.an('object'); - expect(stub.getCall(0).args[0].params).to.be.equal(true); + }) - }); + expect(stub.calledOnce).to.be.equal(true) + expect(stub.getCall(0).args[0]).to.be.an('object') + expect(stub.getCall(0).args[0].params).to.be.equal(true) + }) - it('fires handlers only once', function() { + it('fires handlers only once', function () { + var stub = sandbox.stub() + var stub2 = sandbox.stub() - var stub = sandbox.stub(); - var stub2 = sandbox.stub(); + expect(corbelDriver._events['custom:event:name']).to.be.equal(undefined) + corbelDriver.addEventListener('custom:event:name', stub) + corbelDriver.addEventListener('custom:event:name', stub) + corbelDriver.addEventListener('custom:event:name', stub2) + corbelDriver.addEventListener('custom:event:name', stub2) + corbelDriver.removeEventListener('custom:event:name', stub) + corbelDriver.addEventListener('custom:event:name', stub) - expect(corbelDriver._events['custom:event:name']).to.be.equal(undefined); - corbelDriver.addEventListener('custom:event:name', stub); - corbelDriver.addEventListener('custom:event:name', stub); - corbelDriver.addEventListener('custom:event:name', stub2); - corbelDriver.addEventListener('custom:event:name', stub2); - corbelDriver.removeEventListener('custom:event:name', stub); - corbelDriver.addEventListener('custom:event:name', stub); - - expect(corbelDriver._events['custom:event:name'].length).to.be.equal(2); + expect(corbelDriver._events['custom:event:name'].length).to.be.equal(2) corbelDriver.dispatch('custom:event:name', { params: true - }); - - expect(stub.calledOnce).to.be.equal(true); - expect(stub2.calledOnce).to.be.equal(true); - expect(stub.getCall(0).args[0]).to.be.an('object'); - expect(stub.getCall(0).args[0].params).to.be.equal(true); - - expect(stub2.getCall(0).args[0]).to.be.an('object'); - expect(stub2.getCall(0).args[0].params).to.be.equal(true); + }) - }); + expect(stub.calledOnce).to.be.equal(true) + expect(stub2.calledOnce).to.be.equal(true) + expect(stub.getCall(0).args[0]).to.be.an('object') + expect(stub.getCall(0).args[0].params).to.be.equal(true) - it('do not fires removed handlers', function() { + expect(stub2.getCall(0).args[0]).to.be.an('object') + expect(stub2.getCall(0).args[0].params).to.be.equal(true) + }) - var stub = sandbox.stub(); - var stub2 = sandbox.stub(); + it('do not fires removed handlers', function () { + var stub = sandbox.stub() + var stub2 = sandbox.stub() - expect(corbelDriver._events['custom:event:name']).to.be.equal(undefined); - corbelDriver.addEventListener('custom:event:name', stub); - corbelDriver.addEventListener('custom:event:name', stub2); - corbelDriver.removeEventListener('custom:event:name', stub); + expect(corbelDriver._events['custom:event:name']).to.be.equal(undefined) + corbelDriver.addEventListener('custom:event:name', stub) + corbelDriver.addEventListener('custom:event:name', stub2) + corbelDriver.removeEventListener('custom:event:name', stub) - expect(corbelDriver._events['custom:event:name'].length).to.be.equal(1); + expect(corbelDriver._events['custom:event:name'].length).to.be.equal(1) corbelDriver.dispatch('custom:event:name', { params: true - }); - - expect(stub.callCount).to.be.equal(0); - expect(stub2.callCount).to.be.equal(1); - - }); - - }); - - }); - -}); + }) + + expect(stub.callCount).to.be.equal(0) + expect(stub2.callCount).to.be.equal(1) + }) + }) + }) +}) diff --git a/test/node/unit/domain.js b/test/node/unit/domain.js index d45b4f0..63a15c2 100644 --- a/test/node/unit/domain.js +++ b/test/node/unit/domain.js @@ -1,58 +1,58 @@ -'use strict'; +'use strict' /* jshint camelcase:false */ - -var corbel = require('../../../dist/corbel.js'), - chai = require('chai'), - sinon = require('sinon'), - expect = chai.expect; - -describe('With custom domain we can', function() { - - var sandbox = sinon.sandbox.create(); - - var CONFIG = { - clientId: 'clientId', - clientSecret: 'clientSecret', - scopes: ['corbel-qa:client'], - urlBase: 'https://{{module}}-corbel.io/' - }; - - var RESOURCE_COLLECTION_URL = CONFIG.urlBase.replace('{{module}}', 'resources') + '{{domain}}/resource/{{resource}}' ; - - var corbelDriver, corbelRequestStub; - - beforeEach(function() { - corbelDriver = corbel.getDriver(CONFIG); - corbelRequestStub = sandbox.stub(corbel.request, 'send'); - corbelRequestStub.returns(Promise.resolve()); - }); - - afterEach(function() { - sandbox.restore(); - }); - - it('add a custom domain value', function() { - var resource = 'resource:entity'; - var customDomain = 'oneTestDomain'; - - var url = RESOURCE_COLLECTION_URL.replace('{{resource}}', resource).replace('{{domain}}', customDomain); - expect(corbelDriver.domain(customDomain).resources.collection(resource).getURL()).to.be.equal(url); - }); - - it('does not persist the value on the configuration for consecutive calls', function(done){ - var resource = 'resource:entity'; - var customDomain = 'oneTestDomainTwo'; - - var urlWithDomain = RESOURCE_COLLECTION_URL.replace('{{resource}}', resource).replace('{{domain}}', customDomain); - var urlWithoutDomain = RESOURCE_COLLECTION_URL.replace('{{resource}}', resource).replace('{{domain}}', 'unauthenticated'); - - expect(corbelDriver.domain(customDomain).resources.collection(resource).getURL()).to.be.equal(urlWithDomain); - - corbelDriver.domain(customDomain).resources.collection(resource) - .get() - .then(function(){ - expect(corbelDriver.resources.collection(resource).getURL()).to.be.equal(urlWithoutDomain); - }) - .should.notify(done); - }); -}); +/* globals describe it beforeEach afterEach */ + +var corbel = require('../../../dist/corbel.js') +var chai = require('chai') +var sinon = require('sinon') +var expect = chai.expect + +describe('With custom domain we can', function () { + var sandbox = sinon.sandbox.create() + + var CONFIG = { + clientId: 'clientId', + clientSecret: 'clientSecret', + scopes: ['corbel-qa:client'], + urlBase: 'https://{{module}}-corbel.io/' + } + + var RESOURCE_COLLECTION_URL = CONFIG.urlBase.replace('{{module}}', 'resources') + '{{domain}}/resource/{{resource}}' + + var corbelDriver, corbelRequestStub + + beforeEach(function () { + corbelDriver = corbel.getDriver(CONFIG) + corbelRequestStub = sandbox.stub(corbel.request, 'send') + corbelRequestStub.returns(Promise.resolve()) + }) + + afterEach(function () { + sandbox.restore() + }) + + it('add a custom domain value', function () { + var resource = 'resource:entity' + var customDomain = 'oneTestDomain' + + var url = RESOURCE_COLLECTION_URL.replace('{{resource}}', resource).replace('{{domain}}', customDomain) + expect(corbelDriver.domain(customDomain).resources.collection(resource).getURL()).to.be.equal(url) + }) + + it('does not persist the value on the configuration for consecutive calls', function (done) { + var resource = 'resource:entity' + var customDomain = 'oneTestDomainTwo' + + var urlWithDomain = RESOURCE_COLLECTION_URL.replace('{{resource}}', resource).replace('{{domain}}', customDomain) + var urlWithoutDomain = RESOURCE_COLLECTION_URL.replace('{{resource}}', resource).replace('{{domain}}', 'unauthenticated') + + expect(corbelDriver.domain(customDomain).resources.collection(resource).getURL()).to.be.equal(urlWithDomain) + + corbelDriver.domain(customDomain).resources.collection(resource) + .get() + .then(function () { + expect(corbelDriver.resources.collection(resource).getURL()).to.be.equal(urlWithoutDomain) + }) + .should.notify(done) + }) +}) diff --git a/test/node/unit/ec.js b/test/node/unit/ec.js index 891e0b4..63f6462 100644 --- a/test/node/unit/ec.js +++ b/test/node/unit/ec.js @@ -1,15 +1,14 @@ -'use strict'; +'use strict' +/* globals describe it beforeEach afterEach */ -var corbel = require('../../../dist/corbel.js'), - chai = require('chai'), - sinon = require('sinon'), - expect = chai.expect; +var corbel = require('../../../dist/corbel.js') +var chai = require('chai') +var sinon = require('sinon') +var expect = chai.expect -describe('In EC module', function() { - - var sandbox = sinon.sandbox.create(); +describe('In EC module', function () { + var sandbox = sinon.sandbox.create() var CONFIG = { - clientId: 'clientId', clientSecret: 'clientSecret', @@ -17,47 +16,46 @@ describe('In EC module', function() { urlBase: 'https://{{module}}-corbel.io/' - }; + } - var EC_URL = CONFIG.urlBase.replace('{{module}}', corbel.Ec.moduleName); + var EC_URL = CONFIG.urlBase.replace('{{module}}', corbel.Ec.moduleName) - var corbelDriver = corbel.getDriver(CONFIG); + var corbelDriver = corbel.getDriver(CONFIG) - var corbelRequestStub; + var corbelRequestStub - beforeEach(function() { - corbelRequestStub = sandbox.stub(corbel.request, 'send'); - }); + beforeEach(function () { + corbelRequestStub = sandbox.stub(corbel.request, 'send') + }) - afterEach(function() { - sandbox.restore(); - }); + afterEach(function () { + sandbox.restore() + }) - describe('with product,', function() { + describe('with product,', function () { + it('create one', function () { + corbelRequestStub.returns(Promise.resolve()) + var productData = "{'test_object':'test'}" + corbelDriver.ec.product().create(productData) - it('create one', function() { - corbelRequestStub.returns(Promise.resolve()); - var productData = '{\'test_object\':\'test\'}'; - corbelDriver.ec.product().create(productData); + var callRequestParam = corbelRequestStub.getCall(0).args[0] + expect(callRequestParam.url).to.be.equal(EC_URL + 'product') + expect(callRequestParam.method).to.be.equal('POST') + expect(callRequestParam.data).to.be.equal(productData) + }) - var callRequestParam = corbelRequestStub.getCall(0).args[0]; - expect(callRequestParam.url).to.be.equal(EC_URL + 'product'); - expect(callRequestParam.method).to.be.equal('POST'); - expect(callRequestParam.data).to.be.equal(productData); - }); + it('get one', function () { + corbelRequestStub.returns(Promise.resolve('OK')) - it('get one', function() { - corbelRequestStub.returns(Promise.resolve('OK')); + corbelDriver.ec.product('idProduct').get() - corbelDriver.ec.product('idProduct').get(); + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.include(EC_URL + 'product') + expect(callRequestParam.method).to.be.equal('GET') + }) - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.include(EC_URL + 'product'); - expect(callRequestParam.method).to.be.equal('GET'); - }); - - it('get all with params', function() { - corbelRequestStub.returns(Promise.resolve('OK')); + it('get all with params', function () { + corbelRequestStub.returns(Promise.resolve('OK')) var params = { query: [{ '$eq': { @@ -71,191 +69,183 @@ describe('In EC module', function() { sort: { field: 'asc' } - }; - - corbelDriver.ec.product().get(params); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.include(EC_URL + 'product'); - expect(callRequestParam.method).to.be.equal('GET'); - console.log(callRequestParam); - expect(callRequestParam.url).to.contain('api:query=' + encodeURIComponent('[{"$eq":{"field":"value"}}]') + '&api:sort=' + encodeURIComponent('{"field":"asc"}') + '&api:page=3&api:pageSize=2'); - }); - - it('update one without an id', function() { - corbelRequestStub.returns(Promise.resolve('OK')); - expect(function(){ - corbelDriver.ec.product().update({}); - }).to.throw('id value is mandatory and cannot be undefined'); - }); - - it('update one', function() { - corbelRequestStub.returns(Promise.resolve(204)); - var productDataUpdate = '{\'test_object\':\'testUpdate\'}'; - var idProduct = 1; - - corbelDriver.ec.product(idProduct).update(productDataUpdate); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(EC_URL + 'product' + '/1'); - expect(callRequestParam.method).to.be.equal('PUT'); - expect(callRequestParam.data).to.be.equal(productDataUpdate); - }); - - it('delete one without an id', function() { - corbelRequestStub.returns(Promise.resolve('OK')); - expect(function(){ - corbelDriver.ec.product().delete(); - }).to.throw('id value is mandatory and cannot be undefined'); - }); - - it('delete one', function() { - corbelRequestStub.returns(Promise.resolve(204)); - var idProduct = 1; - - corbelDriver.ec.product(idProduct).delete(); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(EC_URL + 'product' + '/1'); - expect(callRequestParam.method).to.be.equal('DELETE'); - }); - - }); - - describe('with order,', function() { - - it('get one', function(done) { - corbelRequestStub.returns(Promise.resolve('ok')); - var idOrder = 1; - var response = corbelDriver.ec.order(idOrder).get(); + } + + corbelDriver.ec.product().get(params) + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.include(EC_URL + 'product') + expect(callRequestParam.method).to.be.equal('GET') + console.log(callRequestParam) + expect(callRequestParam.url).to.contain('api:query=' + encodeURIComponent('[{"$eq":{"field":"value"}}]') + '&api:sort=' + encodeURIComponent('{"field":"asc"}') + '&api:page=3&api:pageSize=2') + }) + + it('update one without an id', function () { + corbelRequestStub.returns(Promise.resolve('OK')) + expect(function () { + corbelDriver.ec.product().update({}) + }).to.throw('id value is mandatory and cannot be undefined') + }) + + it('update one', function () { + corbelRequestStub.returns(Promise.resolve(204)) + var productDataUpdate = "{'test_object':'testUpdate'}" + var idProduct = 1 + + corbelDriver.ec.product(idProduct).update(productDataUpdate) + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(EC_URL + 'product' + '/1') + expect(callRequestParam.method).to.be.equal('PUT') + expect(callRequestParam.data).to.be.equal(productDataUpdate) + }) + + it('delete one without an id', function () { + corbelRequestStub.returns(Promise.resolve('OK')) + expect(function () { + corbelDriver.ec.product().delete() + }).to.throw('id value is mandatory and cannot be undefined') + }) + + it('delete one', function () { + corbelRequestStub.returns(Promise.resolve(204)) + var idProduct = 1 + + corbelDriver.ec.product(idProduct).delete() + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(EC_URL + 'product' + '/1') + expect(callRequestParam.method).to.be.equal('DELETE') + }) + }) + + describe('with order,', function () { + it('get one', function (done) { + corbelRequestStub.returns(Promise.resolve('ok')) + var idOrder = 1 + var response = corbelDriver.ec.order(idOrder).get() expect(response).be.eventually.fulfilled - .then(function(response) { - expect(response).to.be.equal('ok'); + .then(function (response) { + expect(response).to.be.equal('ok') - var paramsRecived = corbel.request.send.firstCall.args[0]; - expect(paramsRecived.url).to.be.equal(EC_URL + 'order/1'); - expect(paramsRecived.method).to.be.equal('GET'); + var paramsRecived = corbel.request.send.firstCall.args[0] + expect(paramsRecived.url).to.be.equal(EC_URL + 'order/1') + expect(paramsRecived.method).to.be.equal('GET') }).should.be.eventually.fulfilled - .and.notify(done); - - }); - - it('get one without an id', function() { - corbelRequestStub.returns(Promise.resolve('OK')); - expect(function(){ - corbelDriver.ec.order().get(); - }).to.throw('id value is mandatory and cannot be undefined'); - }); - - it('update one', function(done) { - corbelRequestStub.returns(Promise.resolve(204)); - var productDataUpdate = '{\'test_object\':\'testUpdate\'}'; - var idOrder = 1; - - var response = corbelDriver.ec.order(idOrder).update(productDataUpdate); + .and.notify(done) + }) + + it('get one without an id', function () { + corbelRequestStub.returns(Promise.resolve('OK')) + expect(function () { + corbelDriver.ec.order().get() + }).to.throw('id value is mandatory and cannot be undefined') + }) + + it('update one', function (done) { + corbelRequestStub.returns(Promise.resolve(204)) + var productDataUpdate = "{'test_object':'testUpdate'}" + var idOrder = 1 + + var response = corbelDriver.ec.order(idOrder).update(productDataUpdate) expect(response).be.eventually.fulfilled - .then(function(response) { - expect(response).to.be.equal(204); + .then(function (response) { + expect(response).to.be.equal(204) - var paramsRecived = corbel.request.send.firstCall.args[0]; - expect(paramsRecived.url).to.be.equal(EC_URL + 'order/1'); - expect(paramsRecived.method).to.be.equal('PUT'); - expect(paramsRecived.data).to.be.equal(productDataUpdate); + var paramsRecived = corbel.request.send.firstCall.args[0] + expect(paramsRecived.url).to.be.equal(EC_URL + 'order/1') + expect(paramsRecived.method).to.be.equal('PUT') + expect(paramsRecived.data).to.be.equal(productDataUpdate) }).should.be.eventually.fulfilled - .and.notify(done); + .and.notify(done) + }) - }); + it('update one without an id', function () { + corbelRequestStub.returns(Promise.resolve('OK')) + expect(function () { + corbelDriver.ec.order().update({}) + }).to.throw('id value is mandatory and cannot be undefined') + }) - it('update one without an id', function() { - corbelRequestStub.returns(Promise.resolve('OK')); - expect(function(){ - corbelDriver.ec.order().update({}); - }).to.throw('id value is mandatory and cannot be undefined'); - }); + it('delete one', function (done) { + corbelRequestStub.returns(Promise.resolve(204)) + var idOrder = 1 - it('delete one', function(done) { - corbelRequestStub.returns(Promise.resolve(204)); - var idOrder = 1; - - var response = corbelDriver.ec.order(idOrder).delete(); + var response = corbelDriver.ec.order(idOrder).delete() expect(response).be.eventually.fulfilled - .then(function(response) { - expect(response).to.be.equal(204); + .then(function (response) { + expect(response).to.be.equal(204) - var paramsRecived = corbel.request.send.firstCall.args[0]; - expect(paramsRecived.url).to.be.equal(EC_URL + 'order/1'); - expect(paramsRecived.method).to.be.equal('DELETE'); + var paramsRecived = corbel.request.send.firstCall.args[0] + expect(paramsRecived.url).to.be.equal(EC_URL + 'order/1') + expect(paramsRecived.method).to.be.equal('DELETE') }).should.be.eventually.fulfilled - .and.notify(done); - - }); - - it('delete one without an id', function() { - corbelRequestStub.returns(Promise.resolve('OK')); - expect(function(){ - corbelDriver.ec.order().delete(); - }).to.throw('id value is mandatory and cannot be undefined'); - }); - - it('checkout', function() { - corbelRequestStub.returns(Promise.resolve()); + .and.notify(done) + }) + + it('delete one without an id', function () { + corbelRequestStub.returns(Promise.resolve('OK')) + expect(function () { + corbelDriver.ec.order().delete() + }).to.throw('id value is mandatory and cannot be undefined') + }) + + it('checkout', function () { + corbelRequestStub.returns(Promise.resolve()) var checkoutData = { paymentMethodIds: ['paymentMethod'] - }; - corbelDriver.ec.order('orderId').checkout(checkoutData); + } + corbelDriver.ec.order('orderId').checkout(checkoutData) - var paramsRecived = corbel.request.send.firstCall.args[0]; - expect(paramsRecived.url).to.be.equal(EC_URL + 'order/orderId/checkout'); - expect(paramsRecived.method).to.be.equal('POST'); - expect(paramsRecived.data).to.be.equal(checkoutData); - }); + var paramsRecived = corbel.request.send.firstCall.args[0] + expect(paramsRecived.url).to.be.equal(EC_URL + 'order/orderId/checkout') + expect(paramsRecived.method).to.be.equal('POST') + expect(paramsRecived.data).to.be.equal(checkoutData) + }) - it('checkout without an id', function() { + it('checkout without an id', function () { var checkoutData = { paymentMethodIds: ['paymentMethod'] - }; - corbelRequestStub.returns(Promise.resolve('OK')); - expect(function(){ - corbelDriver.ec.order().checkout(checkoutData); - }).to.throw('id value is mandatory and cannot be undefined'); - }); - - it('checkout failed with empty payment methods', function(done) { - corbelRequestStub.returns(Promise.resolve(202)); + } + corbelRequestStub.returns(Promise.resolve('OK')) + expect(function () { + corbelDriver.ec.order().checkout(checkoutData) + }).to.throw('id value is mandatory and cannot be undefined') + }) + + it('checkout failed with empty payment methods', function (done) { + corbelRequestStub.returns(Promise.resolve(202)) var checkoutData = { paymentMethodIds: [] - }; + } expect(corbelDriver.ec.order('orderId').checkout(checkoutData)).be.eventually.rejected - .then(function(response) { - expect(response.message).to.be.equal('One payment method is needed at least'); + .then(function (response) { + expect(response.message).to.be.equal('One payment method is needed at least') }).should.be.eventually.fulfilled - .and.notify(done); - }); + .and.notify(done) + }) - it('prepare without an id', function() { - corbelRequestStub.returns(Promise.resolve('OK')); - expect(function(){ - corbelDriver.ec.order().prepare(); - }).to.throw('id value is mandatory and cannot be undefined'); - }); + it('prepare without an id', function () { + corbelRequestStub.returns(Promise.resolve('OK')) + expect(function () { + corbelDriver.ec.order().prepare() + }).to.throw('id value is mandatory and cannot be undefined') + }) - it('prepare', function(done) { - corbelRequestStub.returns(Promise.resolve(200)); + it('prepare', function (done) { + corbelRequestStub.returns(Promise.resolve(200)) - var response = corbelDriver.ec.order('orderId').prepare(); + var response = corbelDriver.ec.order('orderId').prepare() expect(response).be.eventually.fulfilled - .then(function(response) { - expect(response).to.be.equal(200); + .then(function (response) { + expect(response).to.be.equal(200) - var paramsRecived = corbel.request.send.firstCall.args[0]; - expect(paramsRecived.url).to.be.equal(EC_URL + 'order/orderId/prepare'); - expect(paramsRecived.method).to.be.equal('POST'); + var paramsRecived = corbel.request.send.firstCall.args[0] + expect(paramsRecived.url).to.be.equal(EC_URL + 'order/orderId/prepare') + expect(paramsRecived.method).to.be.equal('POST') }).should.be.eventually.fulfilled - .and.notify(done); - - }); - - }); - -}); + .and.notify(done) + }) + }) +}) diff --git a/test/node/unit/evci.js b/test/node/unit/evci.js index 452c0e3..8a493cd 100644 --- a/test/node/unit/evci.js +++ b/test/node/unit/evci.js @@ -1,62 +1,61 @@ -'use strict'; +'use strict' /* jshint camelcase:false */ +/* globals describe it beforeEach afterEach */ -var corbel = require('../../../dist/corbel.js'), - chai = require('chai'), - sinon = require('sinon'), - expect = chai.expect; +var corbel = require('../../../dist/corbel.js') +var chai = require('chai') +var sinon = require('sinon') +var expect = chai.expect -describe('In Evci module we can', function() { +describe('In Evci module we can', function () { + var sandbox = sinon.sandbox.create() - var sandbox = sinon.sandbox.create(); + var CONFIG = { + clientId: 'clientId', + clientSecret: 'clientSecret', - var CONFIG = { + scopes: ['silkroad-qa:client', 'resources:send_event_bus', 'resources:test:test_operations'], - clientId: 'clientId', - clientSecret: 'clientSecret', + urlBase: 'https://{{module}}-corbel.io/' - scopes: ['silkroad-qa:client', 'resources:send_event_bus', 'resources:test:test_operations'], + } - urlBase: 'https://{{module}}-corbel.io/' + var EVENT_TYPE = 'log:error' - }; - - var EVENT_TYPE = 'log:error'; - - var EVENT_DATA = '{\'test_object\':\'test\'}'; - - var EVCI_URL = CONFIG.urlBase.replace('{{module}}', corbel.Evci.moduleName) + 'event'; + var EVENT_DATA = "{'test_object':'test'}" - var corbelDriver = corbel.getDriver(CONFIG); + var EVCI_URL = CONFIG.urlBase.replace('{{module}}', corbel.Evci.moduleName) + 'event' - var corbelRequestStub; + var corbelDriver = corbel.getDriver(CONFIG) - beforeEach(function() { - corbelRequestStub = sandbox.stub(corbel.request, 'send'); - }); + var corbelRequestStub - afterEach(function() { - sandbox.restore(); - }); + beforeEach(function () { + corbelRequestStub = sandbox.stub(corbel.request, 'send') + }) - it('generate evci query correctly', function() { - corbelRequestStub.returns(Promise.resolve()); - corbelDriver.evci.event(EVENT_TYPE).publish(EVENT_DATA); + afterEach(function () { + sandbox.restore() + }) - var callRequestParam = corbelRequestStub.getCall(0).args[0]; - expect(callRequestParam.url).to.be.equal(EVCI_URL+'/'+EVENT_TYPE); - expect(callRequestParam.method).to.be.equal('POST'); - expect(callRequestParam.data).to.be.equal(EVENT_DATA); - }); + it('generate evci query correctly', function () { + corbelRequestStub.returns(Promise.resolve()) + corbelDriver.evci.event(EVENT_TYPE).publish(EVENT_DATA) - it('throw exception when create event without type', function() { - corbelRequestStub.returns(Promise.resolve('OK')); - expect(function(){ - corbelDriver.evci.event().publish(EVENT_DATA); - }).to.throw('eventType value is mandatory and cannot be undefined'); - }); + var callRequestParam = corbelRequestStub.getCall(0).args[0] + expect(callRequestParam.url).to.be.equal(EVCI_URL + '/' + EVENT_TYPE) + expect(callRequestParam.method).to.be.equal('POST') + expect(callRequestParam.data).to.be.equal(EVENT_DATA) + }) - it('throw exception when publish event without data', function() { - expect(corbelDriver.evci.event(EVENT_TYPE).publish).to.throw('Send event require data'); - }); -}); + it('throw exception when create event without type', function () { + corbelRequestStub.returns(Promise.resolve('OK')) + expect(function () { + corbelDriver.evci.event().publish(EVENT_DATA) + }).to.throw('eventType value is mandatory and cannot be undefined') + }) + + it('throw exception when publish event without data', function () { + expect(corbelDriver.evci.event(EVENT_TYPE).publish).to.throw('Send event require data') + }) +}) diff --git a/test/node/unit/iam.js b/test/node/unit/iam.js index 3302321..4f9825d 100644 --- a/test/node/unit/iam.js +++ b/test/node/unit/iam.js @@ -1,993 +1,965 @@ -'use strict'; +'use strict' /* jshint camelcase:false */ - -var corbel = require('../../../dist/corbel.js'), - chai = require('chai'), - sinon = require('sinon'), - expect = chai.expect; - -describe('corbel IAM module', function() { - - var sandbox = sinon.sandbox.create(); - var CONFIG = { - - clientId: 'clientId', - clientSecret: 'clientSecret', - audience: 'audience', - scopes: ['silkroad-qa:client', 'resources:send_event_bus', 'resources:test:test_operations', 'resources:music:read_catalog', 'resources:music:streaming'], - - urlBase: 'https://{{module}}-corbel.io/' - - }; - - var IAM_END_POINT = CONFIG.urlBase.replace('{{module}}', 'iam'); - - var corbelDriver = corbel.getDriver(CONFIG); - - var corbelRequestStub; - - beforeEach(function() { - corbelRequestStub = sandbox.stub(corbel.request, 'send').returns(Promise.resolve()); - }); - - afterEach(function() { - sandbox.restore(); - }); - - describe('Creates accessToken', function() { - - it('Using without params', function() { - sandbox.stub(corbel.jwt, '_generateExp').returns(1234); - - var assertion = corbelDriver.iam.token()._getJwt({ - claims: { - exp: 1234 - } - }); - - corbelDriver.iam.token().create(); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'oauth/token'); - expect(callRequestParam.method).to.be.equal('POST'); - expect(callRequestParam.data.assertion).to.be.equal(assertion); - expect(callRequestParam.data.grant_type).to.be.equal(corbel.Iam.GRANT_TYPE); - }); - - it('Using with empty params', function() { - sandbox.stub(corbel.jwt, '_generateExp').returns(1234); - - var assertion = corbelDriver.iam.token()._getJwt({ - claims: { - exp: 1234 - } - }); - - corbelDriver.iam.token().create({}); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'oauth/token'); - expect(callRequestParam.method).to.be.equal('POST'); - expect(callRequestParam.data.assertion).to.be.equal(assertion); - expect(callRequestParam.data.grant_type).to.be.equal(corbel.Iam.GRANT_TYPE); - }); - - describe('mandatory values in config', function(){ - it('expects clientSecret to be defined', function(){ - var config = { - urlBase : 'http://test.com' - }; - var driver = corbel.getDriver(config); - - expect(function(){ - driver.iam.token()._getJwt(); - }).to.throw('config:undefined:clientSecret'); - }); - - it('expects clientId to be defined', function(){ - var config = { - urlBase : 'http://test.com', - clientSecret : 'test' - }; - var driver = corbel.getDriver(config); - - expect(function(){ - driver.iam.token()._getJwt(); - }).to.throw('config:undefined:clientId'); - }); - - it('passes if all mandatory values are provided', function(){ - var config = { - urlBase : 'http://test.com', - clientSecret : 'test', - clientId : 'test' - }; - var driver = corbel.getDriver(config); - - expect(function(){ - driver.iam.token()._getJwt(); - }).not.to.throw(Error); - }); - }); - - it('Using JWT correctly', function() { - var testJwt = '_jwt_'; - corbelDriver.iam.token().create({ - jwt: testJwt - }); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'oauth/token'); - expect(callRequestParam.method).to.be.equal('POST'); - expect(callRequestParam.data.assertion).to.be.equal(testJwt); - expect(callRequestParam.data.grant_type).to.be.equal(corbel.Iam.GRANT_TYPE); - }); - - it('Using claims correctly', function() { - var testClaims = { - iss: 'clientId', - scope: 'scopes', - aud: 'audience', - exp: 'expireAt', - prn: 'principal' - }; - - var assertion = corbel.jwt.generate(testClaims, CONFIG.clientSecret); - - corbelDriver.iam.token().create({ - claims: testClaims - }); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'oauth/token'); - expect(callRequestParam.method).to.be.equal('POST'); - expect(callRequestParam.data.assertion).to.be.equal(assertion); - expect(callRequestParam.data.grant_type).to.be.equal(corbel.Iam.GRANT_TYPE); - }); - - it('Getting token with cookie with POST', function() { - var testClaims = { - iss: 'clientId', - scope: 'scopes', - aud: 'audience', - exp: 'expireAt', - prn: 'principal' - }; - - corbelDriver.iam.token().create({ - claims: testClaims - }, true); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'oauth/token'); - expect(callRequestParam.headers.RequestCookie).to.be.equal('true'); - }); - - it('Getting token with cookie with GET', function() { - var testJwt = '_jwt_'; - var testOauth = { - code: '_code_' - }; - - corbelDriver.iam.token().create({ - jwt: testJwt, - oauth: testOauth - }, true); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - console.log('callRequestParam', callRequestParam); - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'oauth/token'); - expect(callRequestParam.headers.RequestCookie).to.be.equal('true'); - }); - - it('Using Oauth correctly', function() { - var testJwt = '_jwt_'; - var testOauth = { - code: '_code_' - }; - - corbelDriver.iam.token().create({ - jwt: testJwt, - oauth: testOauth - }); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'oauth/token'); - expect(callRequestParam.method).to.be.equal('GET'); - expect(decodeURIComponent(callRequestParam.query)).to.be.equal('assertion=' + testJwt + '&grant_type=' + corbel.Iam.GRANT_TYPE + '&code=' + testOauth.code); - }); - }); - - describe('Refresh accessToken', function() { - - it('Using without refresh token', function() { - expect(corbelDriver.iam.token().refresh).to. - throw('Refresh access token request must contains refresh token'); - }); - - it('Using refresh token correctly with default scopes', function() { - sandbox.stub(corbel.jwt, '_generateExp').returns(1234); - - corbelDriver.iam.token().refresh('refresh_token'); - - var testJwt = corbel.jwt.generate({ - iss: CONFIG.clientId, - aud: CONFIG.audience, - exp: 1234, - scope: CONFIG.scopes, - 'refresh_token': 'refresh_token' - }, CONFIG.clientSecret); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'oauth/token'); - expect(callRequestParam.method).to.be.equal('POST'); - expect(callRequestParam.data.assertion).to.be.equal(testJwt); - expect(callRequestParam.data.grant_type).to.be.equal(corbel.Iam.GRANT_TYPE); - }); - - it('Using refresh token correctly with scopes', function() { - sandbox.stub(corbel.jwt, '_generateExp').returns(1234); - - corbelDriver.iam.token().refresh('refresh_token', 'test_scope'); - - var claims = { - 'refresh_token': 'refresh_token' - }; - claims.scope = 'test_scope'; - claims.exp = 1234; - - var testJwt = corbel.jwt.generate({ - iss: CONFIG.clientId, - aud: CONFIG.audience, - exp: 1234, - scope: 'test_scope', - 'refresh_token': 'refresh_token' - }, CONFIG.clientSecret); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'oauth/token'); - expect(callRequestParam.method).to.be.equal('POST'); - expect(callRequestParam.data.assertion).to.be.equal(testJwt); - expect(callRequestParam.data.grant_type).to.be.equal(corbel.Iam.GRANT_TYPE); - }); - }); - - describe('usernames availability', function() { - it('get username availability', function() { - var USERNAME = 'test'; - corbelDriver.iam.username().availability(USERNAME); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'username/' + USERNAME); - expect(callRequestParam.method).to.be.equal('HEAD'); - }); - - it('get username availability with undefined value', function() { - corbelRequestStub.returns(Promise.resolve('OK')); - expect(function(){ - corbelDriver.iam.username().availability(); - }).to.throw('username value is mandatory and cannot be undefined'); - }); - - it('username available return true', function(done) { - corbelRequestStub.returns(Promise.reject({ - status: 404 - })); - corbelDriver.iam.username().availability('test').then(function(result) { - expect(result).to.be.equal(true); - done(); - }); - }); - - it('username not available return false', function(done) { - corbelDriver.iam.username().availability('test').then(function(result) { - expect(result).to.be.equal(false); - done(); - }); - }); - - it('on server error reject promise', function(done) { - corbelRequestStub.returns(Promise.reject({ - httpStatus: 500 - })); - corbelDriver.iam.username().availability('test').catch(function() { - done(); - }); - }); - - }); - - describe('Email availability', function() { - it('Get email availability', function() { - var EMAIL = 'test@test.com'; - corbelDriver.iam.email().availability(EMAIL); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'email/' + EMAIL); - expect(callRequestParam.method).to.be.equal('HEAD'); - }); - - it('get email availability with undefined value', function() { - corbelRequestStub.returns(Promise.resolve('OK')); - expect(function(){ - corbelDriver.iam.email().availability(); - }).to.throw('email value is mandatory and cannot be undefined'); - }); - - it('Email available return true', function(done) { - corbelRequestStub.returns(Promise.reject({ - status: 404 - })); - corbelDriver.iam.email().availability('test@domingo.com').then(function(result) { - expect(result).to.be.equal(true); - done(); - }); - }); - - it('Email not available return false', function(done) { - corbelDriver.iam.email().availability('test@test.com').then(function(result) { - expect(result).to.be.equal(false); - done(); - }); - }); - - it('On server error reject promise', function(done) { - corbelRequestStub.returns(Promise.reject({ - httpStatus: 500 - })); - corbelDriver.iam.email().availability('test').catch(function() { - done(); - }); - }); - }); - - describe('Users Management', function() { - - it('Create user', function() { - var username = 'username'; - corbelDriver.iam.users().create({ - username: username - }); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user'); - expect(callRequestParam.method).to.be.equal('POST'); - expect(JSON.stringify(callRequestParam.data)).to.be.equal('{"username":"username"}'); - }); - - it('Get all users', function() { - corbelDriver.iam.users().get(); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user'); - expect(callRequestParam.method).to.be.equal('GET'); - }); - - it('Get user me', function() { - corbelDriver.iam.user('me').get(); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/me'); - expect(callRequestParam.method).to.be.equal('GET'); - }); - - it('Get user', function() { - corbelDriver.iam.user('userId').get(); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/userId'); - expect(callRequestParam.method).to.be.equal('GET'); - }); - - it('Update user', function() { - var username = 'username'; - - corbelDriver.iam.user('userId').update({ - username: username - }); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/userId'); - expect(callRequestParam.method).to.be.equal('PUT'); - expect(JSON.stringify(callRequestParam.data)).to.be.equal('{"username":"username"}'); - }); - - it('Update user using me', function() { - var username = 'username'; - - corbelDriver.iam.user('me').update({ - username: username - }); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/me'); - expect(callRequestParam.method).to.be.equal('PUT'); - expect(JSON.stringify(callRequestParam.data)).to.be.equal('{"username":"username"}'); - }); - - it('Update user me', function() { - var username = 'username'; - - corbelDriver.iam.user().updateMe({ - username: username - }); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/me'); - expect(callRequestParam.method).to.be.equal('PUT'); - expect(JSON.stringify(callRequestParam.data)).to.be.equal('{"username":"username"}'); - }); - - it('Delete user', function() { - corbelDriver.iam.user('userId').delete(); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/userId'); - expect(callRequestParam.method).to.be.equal('DELETE'); - }); - - it('Delete user using me', function() { - corbelDriver.iam.user('me').delete(); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/me'); - expect(callRequestParam.method).to.be.equal('DELETE'); - }); - - it('Delete user me', function() { - - corbelDriver.iam.user().deleteMe(); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/me'); - expect(callRequestParam.method).to.be.equal('DELETE'); - }); - - it('Sign Out user using me', function() { - - corbelDriver.iam.user('me').signOut(); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/me/signout'); - expect(callRequestParam.method).to.be.equal('PUT'); - }); - - it('Sign Out user me', function() { - - corbelDriver.iam.user().signOutMe(); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/me/signout'); - expect(callRequestParam.method).to.be.equal('PUT'); - }); - - it('Disconnect user', function() { - - corbelDriver.iam.user('userId').disconnect(); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/userId/disconnect'); - expect(callRequestParam.method).to.be.equal('PUT'); - }); - - it('Disconnect user logged', function() { - - corbelDriver.iam.user('me').disconnect(); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/me/disconnect'); - expect(callRequestParam.method).to.be.equal('PUT'); - }); - - it('Disconnect me', function() { - - corbelDriver.iam.user().disconnectMe(); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/me/disconnect'); - expect(callRequestParam.method).to.be.equal('PUT'); - }); - - it('generate sendResetPasswordEmail request correctly', function() { - corbelDriver.iam.users().sendResetPasswordEmail('test@email.com'); - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/resetPassword?email=test@email.com'); - expect(callRequestParam.method).to.be.equal('GET'); - }); - - describe('Adding user identity', function() { - it('with valid identity object', function() { - - corbelDriver.iam.user('userId').addIdentity({ - oAuthService: 'silkroad', - oAuthId: '12435' - }); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/userId/identity'); - expect(callRequestParam.method).to.be.equal('POST'); - expect(callRequestParam.data.oAuthService).to.be.equal('silkroad'); - expect(callRequestParam.data.oAuthId).to.be.equal('12435'); - }); - - it('without passing an identity object', function() { - expect(corbelDriver.iam.user('userId').addIdentity).to. - throw('Missing identity'); - }); - }); - - it('Get user identities', function() { - corbelDriver.iam.user('userId').getIdentities(); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/userId/identity'); - expect(callRequestParam.method).to.be.equal('GET'); - }); - - it('Get user identities using me', function() { - corbelDriver.iam.user('me').getIdentities(); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/me/identity'); - expect(callRequestParam.method).to.be.equal('GET'); - }); - - it('Get my identities', function() { - corbelDriver.iam.user().getMyIdentities(); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/me/identity'); - expect(callRequestParam.method).to.be.equal('GET'); - }); - - it('Get user profile using me', function() { - corbelDriver.iam.user('me').getProfile(); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/me/profile'); - expect(callRequestParam.method).to.be.equal('GET'); - }); - - it('Get my profile', function() { - corbelDriver.iam.user().getMyProfile(); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/me/profile'); - expect(callRequestParam.method).to.be.equal('GET'); - }); - - it('Get user profile', function() { - corbelDriver.iam.user('userId').getProfile(); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/userId/profile'); - expect(callRequestParam.method).to.be.equal('GET'); - }); - - it('Get user profiles', function() { - corbelDriver.iam.users().getProfiles(); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/profile'); - expect(callRequestParam.method).to.be.equal('GET'); - }); - - }); - - describe('User devices', function() { - - it('Register my device', function() { - corbelDriver.iam.user().registerMyDevice('Device data'); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/me/devices'); - expect(callRequestParam.method).to.be.equal('PUT'); - }); - - it('Register device', function() { - corbelDriver.iam.user('userId').registerDevice('Device data'); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/userId/devices'); - expect(callRequestParam.method).to.be.equal('PUT'); - }); - - it('Register device using me', function() { - corbelDriver.iam.user('me').registerDevice('Device data'); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/me/devices'); - expect(callRequestParam.method).to.be.equal('PUT'); - }); - - it('Get device id', function() { - corbelDriver.iam.user('userId').getDevice('deviceId'); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/userId/devices/deviceId'); - expect(callRequestParam.method).to.be.equal('GET'); - }); - - it('Get device id using me', function() { - corbelDriver.iam.user('me').getDevice('deviceId'); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/me/devices/deviceId'); - expect(callRequestParam.method).to.be.equal('GET'); - }); - - it('Get my device id', function() { - corbelDriver.iam.user().getMyDevice('deviceId'); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/me/devices/deviceId'); - expect(callRequestParam.method).to.be.equal('GET'); - }); - - it('Get devices', function() { - corbelDriver.iam.user('userId').getDevices(); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/userId/devices/'); - expect(callRequestParam.method).to.be.equal('GET'); - }); - - it('Get devices using me', function() { - corbelDriver.iam.user('me').getDevices(); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/me/devices/'); - expect(callRequestParam.method).to.be.equal('GET'); - }); - - - it('Get my devices', function() { - corbelDriver.iam.user().getMyDevices(); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/me/devices/'); - expect(callRequestParam.method).to.be.equal('GET'); - }); - - it('Get my device', function() { - corbelDriver.iam.user('me').getDevice('123'); - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/me/devices/123'); - expect(callRequestParam.method).to.be.equal('GET'); - }); - - it('Delete my device', function() { - corbelDriver.iam.user('me').deleteDevice('deviceId'); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/me/devices/deviceId'); - expect(callRequestParam.method).to.be.equal('DELETE'); - }); - - it('Delete device', function() { - corbelDriver.iam.user('123').deleteDevice('deviceId'); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/123/devices/deviceId'); - expect(callRequestParam.method).to.be.equal('DELETE'); - }); - - - }); - - describe('User groups', function() { - - it('Add groups to user', function() { - var groups = ['g1', 'g2']; - - corbelDriver.iam.user('userId').addGroups(groups); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/userId/groups'); - expect(callRequestParam.method).to.be.equal('PUT'); - }); - - it('delete group to user', function() { - corbelDriver.iam.user('userId').deleteGroup('g1'); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/userId/groups/g1'); - expect(callRequestParam.method).to.be.equal('DELETE'); - }); - - it('delete group my group using me', function() { - corbelDriver.iam.user('me').deleteGroup('g1'); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/me/groups/g1'); - expect(callRequestParam.method).to.be.equal('DELETE'); - }); - - it('delete my group', function() { - corbelDriver.iam.user().deleteMyGroup('g1'); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/me/groups/g1'); - expect(callRequestParam.method).to.be.equal('DELETE'); - }); - - }); - - describe('Domain admin interface', function() { - var data = { - id: 'jklasdfjklasdf', - domain: 'wenuirasdj' - }; - - it('Create a new domain', function() { - corbelDriver.iam.domain().create(data). - then(function(id) { - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'domain'); - expect(callRequestParam.method).to.be.equal('POST'); - expect(data.id).to.be.equal(id); - }); - }); - - it('get a domain with undefined value', function() { - corbelRequestStub.returns(Promise.resolve('OK')); - expect(function(){ - corbelDriver.iam.domain().get(); - }).to.throw('domainId value is mandatory and cannot be undefined'); - }); - - it('Gets a domain', function() { - corbelDriver.iam.domain(data.id).get(); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'domain/' + data.id); - expect(callRequestParam.method).to.be.equal('GET'); - }); - - - it('Gets all domains', function() { - corbelDriver.iam.domain().getAll(); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'domain'); - expect(callRequestParam.method).to.be.equal('GET'); - }); - - it('Update a domain', function() { - corbelDriver.iam.domain(data.id).update(data); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'domain/' + data.id); - expect(callRequestParam.method).to.be.equal('PUT'); - }); - - it('update a domain with undefined value', function() { - corbelRequestStub.returns(Promise.resolve('OK')); - expect(function(){ - corbelDriver.iam.domain().update({}); - }).to.throw('domainId value is mandatory and cannot be undefined'); - }); - - it('Remove a domain', function() { - var domainId = 'sjdfkls'; - corbelDriver.iam.domain(domainId).remove(); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'domain/' + domainId); - expect(callRequestParam.method).to.be.equal('DELETE'); - }); - - it('remove a domain with undefined value', function() { - corbelRequestStub.returns(Promise.resolve('OK')); - expect(function(){ - corbelDriver.iam.domain().remove(); - }).to.throw('domainId value is mandatory and cannot be undefined'); - }); - - it('Create a new client', function() { - corbelDriver.iam.client(data.domain).create(data). - then(function(id) { - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'domain/' + data.domain + '/client'); - expect(callRequestParam.method).to.be.equal('POST'); - expect(data.id).to.be.equal(id); - }); - }); - - it('Create a new client with undefined domainId', function() { - corbelRequestStub.returns(Promise.resolve('OK')); - expect(function(){ - corbelDriver.iam.client(undefined, 'clientId').create({}); - }).to.throw('domainId value is mandatory and cannot be undefined'); - }); - - it('Get a client', function() { - corbelDriver.iam.client(data.domain, data.id).get(); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'domain/' + data.domain + '/client/' + data.id); - expect(callRequestParam.method).to.be.equal('GET'); - }); - - it('get a client with undefined clientId', function() { - corbelRequestStub.returns(Promise.resolve('OK')); - expect(function(){ - corbelDriver.iam.client(data.domain, undefined).get(); - }).to.throw('clientId value is mandatory and cannot be undefined'); - }); - - it('get a client with undefined domainId', function() { - corbelRequestStub.returns(Promise.resolve('OK')); - expect(function(){ - corbelDriver.iam.client(undefined, 'clientId').get(); - }).to.throw('domainId value is mandatory and cannot be undefined'); - }); - - it('Get all clients in a domain', function() { - corbelDriver.iam.client(data.domain).getAll(); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'domain/' + data.domain + '/client'); - expect(callRequestParam.method).to.be.equal('GET'); - }); - - it('Update a client', function() { - corbelDriver.iam.client(data.domain, data.id).update(data); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'domain/' + data.domain + '/client/' + data.id); - expect(callRequestParam.method).to.be.equal('PUT'); - }); - - it('update a new client with undefined domainId', function() { - corbelRequestStub.returns(Promise.resolve('OK')); - expect(function(){ - corbelDriver.iam.client(undefined, 'clientId').update({}); - }).to.throw('domainId value is mandatory and cannot be undefined'); - }); - - it('update a new client with undefined domainId', function() { - corbelRequestStub.returns(Promise.resolve('OK')); - expect(function(){ - corbelDriver.iam.client('domainId', undefined).update({}); - }).to.throw('clientId value is mandatory and cannot be undefined'); - }); - - it('Remove a client', function() { - corbelDriver.iam.client(data.domain, data.id).remove(); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'domain/' + data.domain + '/client/' + data.id); - expect(callRequestParam.method).to.be.equal('DELETE'); - }); - - it('remove a new client with undefined domainId', function() { - corbelRequestStub.returns(Promise.resolve('OK')); - expect(function(){ - corbelDriver.iam.client(undefined, 'clientId').remove({}); - }).to.throw('domainId value is mandatory and cannot be undefined'); - }); - - it('remove a new client with undefined domainId', function() { - corbelRequestStub.returns(Promise.resolve('OK')); - expect(function(){ - corbelDriver.iam.client('domainId', undefined).remove({}); - }).to.throw('clientId value is mandatory and cannot be undefined'); - }); - - }); - - describe('Scope admin interface', function() { - it('Create a new scope', function() { - var scope = { - id: 'jklsdfbnwerj' - }; - - corbelDriver.iam.scope().create(scope). - then(function(id) { - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'scope'); - expect(callRequestParam.method).to.be.equal('POST'); - expect(scope.id).to.be.equal(id); - }); - }); - - it('Get a scope', function() { - var scopeId = 'jklsdfbnwerj'; - - corbelDriver.iam.scope(scopeId).get(); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'scope/' + scopeId); - expect(callRequestParam.method).to.be.equal('GET'); - }); - - it('get a scope with undefined value', function() { - corbelRequestStub.returns(Promise.resolve('OK')); - expect(function(){ - corbelDriver.iam.scope().get(); - }).to.throw('id value is mandatory and cannot be undefined'); - }); - - it('Remove a scope', function() { - var scopeId = 'jklsdfbnwerj'; - - corbelDriver.iam.scope(scopeId).remove(); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'scope/' + scopeId); - expect(callRequestParam.method).to.be.equal('DELETE'); - }); - - it('remove a scope with undefined value', function() { - corbelRequestStub.returns(Promise.resolve('OK')); - expect(function(){ - corbelDriver.iam.scope().remove(); - }).to.throw('id value is mandatory and cannot be undefined'); - }); - }); - - describe('Groups api interface', function() { - it('Get all groups', function() { - corbelDriver.iam.group().getAll(); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'group'); - expect(callRequestParam.method).to.be.equal('GET'); - }); - - it('Get a group', function() { - var id = 'id'; - - corbelDriver.iam.group(id).get(); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'group/' + id); - expect(callRequestParam.method).to.be.equal('GET'); - }); - - it('Create a group', function() { - var group = { - name: 'name', - scopes: ['scope1', 'scope2'] - }; - - corbelDriver.iam.group().create(group); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'group'); - expect(callRequestParam.method).to.be.equal('POST'); - }); - - it('Add scopes to a group', function() { - var id = 'id'; - - corbelDriver.iam.group(id).addScopes(['scope1']); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'group/' + id + '/scopes'); - expect(callRequestParam.method).to.be.equal('PUT'); - }); - - it('Remove scopes from a group', function() { - var id = 'id'; - var scopeToRemove = 'scope1'; - - corbelDriver.iam.group(id).removeScope(scopeToRemove); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'group/' + id + '/scopes/' + scopeToRemove); - expect(callRequestParam.method).to.be.equal('DELETE'); - }); - - it('Delete a group', function() { - var id = 'id'; - - corbelDriver.iam.group(id).delete(); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'group/' + id); - expect(callRequestParam.method).to.be.equal('DELETE'); - }); - }); -}); +/* globals describe it beforeEach afterEach */ + +var corbel = require('../../../dist/corbel.js') +var chai = require('chai') +var sinon = require('sinon') +var expect = chai.expect + +describe('corbel IAM module', function () { + var sandbox = sinon.sandbox.create() + var CONFIG = { + clientId: 'clientId', + clientSecret: 'clientSecret', + audience: 'audience', + scopes: ['silkroad-qa:client', 'resources:send_event_bus', 'resources:test:test_operations', 'resources:music:read_catalog', 'resources:music:streaming'], + urlBase: 'https://{{module}}-corbel.io/' + } + + var IAM_END_POINT = CONFIG.urlBase.replace('{{module}}', 'iam') + + var corbelDriver = corbel.getDriver(CONFIG) + + var corbelRequestStub + + beforeEach(function () { + corbelRequestStub = sandbox.stub(corbel.request, 'send').returns(Promise.resolve()) + }) + + afterEach(function () { + sandbox.restore() + }) + + describe('Creates accessToken', function () { + it('Using without params', function () { + sandbox.stub(corbel.jwt, '_generateExp').returns(1234) + + var assertion = corbelDriver.iam.token()._getJwt({ + claims: { + exp: 1234 + } + }) + + corbelDriver.iam.token().create() + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'oauth/token') + expect(callRequestParam.method).to.be.equal('POST') + expect(callRequestParam.data.assertion).to.be.equal(assertion) + expect(callRequestParam.data.grant_type).to.be.equal(corbel.Iam.GRANT_TYPE) + }) + + it('Using with empty params', function () { + sandbox.stub(corbel.jwt, '_generateExp').returns(1234) + + var assertion = corbelDriver.iam.token()._getJwt({ + claims: { + exp: 1234 + } + }) + + corbelDriver.iam.token().create({}) + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'oauth/token') + expect(callRequestParam.method).to.be.equal('POST') + expect(callRequestParam.data.assertion).to.be.equal(assertion) + expect(callRequestParam.data.grant_type).to.be.equal(corbel.Iam.GRANT_TYPE) + }) + + describe('mandatory values in config', function () { + it('expects clientSecret to be defined', function () { + var config = { + urlBase: 'http://test.com' + } + var driver = corbel.getDriver(config) + + expect(function () { + driver.iam.token()._getJwt() + }).to.throw('config:undefined:clientSecret') + }) + + it('expects clientId to be defined', function () { + var config = { + urlBase: 'http://test.com', + clientSecret: 'test' + } + var driver = corbel.getDriver(config) + + expect(function () { + driver.iam.token()._getJwt() + }).to.throw('config:undefined:clientId') + }) + + it('passes if all mandatory values are provided', function () { + var config = { + urlBase: 'http://test.com', + clientSecret: 'test', + clientId: 'test' + } + var driver = corbel.getDriver(config) + + expect(function () { + driver.iam.token()._getJwt() + }).not.to.throw(Error) + }) + }) + + it('Using JWT correctly', function () { + var testJwt = '_jwt_' + corbelDriver.iam.token().create({ + jwt: testJwt + }) + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'oauth/token') + expect(callRequestParam.method).to.be.equal('POST') + expect(callRequestParam.data.assertion).to.be.equal(testJwt) + expect(callRequestParam.data.grant_type).to.be.equal(corbel.Iam.GRANT_TYPE) + }) + + it('Using claims correctly', function () { + var testClaims = { + iss: 'clientId', + scope: 'scopes', + aud: 'audience', + exp: 'expireAt', + prn: 'principal' + } + + var assertion = corbel.jwt.generate(testClaims, CONFIG.clientSecret) + + corbelDriver.iam.token().create({ + claims: testClaims + }) + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'oauth/token') + expect(callRequestParam.method).to.be.equal('POST') + expect(callRequestParam.data.assertion).to.be.equal(assertion) + expect(callRequestParam.data.grant_type).to.be.equal(corbel.Iam.GRANT_TYPE) + }) + + it('Getting token with cookie with POST', function () { + var testClaims = { + iss: 'clientId', + scope: 'scopes', + aud: 'audience', + exp: 'expireAt', + prn: 'principal' + } + + corbelDriver.iam.token().create({ + claims: testClaims + }, true) + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'oauth/token') + expect(callRequestParam.headers.RequestCookie).to.be.equal('true') + }) + + it('Getting token with cookie with GET', function () { + var testJwt = '_jwt_' + var testOauth = { + code: '_code_' + } + + corbelDriver.iam.token().create({ + jwt: testJwt, + oauth: testOauth + }, true) + + var callRequestParam = corbel.request.send.firstCall.args[0] + console.log('callRequestParam', callRequestParam) + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'oauth/token') + expect(callRequestParam.headers.RequestCookie).to.be.equal('true') + }) + + it('Using Oauth correctly', function () { + var testJwt = '_jwt_' + var testOauth = { + code: '_code_' + } + + corbelDriver.iam.token().create({ + jwt: testJwt, + oauth: testOauth + }) + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'oauth/token') + expect(callRequestParam.method).to.be.equal('GET') + expect(decodeURIComponent(callRequestParam.query)).to.be.equal('assertion=' + testJwt + '&grant_type=' + corbel.Iam.GRANT_TYPE + '&code=' + testOauth.code) + }) + }) + + describe('Refresh accessToken', function () { + it('Using without refresh token', function () { + expect(corbelDriver.iam.token().refresh).to.throw('Refresh access token request must contains refresh token') + }) + + it('Using refresh token correctly with default scopes', function () { + sandbox.stub(corbel.jwt, '_generateExp').returns(1234) + + corbelDriver.iam.token().refresh('refresh_token') + + var testJwt = corbel.jwt.generate({ + iss: CONFIG.clientId, + aud: CONFIG.audience, + exp: 1234, + scope: CONFIG.scopes, + 'refresh_token': 'refresh_token' + }, CONFIG.clientSecret) + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'oauth/token') + expect(callRequestParam.method).to.be.equal('POST') + expect(callRequestParam.data.assertion).to.be.equal(testJwt) + expect(callRequestParam.data.grant_type).to.be.equal(corbel.Iam.GRANT_TYPE) + }) + + it('Using refresh token correctly with scopes', function () { + sandbox.stub(corbel.jwt, '_generateExp').returns(1234) + + corbelDriver.iam.token().refresh('refresh_token', 'test_scope') + + var claims = { + 'refresh_token': 'refresh_token' + } + claims.scope = 'test_scope' + claims.exp = 1234 + + var testJwt = corbel.jwt.generate({ + iss: CONFIG.clientId, + aud: CONFIG.audience, + exp: 1234, + scope: 'test_scope', + 'refresh_token': 'refresh_token' + }, CONFIG.clientSecret) + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'oauth/token') + expect(callRequestParam.method).to.be.equal('POST') + expect(callRequestParam.data.assertion).to.be.equal(testJwt) + expect(callRequestParam.data.grant_type).to.be.equal(corbel.Iam.GRANT_TYPE) + }) + }) + + describe('usernames availability', function () { + it('get username availability', function () { + var USERNAME = 'test' + corbelDriver.iam.username().availability(USERNAME) + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'username/' + USERNAME) + expect(callRequestParam.method).to.be.equal('HEAD') + }) + + it('get username availability with undefined value', function () { + corbelRequestStub.returns(Promise.resolve('OK')) + expect(function () { + corbelDriver.iam.username().availability() + }).to.throw('username value is mandatory and cannot be undefined') + }) + + it('username available return true', function (done) { + corbelRequestStub.returns(Promise.reject({ + status: 404 + })) + corbelDriver.iam.username().availability('test').then(function (result) { + expect(result).to.be.equal(true) + done() + }) + }) + + it('username not available return false', function (done) { + corbelDriver.iam.username().availability('test').then(function (result) { + expect(result).to.be.equal(false) + done() + }) + }) + + it('on server error reject promise', function (done) { + corbelRequestStub.returns(Promise.reject({ + httpStatus: 500 + })) + corbelDriver.iam.username().availability('test').catch(function () { + done() + }) + }) + }) + + describe('Email availability', function () { + it('Get email availability', function () { + var EMAIL = 'test@test.com' + corbelDriver.iam.email().availability(EMAIL) + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'email/' + EMAIL) + expect(callRequestParam.method).to.be.equal('HEAD') + }) + + it('get email availability with undefined value', function () { + corbelRequestStub.returns(Promise.resolve('OK')) + expect(function () { + corbelDriver.iam.email().availability() + }).to.throw('email value is mandatory and cannot be undefined') + }) + + it('Email available return true', function (done) { + corbelRequestStub.returns(Promise.reject({ + status: 404 + })) + corbelDriver.iam.email().availability('test@domingo.com').then(function (result) { + expect(result).to.be.equal(true) + done() + }) + }) + + it('Email not available return false', function (done) { + corbelDriver.iam.email().availability('test@test.com').then(function (result) { + expect(result).to.be.equal(false) + done() + }) + }) + + it('On server error reject promise', function (done) { + corbelRequestStub.returns(Promise.reject({ + httpStatus: 500 + })) + corbelDriver.iam.email().availability('test').catch(function () { + done() + }) + }) + }) + + describe('Users Management', function () { + it('Create user', function () { + var username = 'username' + corbelDriver.iam.users().create({ + username: username + }) + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user') + expect(callRequestParam.method).to.be.equal('POST') + expect(JSON.stringify(callRequestParam.data)).to.be.equal('{"username":"username"}') + }) + + it('Get all users', function () { + corbelDriver.iam.users().get() + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user') + expect(callRequestParam.method).to.be.equal('GET') + }) + + it('Get user me', function () { + corbelDriver.iam.user('me').get() + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/me') + expect(callRequestParam.method).to.be.equal('GET') + }) + + it('Get user', function () { + corbelDriver.iam.user('userId').get() + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/userId') + expect(callRequestParam.method).to.be.equal('GET') + }) + + it('Update user', function () { + var username = 'username' + + corbelDriver.iam.user('userId').update({ + username: username + }) + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/userId') + expect(callRequestParam.method).to.be.equal('PUT') + expect(JSON.stringify(callRequestParam.data)).to.be.equal('{"username":"username"}') + }) + + it('Update user using me', function () { + var username = 'username' + + corbelDriver.iam.user('me').update({ + username: username + }) + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/me') + expect(callRequestParam.method).to.be.equal('PUT') + expect(JSON.stringify(callRequestParam.data)).to.be.equal('{"username":"username"}') + }) + + it('Update user me', function () { + var username = 'username' + + corbelDriver.iam.user().updateMe({ + username: username + }) + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/me') + expect(callRequestParam.method).to.be.equal('PUT') + expect(JSON.stringify(callRequestParam.data)).to.be.equal('{"username":"username"}') + }) + + it('Delete user', function () { + corbelDriver.iam.user('userId').delete() + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/userId') + expect(callRequestParam.method).to.be.equal('DELETE') + }) + + it('Delete user using me', function () { + corbelDriver.iam.user('me').delete() + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/me') + expect(callRequestParam.method).to.be.equal('DELETE') + }) + + it('Delete user me', function () { + corbelDriver.iam.user().deleteMe() + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/me') + expect(callRequestParam.method).to.be.equal('DELETE') + }) + + it('Sign Out user using me', function () { + corbelDriver.iam.user('me').signOut() + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/me/signout') + expect(callRequestParam.method).to.be.equal('PUT') + }) + + it('Sign Out user me', function () { + corbelDriver.iam.user().signOutMe() + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/me/signout') + expect(callRequestParam.method).to.be.equal('PUT') + }) + + it('Disconnect user', function () { + corbelDriver.iam.user('userId').disconnect() + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/userId/disconnect') + expect(callRequestParam.method).to.be.equal('PUT') + }) + + it('Disconnect user logged', function () { + corbelDriver.iam.user('me').disconnect() + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/me/disconnect') + expect(callRequestParam.method).to.be.equal('PUT') + }) + + it('Disconnect me', function () { + corbelDriver.iam.user().disconnectMe() + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/me/disconnect') + expect(callRequestParam.method).to.be.equal('PUT') + }) + + it('generate sendResetPasswordEmail request correctly', function () { + corbelDriver.iam.users().sendResetPasswordEmail('test@email.com') + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/resetPassword?email=test@email.com') + expect(callRequestParam.method).to.be.equal('GET') + }) + + describe('Adding user identity', function () { + it('with valid identity object', function () { + corbelDriver.iam.user('userId').addIdentity({ + oAuthService: 'silkroad', + oAuthId: '12435' + }) + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/userId/identity') + expect(callRequestParam.method).to.be.equal('POST') + expect(callRequestParam.data.oAuthService).to.be.equal('silkroad') + expect(callRequestParam.data.oAuthId).to.be.equal('12435') + }) + + it('without passing an identity object', function () { + expect(corbelDriver.iam.user('userId').addIdentity).to.throw('Missing identity') + }) + }) + + it('Get user identities', function () { + corbelDriver.iam.user('userId').getIdentities() + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/userId/identity') + expect(callRequestParam.method).to.be.equal('GET') + }) + + it('Get user identities using me', function () { + corbelDriver.iam.user('me').getIdentities() + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/me/identity') + expect(callRequestParam.method).to.be.equal('GET') + }) + + it('Get my identities', function () { + corbelDriver.iam.user().getMyIdentities() + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/me/identity') + expect(callRequestParam.method).to.be.equal('GET') + }) + + it('Get user profile using me', function () { + corbelDriver.iam.user('me').getProfile() + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/me/profile') + expect(callRequestParam.method).to.be.equal('GET') + }) + + it('Get my profile', function () { + corbelDriver.iam.user().getMyProfile() + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/me/profile') + expect(callRequestParam.method).to.be.equal('GET') + }) + + it('Get user profile', function () { + corbelDriver.iam.user('userId').getProfile() + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/userId/profile') + expect(callRequestParam.method).to.be.equal('GET') + }) + + it('Get user profiles', function () { + corbelDriver.iam.users().getProfiles() + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/profile') + expect(callRequestParam.method).to.be.equal('GET') + }) + }) + + describe('User devices', function () { + it('Register my device', function () { + corbelDriver.iam.user().registerMyDevice('Device data') + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/me/devices') + expect(callRequestParam.method).to.be.equal('PUT') + }) + + it('Register device', function () { + corbelDriver.iam.user('userId').registerDevice('Device data') + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/userId/devices') + expect(callRequestParam.method).to.be.equal('PUT') + }) + + it('Register device using me', function () { + corbelDriver.iam.user('me').registerDevice('Device data') + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/me/devices') + expect(callRequestParam.method).to.be.equal('PUT') + }) + + it('Get device id', function () { + corbelDriver.iam.user('userId').getDevice('deviceId') + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/userId/devices/deviceId') + expect(callRequestParam.method).to.be.equal('GET') + }) + + it('Get device id using me', function () { + corbelDriver.iam.user('me').getDevice('deviceId') + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/me/devices/deviceId') + expect(callRequestParam.method).to.be.equal('GET') + }) + + it('Get my device id', function () { + corbelDriver.iam.user().getMyDevice('deviceId') + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/me/devices/deviceId') + expect(callRequestParam.method).to.be.equal('GET') + }) + + it('Get devices', function () { + corbelDriver.iam.user('userId').getDevices() + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/userId/devices/') + expect(callRequestParam.method).to.be.equal('GET') + }) + + it('Get devices using me', function () { + corbelDriver.iam.user('me').getDevices() + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/me/devices/') + expect(callRequestParam.method).to.be.equal('GET') + }) + + it('Get my devices', function () { + corbelDriver.iam.user().getMyDevices() + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/me/devices/') + expect(callRequestParam.method).to.be.equal('GET') + }) + + it('Get my device', function () { + corbelDriver.iam.user('me').getDevice('123') + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/me/devices/123') + expect(callRequestParam.method).to.be.equal('GET') + }) + + it('Delete my device', function () { + corbelDriver.iam.user('me').deleteDevice('deviceId') + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/me/devices/deviceId') + expect(callRequestParam.method).to.be.equal('DELETE') + }) + + it('Delete device', function () { + corbelDriver.iam.user('123').deleteDevice('deviceId') + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/123/devices/deviceId') + expect(callRequestParam.method).to.be.equal('DELETE') + }) + }) + + describe('User groups', function () { + it('Add groups to user', function () { + var groups = ['g1', 'g2'] + + corbelDriver.iam.user('userId').addGroups(groups) + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/userId/groups') + expect(callRequestParam.method).to.be.equal('PUT') + }) + + it('delete group to user', function () { + corbelDriver.iam.user('userId').deleteGroup('g1') + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/userId/groups/g1') + expect(callRequestParam.method).to.be.equal('DELETE') + }) + + it('delete group my group using me', function () { + corbelDriver.iam.user('me').deleteGroup('g1') + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/me/groups/g1') + expect(callRequestParam.method).to.be.equal('DELETE') + }) + + it('delete my group', function () { + corbelDriver.iam.user().deleteMyGroup('g1') + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'user/me/groups/g1') + expect(callRequestParam.method).to.be.equal('DELETE') + }) + }) + + describe('Domain admin interface', function () { + var data = { + id: 'jklasdfjklasdf', + domain: 'wenuirasdj' + } + + it('Create a new domain', function () { + corbelDriver.iam.domain().create(data).then(function (id) { + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'domain') + expect(callRequestParam.method).to.be.equal('POST') + expect(data.id).to.be.equal(id) + }) + }) + + it('get a domain with undefined value', function () { + corbelRequestStub.returns(Promise.resolve('OK')) + expect(function () { + corbelDriver.iam.domain().get() + }).to.throw('domainId value is mandatory and cannot be undefined') + }) + + it('Gets a domain', function () { + corbelDriver.iam.domain(data.id).get() + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'domain/' + data.id) + expect(callRequestParam.method).to.be.equal('GET') + }) + + it('Gets all domains', function () { + corbelDriver.iam.domain().getAll() + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'domain') + expect(callRequestParam.method).to.be.equal('GET') + }) + + it('Update a domain', function () { + corbelDriver.iam.domain(data.id).update(data) + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'domain/' + data.id) + expect(callRequestParam.method).to.be.equal('PUT') + }) + + it('update a domain with undefined value', function () { + corbelRequestStub.returns(Promise.resolve('OK')) + expect(function () { + corbelDriver.iam.domain().update({}) + }).to.throw('domainId value is mandatory and cannot be undefined') + }) + + it('Remove a domain', function () { + var domainId = 'sjdfkls' + corbelDriver.iam.domain(domainId).remove() + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'domain/' + domainId) + expect(callRequestParam.method).to.be.equal('DELETE') + }) + + it('remove a domain with undefined value', function () { + corbelRequestStub.returns(Promise.resolve('OK')) + expect(function () { + corbelDriver.iam.domain().remove() + }).to.throw('domainId value is mandatory and cannot be undefined') + }) + + it('Create a new client', function () { + corbelDriver.iam.client(data.domain).create(data).then(function (id) { + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'domain/' + data.domain + '/client') + expect(callRequestParam.method).to.be.equal('POST') + expect(data.id).to.be.equal(id) + }) + }) + + it('Create a new client with undefined domainId', function () { + corbelRequestStub.returns(Promise.resolve('OK')) + expect(function () { + corbelDriver.iam.client(undefined, 'clientId').create({}) + }).to.throw('domainId value is mandatory and cannot be undefined') + }) + + it('Get a client', function () { + corbelDriver.iam.client(data.domain, data.id).get() + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'domain/' + data.domain + '/client/' + data.id) + expect(callRequestParam.method).to.be.equal('GET') + }) + + it('get a client with undefined clientId', function () { + corbelRequestStub.returns(Promise.resolve('OK')) + expect(function () { + corbelDriver.iam.client(data.domain, undefined).get() + }).to.throw('clientId value is mandatory and cannot be undefined') + }) + + it('get a client with undefined domainId', function () { + corbelRequestStub.returns(Promise.resolve('OK')) + expect(function () { + corbelDriver.iam.client(undefined, 'clientId').get() + }).to.throw('domainId value is mandatory and cannot be undefined') + }) + + it('Get all clients in a domain', function () { + corbelDriver.iam.client(data.domain).getAll() + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'domain/' + data.domain + '/client') + expect(callRequestParam.method).to.be.equal('GET') + }) + + it('Update a client', function () { + corbelDriver.iam.client(data.domain, data.id).update(data) + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'domain/' + data.domain + '/client/' + data.id) + expect(callRequestParam.method).to.be.equal('PUT') + }) + + it('update a new client with undefined domainId', function () { + corbelRequestStub.returns(Promise.resolve('OK')) + expect(function () { + corbelDriver.iam.client(undefined, 'clientId').update({}) + }).to.throw('domainId value is mandatory and cannot be undefined') + }) + + it('update a new client with undefined domainId', function () { + corbelRequestStub.returns(Promise.resolve('OK')) + expect(function () { + corbelDriver.iam.client('domainId', undefined).update({}) + }).to.throw('clientId value is mandatory and cannot be undefined') + }) + + it('Remove a client', function () { + corbelDriver.iam.client(data.domain, data.id).remove() + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'domain/' + data.domain + '/client/' + data.id) + expect(callRequestParam.method).to.be.equal('DELETE') + }) + + it('remove a new client with undefined domainId', function () { + corbelRequestStub.returns(Promise.resolve('OK')) + expect(function () { + corbelDriver.iam.client(undefined, 'clientId').remove({}) + }).to.throw('domainId value is mandatory and cannot be undefined') + }) + + it('remove a new client with undefined domainId', function () { + corbelRequestStub.returns(Promise.resolve('OK')) + expect(function () { + corbelDriver.iam.client('domainId', undefined).remove({}) + }).to.throw('clientId value is mandatory and cannot be undefined') + }) + }) + + describe('Scope admin interface', function () { + it('Create a new scope', function () { + var scope = { + id: 'jklsdfbnwerj' + } + + corbelDriver.iam.scope().create(scope).then(function (id) { + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'scope') + expect(callRequestParam.method).to.be.equal('POST') + expect(scope.id).to.be.equal(id) + }) + }) + + it('Get a scope', function () { + var scopeId = 'jklsdfbnwerj' + + corbelDriver.iam.scope(scopeId).get() + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'scope/' + scopeId) + expect(callRequestParam.method).to.be.equal('GET') + }) + + it('get a scope with undefined value', function () { + corbelRequestStub.returns(Promise.resolve('OK')) + expect(function () { + corbelDriver.iam.scope().get() + }).to.throw('id value is mandatory and cannot be undefined') + }) + + it('Remove a scope', function () { + var scopeId = 'jklsdfbnwerj' + + corbelDriver.iam.scope(scopeId).remove() + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'scope/' + scopeId) + expect(callRequestParam.method).to.be.equal('DELETE') + }) + + it('remove a scope with undefined value', function () { + corbelRequestStub.returns(Promise.resolve('OK')) + expect(function () { + corbelDriver.iam.scope().remove() + }).to.throw('id value is mandatory and cannot be undefined') + }) + }) + + describe('Groups api interface', function () { + it('Get all groups', function () { + corbelDriver.iam.group().getAll() + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'group') + expect(callRequestParam.method).to.be.equal('GET') + }) + + it('Get a group', function () { + var id = 'id' + + corbelDriver.iam.group(id).get() + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'group/' + id) + expect(callRequestParam.method).to.be.equal('GET') + }) + + it('Create a group', function () { + var group = { + name: 'name', + scopes: ['scope1', 'scope2'] + } + + corbelDriver.iam.group().create(group) + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'group') + expect(callRequestParam.method).to.be.equal('POST') + }) + + it('Add scopes to a group', function () { + var id = 'id' + + corbelDriver.iam.group(id).addScopes(['scope1']) + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'group/' + id + '/scopes') + expect(callRequestParam.method).to.be.equal('PUT') + }) + + it('Remove scopes from a group', function () { + var id = 'id' + var scopeToRemove = 'scope1' + + corbelDriver.iam.group(id).removeScope(scopeToRemove) + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'group/' + id + '/scopes/' + scopeToRemove) + expect(callRequestParam.method).to.be.equal('DELETE') + }) + + it('Delete a group', function () { + var id = 'id' + + corbelDriver.iam.group(id).delete() + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(IAM_END_POINT + 'group/' + id) + expect(callRequestParam.method).to.be.equal('DELETE') + }) + }) +}) diff --git a/test/node/unit/jwt.js b/test/node/unit/jwt.js index 5cf8d20..5fa86f0 100644 --- a/test/node/unit/jwt.js +++ b/test/node/unit/jwt.js @@ -1,105 +1,97 @@ -'use strict'; +'use strict' +/* globals describe it */ -var corbel = require('../../../dist/corbel.js'), - chai = require('chai'), - expect = chai.expect; +var corbel = require('../../../dist/corbel.js') +var chai = require('chai') +var expect = chai.expect -describe('JWT module', function() { +describe('JWT module', function () { + var CLIENT_ID = 'CLIENT_ID' + var SCOPES = 'scope1 scope2' - var CLIENT_ID = 'CLIENT_ID'; - var SCOPES = 'scope1 scope2'; + it('exists and is an object', function () { + expect(corbel.jwt).to.be.an('object') + }) - it('exists and is an object', function() { - expect(corbel.jwt).to.be.an('object'); - }); - - it('has all namespace properties', function() { + it('has all namespace properties', function () { expect(corbel.jwt).to.include.keys( 'generate' - ); - }); - - it('generates a valid JWT', function() { - var secret = 'secret', - claims = { - 'iss': CLIENT_ID, - 'aud': 'http://iam.bqws.io', - 'exp': 1391535, - 'scope': SCOPES, - 'version': '1.0.0' - }; - var EXPECTED_ASSERTION = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJDTElFTlRfSUQiLCJhdWQiOiJodHRwOi8vaWFtLmJxd3MuaW8iLCJleHAiOjEzOTE1MzUsInNjb3BlIjoic2NvcGUxIHNjb3BlMiIsInZlcnNpb24iOiIxLjAuMCJ9._TCKYb3gbsuznfwA1gopY4mSYr7VHmvFQGxW1CJJjHQ'; + ) + }) + + it('generates a valid JWT', function () { + var secret = 'secret' + var claims = { + 'iss': CLIENT_ID, + 'aud': 'http://iam.bqws.io', + 'exp': 1391535, + 'scope': SCOPES, + 'version': '1.0.0' + } + var EXPECTED_ASSERTION = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJDTElFTlRfSUQiLCJhdWQiOiJodHRwOi8vaWFtLmJxd3MuaW8iLCJleHAiOjEzOTE1MzUsInNjb3BlIjoic2NvcGUxIHNjb3BlMiIsInZlcnNpb24iOiIxLjAuMCJ9._TCKYb3gbsuznfwA1gopY4mSYr7VHmvFQGxW1CJJjHQ' // without alg - var assertion = corbel.jwt.generate(claims, secret); - expect(assertion).to.be.equal(EXPECTED_ASSERTION); + var assertion = corbel.jwt.generate(claims, secret) + expect(assertion).to.be.equal(EXPECTED_ASSERTION) // with alg - assertion = corbel.jwt.generate(claims, secret, 'HS256'); - expect(assertion).to.be.equal(EXPECTED_ASSERTION); + assertion = corbel.jwt.generate(claims, secret, 'HS256') + expect(assertion).to.be.equal(EXPECTED_ASSERTION) // with array scopes - claims.scope = ['scope1', 'scope2']; - assertion = corbel.jwt.generate(claims, secret); - expect(assertion).to.be.equal(EXPECTED_ASSERTION); - }); + claims.scope = ['scope1', 'scope2'] + assertion = corbel.jwt.generate(claims, secret) + expect(assertion).to.be.equal(EXPECTED_ASSERTION) + }) - it('decodes expected values', function() { - var secret = 'secret', - claims = { - iss: 'clientId', - aud: 'http://iam.bqws.io', - exp: 12345, - scope: 'scope:example1 scope:example2' - }; + it('decodes expected values', function () { + var secret = 'secret' + var claims = { + iss: 'clientId', + aud: 'http://iam.bqws.io', + exp: 12345, + scope: 'scope:example1 scope:example2' + } - var EXPECTED = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJjbGllbnRJZCIsImF1ZCI6Imh0dHA6Ly9pYW0uYnF3cy5pbyIsImV4cCI6MTIzNDUsInNjb3BlIjoic2NvcGU6ZXhhbXBsZTEgc2NvcGU6ZXhhbXBsZTIifQ.18g9YO_KgWtW1s7HSo87mIjG02u8Pe880tdLbg_JxC4'; + var EXPECTED = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJjbGllbnRJZCIsImF1ZCI6Imh0dHA6Ly9pYW0uYnF3cy5pbyIsImV4cCI6MTIzNDUsInNjb3BlIjoic2NvcGU6ZXhhbXBsZTEgc2NvcGU6ZXhhbXBsZTIifQ.18g9YO_KgWtW1s7HSo87mIjG02u8Pe880tdLbg_JxC4' - var assertion = corbel.jwt.generate(claims, secret); - expect(assertion).to.be.equal(EXPECTED); + var assertion = corbel.jwt.generate(claims, secret) + expect(assertion).to.be.equal(EXPECTED) // with array scopes - claims.scope = ['scope:example1', 'scope:example2']; - assertion = corbel.jwt.generate(claims, secret); - var jwtDecoded = corbel.jwt.decode(assertion); - expect(jwtDecoded).to.be.an('object'); - - expect(jwtDecoded.typ).to.be.equal('JWT'); - expect(jwtDecoded.alg).to.be.equal('HS256'); - - expect(jwtDecoded.iss).to.be.equal('clientId'); - expect(jwtDecoded.aud).to.be.equal('http://iam.bqws.io'); - expect(jwtDecoded.exp).to.be.equal(12345); - expect(jwtDecoded.scope).to.be.equal('scope:example1 scope:example2'); - }); - - it('throws exception with invalid assertion', function() { - expect(function() { - corbel.jwt.decode('invalid_assertion'); - }).to.throw('corbel:jwt:decode:invalid_assertion'); - }); - - describe('when generating claims', function() { - - it('iss are required', function() { - - expect(function() { - corbel.jwt.generate(); - }).to.throw('jwt:undefined:iss'); - - }); - - it('aud are required', function() { - - expect(function() { + claims.scope = ['scope:example1', 'scope:example2'] + assertion = corbel.jwt.generate(claims, secret) + var jwtDecoded = corbel.jwt.decode(assertion) + expect(jwtDecoded).to.be.an('object') + + expect(jwtDecoded.typ).to.be.equal('JWT') + expect(jwtDecoded.alg).to.be.equal('HS256') + + expect(jwtDecoded.iss).to.be.equal('clientId') + expect(jwtDecoded.aud).to.be.equal('http://iam.bqws.io') + expect(jwtDecoded.exp).to.be.equal(12345) + expect(jwtDecoded.scope).to.be.equal('scope:example1 scope:example2') + }) + + it('throws exception with invalid assertion', function () { + expect(function () { + corbel.jwt.decode('invalid_assertion') + }).to.throw('corbel:jwt:decode:invalid_assertion') + }) + + describe('when generating claims', function () { + it('iss are required', function () { + expect(function () { + corbel.jwt.generate() + }).to.throw('jwt:undefined:iss') + }) + + it('aud are required', function () { + expect(function () { corbel.jwt.generate({ iss: 'myiss' - }); - }).to.throw('jwt:undefined:aud'); - - }); - - - }); - -}); + }) + }).to.throw('jwt:undefined:aud') + }) + }) +}) diff --git a/test/node/unit/notifications.js b/test/node/unit/notifications.js index da1ea29..1459de8 100644 --- a/test/node/unit/notifications.js +++ b/test/node/unit/notifications.js @@ -1,134 +1,133 @@ -'use strict'; +'use strict' /* jshint camelcase:false */ - -var corbel = require('../../../dist/corbel.js'), - chai = require('chai'), - sinon = require('sinon'), - expect = chai.expect; - -describe('In Notifications module we can', function() { - - var sandbox = sinon.sandbox.create(); - - var CONFIG = { - - clientId: 'clientId', - clientSecret: 'clientSecret', - - scopes: ['silkroad-qa:client', 'resources:send_event_bus', 'resources:test:test_operations', 'resources:music:read_catalog', 'resources:music:streaming'], - - urlBase: 'https://{{module}}-corbel.io/' - - }; - - var NOTIFICATION_URL = CONFIG.urlBase.replace('{{module}}', 'notifications') + 'notification'; - - var corbelRequestStub; - - var corbelDriver = corbel.getDriver(CONFIG); - - beforeEach(function() { - corbelRequestStub = sandbox.stub(corbel.request, 'send'); - }); - - afterEach(function() { - sandbox.restore(); - }); - - it('create notification', function() { - corbelRequestStub.returns(Promise.resolve()); - var notificationData = '{\'id\':\'OAuth:mail:resetPass\',\'type\':\'mail\', }'; - corbelDriver.notifications.notification().create(notificationData); - - var paramsRecived = corbelRequestStub.getCall(0).args[0]; - expect(paramsRecived.url).to.be.equal(NOTIFICATION_URL); - expect(paramsRecived.method).to.be.equal('POST'); - expect(paramsRecived.data).to.be.equal(notificationData); - }); - - it('get notification', function() { - corbelRequestStub.returns(Promise.resolve('OK')); - var idNotification = 1; - - corbelDriver.notifications.notification(idNotification).get(); - - var paramsRecived = corbelRequestStub.getCall(0).args[0]; - expect(paramsRecived.url).to.be.equal(NOTIFICATION_URL +'/1'); - expect(paramsRecived.method).to.be.equal('GET'); - }); - - it('get all with params', function() { - corbelRequestStub.returns(Promise.resolve('OK')); - var params = { - query: [{ - '$eq': { - type: 'mail' - } - }], - page: { - size: 2, - page: 3 - }, - sort: { - field: 'asc' - } - }; - - corbelDriver.notifications.notification().get(params); - - var paramsRecived = corbelRequestStub.getCall(0).args[0]; - var url = paramsRecived.url.split('?'); - expect(url).to.be.include(NOTIFICATION_URL); - expect(url).to.be.include('api:query=' + encodeURIComponent('[{"$eq":{"type":"mail"}}]') + '&api:sort=' + encodeURIComponent('{"field":"asc"}')); - expect(paramsRecived.method).to.be.equal('GET'); - }); - - it('update notification', function() { - corbelRequestStub.returns(Promise.resolve('OK')); - var idNotification = 1; - var notificationData = '{\'id\':\'OAuth:mail:resetPass\',\'type\':\'mail\', }'; - - corbelDriver.notifications.notification(idNotification).update(notificationData); - - var paramsRecived = corbelRequestStub.getCall(0).args[0]; - expect(paramsRecived.url).to.be.equal(NOTIFICATION_URL +'/1'); - expect(paramsRecived.method).to.be.equal('PUT'); - expect(paramsRecived.data).to.be.equal(notificationData); - }); - - it('update notification without an id', function() { - corbelRequestStub.returns(Promise.resolve('OK')); - expect(function(){ - corbelDriver.notifications.notification().update({}); - }).to.throw('id value is mandatory and cannot be undefined'); - }); - - it('delete notification', function() { - corbelRequestStub.returns(Promise.resolve('OK')); - var idNotification = 1; - - corbelDriver.notifications.notification(idNotification).delete(); - - var paramsRecived = corbelRequestStub.getCall(0).args[0]; - expect(paramsRecived.url).to.be.equal(NOTIFICATION_URL +'/1'); - expect(paramsRecived.method).to.be.equal('DELETE'); - }); - - it('delete notification without an id', function() { - corbelRequestStub.returns(Promise.resolve('OK')); - expect(function(){ - corbelDriver.notifications.notification().delete(); - }).to.throw('id value is mandatory and cannot be undefined'); - }); - - it('send notification', function() { - corbelRequestStub.returns(Promise.resolve()); - var notificationData = '{\'id\':\'OAuth:mail:resetPass\',\'type\':\'mail\', }'; - corbelDriver.notifications.notification().sendNotification(notificationData); - - var paramsRecived = corbelRequestStub.getCall(0).args[0]; - expect(paramsRecived.url).to.be.equal(NOTIFICATION_URL + '/send'); - expect(paramsRecived.method).to.be.equal('POST'); - expect(paramsRecived.data).to.be.equal(notificationData); - }); -}); +/* globals describe it beforeEach afterEach */ + +var corbel = require('../../../dist/corbel.js') +var chai = require('chai') +var sinon = require('sinon') +var expect = chai.expect + +describe('In Notifications module we can', function () { + var sandbox = sinon.sandbox.create() + + var CONFIG = { + clientId: 'clientId', + clientSecret: 'clientSecret', + + scopes: ['silkroad-qa:client', 'resources:send_event_bus', 'resources:test:test_operations', 'resources:music:read_catalog', 'resources:music:streaming'], + + urlBase: 'https://{{module}}-corbel.io/' + + } + + var NOTIFICATION_URL = CONFIG.urlBase.replace('{{module}}', 'notifications') + 'notification' + + var corbelRequestStub + + var corbelDriver = corbel.getDriver(CONFIG) + + beforeEach(function () { + corbelRequestStub = sandbox.stub(corbel.request, 'send') + }) + + afterEach(function () { + sandbox.restore() + }) + + it('create notification', function () { + corbelRequestStub.returns(Promise.resolve()) + var notificationData = "{'id':'OAuth:mail:resetPass','type':'mail', }" + corbelDriver.notifications.notification().create(notificationData) + + var paramsRecived = corbelRequestStub.getCall(0).args[0] + expect(paramsRecived.url).to.be.equal(NOTIFICATION_URL) + expect(paramsRecived.method).to.be.equal('POST') + expect(paramsRecived.data).to.be.equal(notificationData) + }) + + it('get notification', function () { + corbelRequestStub.returns(Promise.resolve('OK')) + var idNotification = 1 + + corbelDriver.notifications.notification(idNotification).get() + + var paramsRecived = corbelRequestStub.getCall(0).args[0] + expect(paramsRecived.url).to.be.equal(NOTIFICATION_URL + '/1') + expect(paramsRecived.method).to.be.equal('GET') + }) + + it('get all with params', function () { + corbelRequestStub.returns(Promise.resolve('OK')) + var params = { + query: [{ + '$eq': { + type: 'mail' + } + }], + page: { + size: 2, + page: 3 + }, + sort: { + field: 'asc' + } + } + + corbelDriver.notifications.notification().get(params) + + var paramsRecived = corbelRequestStub.getCall(0).args[0] + var url = paramsRecived.url.split('?') + expect(url).to.be.include(NOTIFICATION_URL) + expect(url).to.be.include('api:query=' + encodeURIComponent('[{"$eq":{"type":"mail"}}]') + '&api:sort=' + encodeURIComponent('{"field":"asc"}')) + expect(paramsRecived.method).to.be.equal('GET') + }) + + it('update notification', function () { + corbelRequestStub.returns(Promise.resolve('OK')) + var idNotification = 1 + var notificationData = "{'id':'OAuth:mail:resetPass','type':'mail', }" + + corbelDriver.notifications.notification(idNotification).update(notificationData) + + var paramsRecived = corbelRequestStub.getCall(0).args[0] + expect(paramsRecived.url).to.be.equal(NOTIFICATION_URL + '/1') + expect(paramsRecived.method).to.be.equal('PUT') + expect(paramsRecived.data).to.be.equal(notificationData) + }) + + it('update notification without an id', function () { + corbelRequestStub.returns(Promise.resolve('OK')) + expect(function () { + corbelDriver.notifications.notification().update({}) + }).to.throw('id value is mandatory and cannot be undefined') + }) + + it('delete notification', function () { + corbelRequestStub.returns(Promise.resolve('OK')) + var idNotification = 1 + + corbelDriver.notifications.notification(idNotification).delete() + + var paramsRecived = corbelRequestStub.getCall(0).args[0] + expect(paramsRecived.url).to.be.equal(NOTIFICATION_URL + '/1') + expect(paramsRecived.method).to.be.equal('DELETE') + }) + + it('delete notification without an id', function () { + corbelRequestStub.returns(Promise.resolve('OK')) + expect(function () { + corbelDriver.notifications.notification().delete() + }).to.throw('id value is mandatory and cannot be undefined') + }) + + it('send notification', function () { + corbelRequestStub.returns(Promise.resolve()) + var notificationData = "{'id':'OAuth:mail:resetPass','type':'mail', }" + corbelDriver.notifications.notification().sendNotification(notificationData) + + var paramsRecived = corbelRequestStub.getCall(0).args[0] + expect(paramsRecived.url).to.be.equal(NOTIFICATION_URL + '/send') + expect(paramsRecived.method).to.be.equal('POST') + expect(paramsRecived.data).to.be.equal(notificationData) + }) +}) diff --git a/test/node/unit/oauth.js b/test/node/unit/oauth.js index 313fc50..cf262e2 100644 --- a/test/node/unit/oauth.js +++ b/test/node/unit/oauth.js @@ -1,327 +1,303 @@ -'use strict'; +'use strict' /* jshint camelcase:false */ - -var corbel = require('../../../dist/corbel.js'), - chai = require('chai'), - sinon = require('sinon'), - expect = chai.expect; - -describe('In OAUTH module', function() { - - var sandbox = sinon.sandbox.create(), - corbelDriver, - oauth; - - var CONFIG = { - - clientId: 'clientId', - clientSecret: 'clientSecret', - scopes: ['silkroad-qa:client', 'resources:send_event_bus', 'resources:test:test_operations', 'resources:music:read_catalog', 'resources:music:streaming'], - urlBase: 'https://{{module}}-corbel.io/' - }; - - var OAUTH_URL = CONFIG.urlBase.replace('{{module}}', 'oauth'); - - before(function() { - corbelDriver = corbel.getDriver(CONFIG); - oauth = corbelDriver.oauth; - }); - - beforeEach(function() { - sandbox.stub(corbel.request, 'send').returns(Promise.resolve()); - }); - - afterEach(function() { - sandbox.restore(); - }); - - describe('with authorization endpoint,', function() { - it('do login request correctly', function() { - var clientParams = { - clientId: 'testClient', - redirectUri: 'redirectUri', - responseType: 'code' - }; - - oauth.authorization(clientParams).login('testUser', 'testPassword'); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(OAUTH_URL + 'oauth/authorize'); - expect(callRequestParam.method).to.be.equal('POST'); - var response = callRequestParam.data; - expect(response).to.have.a.property('username', 'testUser'); - expect(response).to.have.a.property('password', 'testPassword'); - }); - - it('do the login with cookie request correctly', function() { - var clientParams = { - clientId: 'testClient', - redirectUri: 'redirectUri', - responseType: 'code' - }; - - oauth.authorization(clientParams).loginWithCookie(); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(OAUTH_URL + 'oauth/authorize'); - expect(callRequestParam.method).to.be.equal('GET'); - var response = callRequestParam.data; - expect(response.contentType).to.be.equal(corbel.Oauth._URL_ENCODED); - expect(response.data).to.have.a.property('client_id', 'testClient'); - expect(response.data).to.have.a.property('response_type', 'code'); - expect(response.data).to.have.a.property('redirect_uri', 'redirectUri'); - }); - - it('do not allow a response type disctint to "code"', function() { - var clientParams = { - clientId: 'testClient', - redirectUri: 'redirectUri', - responseType: 'other' - }; - - expect(oauth.authorization.bind(corbelDriver.oauth.authorization, clientParams)).to. - throw('Only "code" or "token" response type allowed'); - }); - - it('fails with missing params', function() { - - expect(oauth.authorization).to. - throw('Invalid client parameters'); - }); - - it('fails with incomplete params', function() { - var clientParams = { - clientId: 'testClient' - }; - - expect(oauth.authorization.bind(corbelDriver.oauth.authorization, clientParams)).to. - throw('Invalid client parameters'); - }); - }); - - describe('with signOut endpoint,', function() { - - it('does the sign out request correctly', function() { - var clientParams = { - clientId: 'testClient', - redirectUri: 'redirectUri', - responseType: 'code' - }; - - oauth.authorization(clientParams).signout(); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(OAUTH_URL + 'oauth/signout'); - expect(callRequestParam.method).to.be.equal('GET'); - }); - }); - - describe('with token endpoint', function() { - it('generate token request correctly', function() { - var clientParams = { - clientId: 'testClient', - redirectUri: 'redirectUri', - clientSecret: 'testClientSecret', - grantType: 'authorization_code' - }; - - oauth.token(clientParams).get('testCode'); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - - expect(callRequestParam.url).to.be.equal(OAUTH_URL + 'oauth/token'); - expect(callRequestParam.method).to.be.equal('POST'); - var response = callRequestParam.data; - expect(response.contentType).to.be.equal(corbel.Oauth._URL_ENCODED); - expect(response.data).to.have.a.property('client_id', 'testClient'); - expect(response.data).to.have.a.property('client_secret', 'testClientSecret'); - expect(response.data).to.have.a.property('redirect_uri', 'redirectUri'); - expect(response.data).to.have.a.property('code', 'testCode'); - expect(response.data).to.have.a.property('grant_type', 'authorization_code'); - }); - - it('do not allow a grant type disctint to "authorization_code"', function() { - var clientParams = { - clientId: 'testClient', - redirectUri: 'redirectUri', - clientSecret: 'testClientSecret', - grantType: 'other' - }; - expect(oauth.token.bind(corbelDriver.oauth.token, clientParams)).to. - throw('Only "authorization_code" grant type is allowed'); - }); - - it('fails with missing params', function() { - expect(oauth.token).to. - throw('Invalid client parameters'); - }); - - it('fails with incomplete params', function() { - expect(oauth.token.bind(corbelDriver.oauth.token, undefined)).to. - throw('Invalid client parameters'); - }); - }); - - describe('with user endpoint', function() { - var clientParams = { - clientId: 'testClient', - clientSecret: 'testClientSecret' - }; - - it('generate create user request correctly', function() { - - oauth.user(clientParams).create({ - user: 'user' - }); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - - expect(callRequestParam.url).to.be.equal(OAUTH_URL + 'user'); - expect(callRequestParam.method).to.be.equal('POST'); - var response = callRequestParam.data; - expect(response).to.have.a.property('user', 'user'); - expect(callRequestParam.headers.Authorization).to.be.equal('Basic dGVzdENsaWVudDp0ZXN0Q2xpZW50U2VjcmV0'); - }); - - it('generate user me request correctly', function() { - - oauth.user(clientParams, 'testToken').get('me'); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(OAUTH_URL + 'user/me'); - expect(callRequestParam.method).to.be.equal('GET'); - // expect(callRequestParam.accessToken).to.have.a.property('accessToken', 'testToken'); - }); - - it('generate user request correctly', function() { - - oauth.user(clientParams, 'testToken').get('userId'); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(OAUTH_URL + 'user/userId'); - expect(callRequestParam.method).to.be.equal('GET'); - //expect(callRequestParam.accessToken).to.have.a.property('accessToken', 'testToken'); - }); - - it('generate get user profile request correctly', function() { - - oauth.user(clientParams, 'testToken').getProfile('userId'); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(OAUTH_URL + 'user/userId/profile'); - expect(callRequestParam.method).to.be.equal('GET'); - //expect(callRequestParam.accessToken).to.have.a.property('accessToken', 'testToken'); - }); - - it('generate get user profile me request correctly', function() { - - oauth.user(clientParams, 'testToken').getProfile('me'); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(OAUTH_URL + 'user/me/profile'); - expect(callRequestParam.method).to.be.equal('GET'); - //expect(callRequestParam.accessToken).to.have.a.property('accessToken', 'testToken'); - }); - - it('generate update me request correctly', function() { - - oauth.user(clientParams, 'testToken').update('me', { - fieldUpdate: 'update' - }); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(OAUTH_URL + 'user/me'); - expect(callRequestParam.method).to.be.equal('PUT'); - //expect(callRequestParam.accessToken).to.be.equal('testToken'); - var response = callRequestParam.data; - expect(response).to.have.a.property('fieldUpdate', 'update'); - }); - - it('generate update request correctly', function() { - - oauth.user(clientParams, 'testToken').update('userId', { - fieldUpdate: 'update' - }); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(OAUTH_URL + 'user/userId'); - expect(callRequestParam.method).to.be.equal('PUT'); - //expect(callRequestParam.accessToken).to.be.equal('testToken'); - var response = callRequestParam.data; - expect(response).to.have.a.property('fieldUpdate', 'update'); - }); - - it('generate delete me request correctly', function() { - - oauth.user(clientParams, 'testToken').delete('me'); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(OAUTH_URL + 'user/me'); - expect(callRequestParam.method).to.be.equal('DELETE'); - // expect(callRequestParam.accessToken).to.be.equal('testToken'); - }); - - it('generate delete request correctly', function() { - - oauth.user(clientParams, 'testToken').delete('userId'); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(OAUTH_URL + 'user/userId'); - expect(callRequestParam.method).to.be.equal('DELETE'); - // expect(callRequestParam.accessToken).to.be.equal('testToken'); - }); - - it('generate send reset password email request correctly', function() { - - oauth.user(clientParams).sendResetPasswordEmail('test@email.com'); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - var spplitedResponse = callRequestParam.url.split('?'); - //expect(spplitedResponse).to.be.equal(USER_OAUTH_URL + '/resetPassword?email=test@email.com'); - expect(callRequestParam.method).to.be.equal('GET'); - expect(spplitedResponse).to.include('email=test@email.com'); - expect(spplitedResponse).to.include(OAUTH_URL + 'user/resetPassword'); - - }); - - it('generate send me validate email request correctly', function() { - - oauth.user(clientParams, 'testToken').sendValidateEmail('me'); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(OAUTH_URL + 'user/me/validate'); - expect(callRequestParam.method).to.be.equal('GET'); - // expect(callRequestParam.accessToken).to.be.equal('testToken'); - }); - - it('generate send validate email request correctly', function() { - - oauth.user(clientParams, 'testToken').sendValidateEmail('userId'); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(OAUTH_URL + 'user/userId/validate'); - expect(callRequestParam.method).to.be.equal('GET'); - //expect(callRequestParam.accessToken).to.be.equal('testToken'); - }); - - it('generate email me confirmation request correctly', function() { - - oauth.user(clientParams, 'oneAccessTestToken').emailConfirmation('me'); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(OAUTH_URL + 'user/me/emailConfirmation'); - expect(callRequestParam.method).to.be.equal('PUT'); - //expect(callRequestParam.accessToken).to.be.equal('oneAccessTestToken'); - }); - - it('generate email confirmation request correctly', function() { - - oauth.user(clientParams, 'oneAccessTestToken').emailConfirmation('userId'); - - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(OAUTH_URL + 'user/userId/emailConfirmation'); - expect(callRequestParam.method).to.be.equal('PUT'); - //expect(callRequestParam.accessToken).to.be.equal('oneAccessTestToken'); - }); - }); -}); +/* globals describe it before beforeEach afterEach */ + +var corbel = require('../../../dist/corbel.js') +var chai = require('chai') +var sinon = require('sinon') +var expect = chai.expect + +describe('In OAUTH module', function () { + var sandbox = sinon.sandbox.create() + var corbelDriver + var oauth + + var CONFIG = { + clientId: 'clientId', + clientSecret: 'clientSecret', + scopes: ['silkroad-qa:client', 'resources:send_event_bus', 'resources:test:test_operations', 'resources:music:read_catalog', 'resources:music:streaming'], + urlBase: 'https://{{module}}-corbel.io/' + } + + var OAUTH_URL = CONFIG.urlBase.replace('{{module}}', 'oauth') + + before(function () { + corbelDriver = corbel.getDriver(CONFIG) + oauth = corbelDriver.oauth + }) + + beforeEach(function () { + sandbox.stub(corbel.request, 'send').returns(Promise.resolve()) + }) + + afterEach(function () { + sandbox.restore() + }) + + describe('with authorization endpoint,', function () { + it('do login request correctly', function () { + var clientParams = { + clientId: 'testClient', + redirectUri: 'redirectUri', + responseType: 'code' + } + + oauth.authorization(clientParams).login('testUser', 'testPassword') + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(OAUTH_URL + 'oauth/authorize') + expect(callRequestParam.method).to.be.equal('POST') + var response = callRequestParam.data + expect(response).to.have.a.property('username', 'testUser') + expect(response).to.have.a.property('password', 'testPassword') + }) + + it('do the login with cookie request correctly', function () { + var clientParams = { + clientId: 'testClient', + redirectUri: 'redirectUri', + responseType: 'code' + } + + oauth.authorization(clientParams).loginWithCookie() + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(OAUTH_URL + 'oauth/authorize') + expect(callRequestParam.method).to.be.equal('GET') + var response = callRequestParam.data + expect(response.contentType).to.be.equal(corbel.Oauth._URL_ENCODED) + expect(response.data).to.have.a.property('client_id', 'testClient') + expect(response.data).to.have.a.property('response_type', 'code') + expect(response.data).to.have.a.property('redirect_uri', 'redirectUri') + }) + + it('do not allow a response type disctint to "code"', function () { + var clientParams = { + clientId: 'testClient', + redirectUri: 'redirectUri', + responseType: 'other' + } + + expect(oauth.authorization.bind(corbelDriver.oauth.authorization, clientParams)).to.throw('Only "code" or "token" response type allowed') + }) + + it('fails with missing params', function () { + expect(oauth.authorization).to.throw('Invalid client parameters') + }) + + it('fails with incomplete params', function () { + var clientParams = { + clientId: 'testClient' + } + + expect(oauth.authorization.bind(corbelDriver.oauth.authorization, clientParams)).to.throw('Invalid client parameters') + }) + }) + + describe('with signOut endpoint,', function () { + it('does the sign out request correctly', function () { + var clientParams = { + clientId: 'testClient', + redirectUri: 'redirectUri', + responseType: 'code' + } + + oauth.authorization(clientParams).signout() + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(OAUTH_URL + 'oauth/signout') + expect(callRequestParam.method).to.be.equal('GET') + }) + }) + + describe('with token endpoint', function () { + it('generate token request correctly', function () { + var clientParams = { + clientId: 'testClient', + redirectUri: 'redirectUri', + clientSecret: 'testClientSecret', + grantType: 'authorization_code' + } + + oauth.token(clientParams).get('testCode') + + var callRequestParam = corbel.request.send.firstCall.args[0] + + expect(callRequestParam.url).to.be.equal(OAUTH_URL + 'oauth/token') + expect(callRequestParam.method).to.be.equal('POST') + var response = callRequestParam.data + expect(response.contentType).to.be.equal(corbel.Oauth._URL_ENCODED) + expect(response.data).to.have.a.property('client_id', 'testClient') + expect(response.data).to.have.a.property('client_secret', 'testClientSecret') + expect(response.data).to.have.a.property('redirect_uri', 'redirectUri') + expect(response.data).to.have.a.property('code', 'testCode') + expect(response.data).to.have.a.property('grant_type', 'authorization_code') + }) + + it('do not allow a grant type disctint to "authorization_code"', function () { + var clientParams = { + clientId: 'testClient', + redirectUri: 'redirectUri', + clientSecret: 'testClientSecret', + grantType: 'other' + } + expect(oauth.token.bind(corbelDriver.oauth.token, clientParams)).to.throw('Only "authorization_code" grant type is allowed') + }) + + it('fails with missing params', function () { + expect(oauth.token).to.throw('Invalid client parameters') + }) + + it('fails with incomplete params', function () { + expect(oauth.token.bind(corbelDriver.oauth.token, undefined)).to.throw('Invalid client parameters') + }) + }) + + describe('with user endpoint', function () { + var clientParams = { + clientId: 'testClient', + clientSecret: 'testClientSecret' + } + + it('generate create user request correctly', function () { + oauth.user(clientParams).create({ + user: 'user' + }) + + var callRequestParam = corbel.request.send.firstCall.args[0] + + expect(callRequestParam.url).to.be.equal(OAUTH_URL + 'user') + expect(callRequestParam.method).to.be.equal('POST') + var response = callRequestParam.data + expect(response).to.have.a.property('user', 'user') + expect(callRequestParam.headers.Authorization).to.be.equal('Basic dGVzdENsaWVudDp0ZXN0Q2xpZW50U2VjcmV0') + }) + + it('generate user me request correctly', function () { + oauth.user(clientParams, 'testToken').get('me') + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(OAUTH_URL + 'user/me') + expect(callRequestParam.method).to.be.equal('GET') + // expect(callRequestParam.accessToken).to.have.a.property('accessToken', 'testToken') + }) + + it('generate user request correctly', function () { + oauth.user(clientParams, 'testToken').get('userId') + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(OAUTH_URL + 'user/userId') + expect(callRequestParam.method).to.be.equal('GET') + // expect(callRequestParam.accessToken).to.have.a.property('accessToken', 'testToken') + }) + + it('generate get user profile request correctly', function () { + oauth.user(clientParams, 'testToken').getProfile('userId') + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(OAUTH_URL + 'user/userId/profile') + expect(callRequestParam.method).to.be.equal('GET') + // expect(callRequestParam.accessToken).to.have.a.property('accessToken', 'testToken') + }) + + it('generate get user profile me request correctly', function () { + oauth.user(clientParams, 'testToken').getProfile('me') + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(OAUTH_URL + 'user/me/profile') + expect(callRequestParam.method).to.be.equal('GET') + // expect(callRequestParam.accessToken).to.have.a.property('accessToken', 'testToken') + }) + + it('generate update me request correctly', function () { + oauth.user(clientParams, 'testToken').update('me', { + fieldUpdate: 'update' + }) + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(OAUTH_URL + 'user/me') + expect(callRequestParam.method).to.be.equal('PUT') + // expect(callRequestParam.accessToken).to.be.equal('testToken') + var response = callRequestParam.data + expect(response).to.have.a.property('fieldUpdate', 'update') + }) + + it('generate update request correctly', function () { + oauth.user(clientParams, 'testToken').update('userId', { + fieldUpdate: 'update' + }) + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(OAUTH_URL + 'user/userId') + expect(callRequestParam.method).to.be.equal('PUT') + // expect(callRequestParam.accessToken).to.be.equal('testToken') + var response = callRequestParam.data + expect(response).to.have.a.property('fieldUpdate', 'update') + }) + + it('generate delete me request correctly', function () { + oauth.user(clientParams, 'testToken').delete('me') + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(OAUTH_URL + 'user/me') + expect(callRequestParam.method).to.be.equal('DELETE') + // expect(callRequestParam.accessToken).to.be.equal('testToken') + }) + + it('generate delete request correctly', function () { + oauth.user(clientParams, 'testToken').delete('userId') + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(OAUTH_URL + 'user/userId') + expect(callRequestParam.method).to.be.equal('DELETE') + // expect(callRequestParam.accessToken).to.be.equal('testToken') + }) + + it('generate send reset password email request correctly', function () { + oauth.user(clientParams).sendResetPasswordEmail('test@email.com') + + var callRequestParam = corbel.request.send.firstCall.args[0] + var spplitedResponse = callRequestParam.url.split('?') + // expect(spplitedResponse).to.be.equal(USER_OAUTH_URL + '/resetPassword?email=test@email.com') + expect(callRequestParam.method).to.be.equal('GET') + expect(spplitedResponse).to.include('email=test@email.com') + expect(spplitedResponse).to.include(OAUTH_URL + 'user/resetPassword') + }) + + it('generate send me validate email request correctly', function () { + oauth.user(clientParams, 'testToken').sendValidateEmail('me') + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(OAUTH_URL + 'user/me/validate') + expect(callRequestParam.method).to.be.equal('GET') + // expect(callRequestParam.accessToken).to.be.equal('testToken') + }) + + it('generate send validate email request correctly', function () { + oauth.user(clientParams, 'testToken').sendValidateEmail('userId') + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(OAUTH_URL + 'user/userId/validate') + expect(callRequestParam.method).to.be.equal('GET') + // expect(callRequestParam.accessToken).to.be.equal('testToken') + }) + + it('generate email me confirmation request correctly', function () { + oauth.user(clientParams, 'oneAccessTestToken').emailConfirmation('me') + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(OAUTH_URL + 'user/me/emailConfirmation') + expect(callRequestParam.method).to.be.equal('PUT') + // expect(callRequestParam.accessToken).to.be.equal('oneAccessTestToken') + }) + + it('generate email confirmation request correctly', function () { + oauth.user(clientParams, 'oneAccessTestToken').emailConfirmation('userId') + + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(OAUTH_URL + 'user/userId/emailConfirmation') + expect(callRequestParam.method).to.be.equal('PUT') + // expect(callRequestParam.accessToken).to.be.equal('oneAccessTestToken') + }) + }) +}) diff --git a/test/node/unit/request.js b/test/node/unit/request.js index 41933b1..a9e9884 100644 --- a/test/node/unit/request.js +++ b/test/node/unit/request.js @@ -1,318 +1,310 @@ -'use strict'; +'use strict' +/* globals describe it before beforeEach afterEach */ -var corbel = require('../../../dist/corbel.js'), - chai = require('chai'), - expect = chai.expect, - sinon = require('sinon'), - stream = require('stream'); +var corbel = require('../../../dist/corbel.js') +var chai = require('chai') +var expect = chai.expect +var sinon = require('sinon') +var stream = require('stream') -describe('corbel-js node', function() { +describe('corbel-js node', function () { + var sandbox - var sandbox; + this.timeout(20000) - this.timeout(20000); + beforeEach(function () { + sandbox = sinon.sandbox.create() + }) - beforeEach(function() { - sandbox = sinon.sandbox.create(); - }); + afterEach(function () { + sandbox.restore() + }) - afterEach(function() { - sandbox.restore(); - }); + it('corbel-js contains all modules', function () { + expect(corbel).to.include.keys('request') + }) - it('corbel-js contains all modules', function() { - expect(corbel).to.include.keys('request'); - }); + describe('request module', function () { + var url = 'http://localhost:3000/' + var request - describe('request module', function() { + before(function () { + request = corbel.request + }) - var url = 'http://localhost:3000/', - request; + it('should has own properties', function () { + expect(request).to.include.keys('method') + expect(request.method).to.include.keys('GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'PATCH', 'HEAD') + }) - before(function() { - request = corbel.request; - }); - - it('should has own properties', function() { - expect(request).to.include.keys('method'); - expect(request.method).to.include.keys('GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'PATCH', 'HEAD'); - }); - - it('expected methods are available', function() { - expect(request).to.respondTo('send'); - }); - - ['GET', 'POST', 'PATCH', 'PUT', 'HEAD'].forEach(function(verb) { - it('send method accepts http ' + verb + ' verb', function(done) { + it('expected methods are available', function () { + expect(request).to.respondTo('send') + }) + ;['GET', 'POST', 'PATCH', 'PUT', 'HEAD'].forEach(function (verb) { + it('send method accepts http ' + verb + ' verb', function (done) { var promise = request.send({ method: verb, url: url - }); - - expect(promise).to.be.fulfilled.and.should.notify(done); - - }); - }); + }) - it('send method throws an error if no url setting', function() { + expect(promise).to.be.fulfilled.and.should.notify(done) + }) + }) - var fn = function() { + it('send method throws an error if no url setting', function () { + var fn = function () { return request.send({ method: 'GET' - }); - }; - - expect(fn).to.throw('undefined:url'); - }); + }) + } - it('send method returns a promise', function() { + expect(fn).to.throw('undefined:url') + }) + it('send method returns a promise', function () { var promise = request.send({ method: 'GET', url: url - }); + }) - expect(promise).to.be.instanceof(Promise); - }); + expect(promise).to.be.instanceof(Promise) + }) - it('send method returns a promise and it resolves', function(done) { + it('send method returns a promise and it resolves', function (done) { expect(request.send({ method: 'GET', url: url })) - .to.be.fulfilled.and.should.notify(done); - }); + .to.be.fulfilled.and.should.notify(done) + }) - it('send method returns a promise and reject it', function(done) { + it('send method returns a promise and reject it', function (done) { var promise = request.send({ method: 'GET', url: url + '404' - }); - - expect(promise).to.be.rejected - .then(function(error) { - expect(error.status).to.be.equal(404); }) - .should.notify(done); - }); + expect(promise).to.be.rejected + .then(function (error) { + expect(error.status).to.be.equal(404) + }) + .should.notify(done) + }) - it('send method accepts a success callback', function(done) { + it('send method accepts a success callback', function (done) { request.send({ method: 'GET', url: url, - success: function() { - done(); - }, - error: function(error) { - done(error); + success: function () { + done() }, - }); - }); + error: function (error) { + done(error) + } + }) + }) - it('success callback expect responseText, status , incoming message object', function(done) { + it('success callback expect responseText, status , incoming message object', function (done) { request.send({ method: 'GET', url: url, - success: function(data, status, httpResponse) { - expect(data).to.be.a('object'); - expect(status).to.be.a('number'); - expect(httpResponse).to.be.an('object'); - done(); + success: function (data, status, httpResponse) { + expect(data).to.be.a('object') + expect(status).to.be.a('number') + expect(httpResponse).to.be.an('object') + done() } - }); - }); + }) + }) - it('send method accepts an error callback', function(done) { + it('send method accepts an error callback', function (done) { request.send({ method: 'GET', url: url + '404', - error: function(data, status) { - expect(status).to.be.equal(404); - done(); + error: function (data, status) { + expect(status).to.be.equal(404) + done() } - }); - }); - - it('send method encodes url parameters', function(done) { - var _nodeAjaxStub = sandbox.stub(request, '_nodeAjax', function(params, resolver) { - resolver.resolve(); - }); - var queryArgs = 'param1=1¶m2=2¶m3=3&combine=3+4'; - var parsedQueryArgs = encodeURI(queryArgs); - //@TODO: the '+' character should be encoded?? I think yes. - //parsedQueryArgs = parsedQueryArgs.replace('+', encodeURIComponent('+')); - url += '?'; + }) + }) + + it('send method encodes url parameters', function (done) { + var _nodeAjaxStub = sandbox.stub(request, '_nodeAjax', function (params, resolver) { + resolver.resolve() + }) + var queryArgs = 'param1=1¶m2=2¶m3=3&combine=3+4' + var parsedQueryArgs = encodeURI(queryArgs) + // @TODO: the '+' character should be encoded?? I think yes. + // parsedQueryArgs = parsedQueryArgs.replace('+', encodeURIComponent('+')) + url += '?' expect(request.send({ method: 'GET', url: url + queryArgs - })).to.be.fulfilled.then(function() { - expect(_nodeAjaxStub.callCount).to.be.equal(1); - expect(_nodeAjaxStub.getCall(0).args[0].url).to.be.equal(url + parsedQueryArgs); - }).should.notify(done); - }); - - it('send method sends a String as application/octet-stream', function(done) { - var _nodeAjaxStub = sandbox.stub(request, '_nodeAjax', function(params, resolver) { - resolver.resolve(); - }); - var testText = 'Test'; - - request.send({ - method: 'POST', - url: url, - contentType : 'application/octet-stream', - data: testText + })).to.be.fulfilled.then(function () { + expect(_nodeAjaxStub.callCount).to.be.equal(1) + expect(_nodeAjaxStub.getCall(0).args[0].url).to.be.equal(url + parsedQueryArgs) + }).should.notify(done) + }) + + it('send method sends a String as application/octet-stream', function (done) { + var _nodeAjaxStub = sandbox.stub(request, '_nodeAjax', function (params, resolver) { + resolver.resolve() + }) + var testText = 'Test' + + request.send({ + method: 'POST', + url: url, + contentType: 'application/octet-stream', + data: testText + }) + .should.be.eventually.fulfilled + .then(function () { + expect(typeof (_nodeAjaxStub.getCall(0).args[0].data)).to.be.equal('string') + expect(_nodeAjaxStub.getCall(0).args[0].data).to.be.equal(testText) }) + .should.notify(done) + }) + + it('send method sends a stream as application/octet-stream', function (done) { + var requestStream + var requestMockedFunction = function (options, callback) { + requestStream = new stream.Transform() + requestStream._transform = function (chunk, encoding, done) { + done() + callback() + } + return requestStream + } + var getNodeRequestAjaxStub = sandbox.stub(request, '_getNodeRequestAjax').returns(requestMockedFunction) + var getNodeRequestCallback = sandbox.stub(request, '_getNodeRequestCallback', function (context, params, resolver) { + return function () { + resolver.resolve() + } + }) + + var streamToSend = new stream.Readable() + streamToSend.push('Test Stream') + streamToSend.push(null) + var pipeSpy = sandbox.spy(streamToSend, 'pipe') + + request.send({ + method: 'POST', + url: url, + contentType: 'application/octet-stream', + data: streamToSend + }) .should.be.eventually.fulfilled - .then(function() { - expect(typeof(_nodeAjaxStub.getCall(0).args[0].data)).to.be.equal('string'); - expect(_nodeAjaxStub.getCall(0).args[0].data).to.be.equal(testText); + .then(function () { + expect(pipeSpy.callCount).to.equals(1) + expect(pipeSpy.calledWith(requestStream)).to.equals(true) + expect(getNodeRequestAjaxStub.callCount).to.equals(1) + expect(getNodeRequestCallback.callCount).to.equals(1) }) - .should.notify(done); - }); - - it('send method sends a stream as application/octet-stream', function(done) { - var requestStream; - var requestMockedFunction = function(options, callback){ - requestStream = new stream.Transform(); - requestStream._transform = function(chunk, encoding, done){ - done(); - callback(); - }; - return requestStream; - }; - var getNodeRequestAjaxStub = sandbox.stub(request, '_getNodeRequestAjax').returns(requestMockedFunction); - var getNodeRequestCallback = sandbox.stub(request, '_getNodeRequestCallback', function(context, params, resolver){ - return function(){ - resolver.resolve(); - }; - }); - - var streamToSend = new stream.Readable(); - streamToSend.push('Test Stream'); - streamToSend.push(null); - var pipeSpy = sandbox.spy(streamToSend, 'pipe'); - - request.send({ - method: 'POST', - url: url, - contentType : 'application/octet-stream', - data: streamToSend + .should.notify(done) + }) + + it('send method sends a byteArray as application/octet-stream', function (done) { + var _nodeAjaxStub = sandbox.stub(request, '_nodeAjax', function (params, resolver) { + resolver.resolve() + }) + var testText = 'Test' + var byteText = [] + for (var i = 0; i < testText.length; i++) { + byteText.push(testText.charCodeAt(i)) + } + + request.send({ + method: 'POST', + url: url, + contentType: 'application/octet-stream', + data: byteText + }) + .should.be.eventually.fulfilled + .then(function () { + var dataSended = _nodeAjaxStub.getCall(0).args[0].data + + byteText.forEach(function (element, index) { + expect(dataSended[index]).to.be.equal(element) + }) + expect(typeof (_nodeAjaxStub.getCall(0).args[0].data)).to.be.equal('object') }) + .should.notify(done) + }) + + it('send method sends an Uint8Array as application/octet-stream', function (done) { + var _nodeAjaxStub = sandbox.stub(request, '_nodeAjax', function (params, resolver) { + resolver.resolve() + }) + var testText = 'Test' + var ui8arr = new Uint8Array(testText.length) + for (var i = 0; i < testText.length; i++) { + ui8arr[i] = testText.charCodeAt(i) + } + + request.send({ + method: 'POST', + url: url, + contentType: 'application/octet-stream', + data: ui8arr + }) .should.be.eventually.fulfilled - .then(function() { - expect(pipeSpy.callCount).to.equals(1); - expect(pipeSpy.calledWith(requestStream)).to.equals(true); - expect(getNodeRequestAjaxStub.callCount).to.equals(1); - expect(getNodeRequestCallback.callCount).to.equals(1); + .then(function () { + var dataSended = _nodeAjaxStub.getCall(0).args[0].data + for (var key in dataSended) { + if (dataSended.hasOwnProperty(key)) { + expect(dataSended[key]).to.be.equal(ui8arr[key]) + } + } + expect(typeof (_nodeAjaxStub.getCall(0).args[0].data)).to.be.equal('object') }) - .should.notify(done); - }); - - it('send method sends a byteArray as application/octet-stream', function(done) { - var _nodeAjaxStub = sandbox.stub(request, '_nodeAjax', function(params, resolver) { - resolver.resolve(); - }); - var testText = 'Test'; - var byteText = []; - for(var i = 0; i < testText.length; i++){ - byteText.push(testText.charCodeAt(i)); - } - + .should.notify(done) + }) + + it('send method throws an error if try to send an ArrayBuffer as application/octet-stream', function () { + var testText = 'Test' + var buffer = new ArrayBuffer(testText.length) + + expect(function () { request.send({ method: 'POST', url: url, - contentType : 'application/octet-stream', - data: byteText + contentType: 'application/octet-stream', + data: buffer }) - .should.be.eventually.fulfilled - .then(function() { - var dataSended = _nodeAjaxStub.getCall(0).args[0].data; + }).to.throw('ArrayBuffer is not supported, please use Blob, File, Stream or ArrayBufferView') + }) - byteText.forEach(function(element, index) { - expect(dataSended[index]).to.be.equal(element); - }); - expect(typeof(_nodeAjaxStub.getCall(0).args[0].data)).to.be.equal('object'); - }) - .should.notify(done); - }); - - it('send method sends an Uint8Array as application/octet-stream', function(done) { - var _nodeAjaxStub = sandbox.stub(request, '_nodeAjax', function(params, resolver) { - resolver.resolve(); - }); - var testText = 'Test'; - var ui8arr = new Uint8Array(testText.length); - for(var i = 0; i < testText.length; i++){ - ui8arr[i] = testText.charCodeAt(i); - } - + it('send method throws an error if try to send an ArrayBuffer as application/blob', function () { + var testText = 'Test' + var buffer = new ArrayBuffer(testText.length) + + expect(function () { request.send({ method: 'POST', url: url, - contentType : 'application/octet-stream', - data: ui8arr - }) - .should.be.eventually.fulfilled - .then(function() { - var dataSended = _nodeAjaxStub.getCall(0).args[0].data; - for(var key in dataSended ) { - if (dataSended.hasOwnProperty(key)) { - expect(dataSended[key]).to.be.equal(ui8arr[key]); - } - } - expect(typeof(_nodeAjaxStub.getCall(0).args[0].data)).to.be.equal('object'); + contentType: 'application/blob', + data: buffer }) - .should.notify(done); - }); - - it('send method throws an error if try to send an ArrayBuffer as application/octet-stream', function() { - var testText = 'Test'; - var buffer = new ArrayBuffer(testText.length); - - expect(function() { - request.send({ - method: 'POST', - url: url, - contentType : 'application/octet-stream', - data: buffer - }); - }).to.throw('ArrayBuffer is not supported, please use Blob, File, Stream or ArrayBufferView'); - }); - - it('send method throws an error if try to send an ArrayBuffer as application/blob', function() { - var testText = 'Test'; - var buffer = new ArrayBuffer(testText.length); - - expect(function() { - request.send({ - method: 'POST', - url: url, - contentType : 'application/blob', - data: buffer - }); - }).to.throw('ArrayBuffer is not supported, please use Blob'); - }); - - it('throws an event if a driver is sent', function(done) { - var driver = corbel.getDriver({ 'urlBase' : 'demo' }); - var stub = sandbox.stub(); - driver.on('request', stub); + }).to.throw('ArrayBuffer is not supported, please use Blob') + }) - request - .send({ - method: 'GET', - url: url - }, driver) - .then(function(){ - expect(stub.callCount).to.equals(1); - }) - .should.notify(done); - }); + it('throws an event if a driver is sent', function (done) { + var driver = corbel.getDriver({ 'urlBase': 'demo' }) + var stub = sandbox.stub() + driver.on('request', stub) - }); - -}); + request + .send({ + method: 'GET', + url: url + }, driver) + .then(function () { + expect(stub.callCount).to.equals(1) + }) + .should.notify(done) + }) + }) +}) diff --git a/test/node/unit/resources-request-params.js b/test/node/unit/resources-request-params.js index 541c651..2568d61 100644 --- a/test/node/unit/resources-request-params.js +++ b/test/node/unit/resources-request-params.js @@ -1,385 +1,367 @@ -/*jshint newcap: false */ -'use strict'; +/* jshint newcap: false */ +'use strict' +/* globals describe it before after beforeEach afterEach */ -var corbel = require('../../../dist/corbel.js'), - chai = require('chai'), - sinon = require('sinon'), - expect = chai.expect; +var corbel = require('../../../dist/corbel.js') +var chai = require('chai') +var sinon = require('sinon') +var expect = chai.expect var REQUEST_PARAMS_METHODS = [ - 'page', - 'pageSize', - 'pageParam', - 'asc', - 'desc', - 'count', - 'like', - 'eq', - 'gt', - 'gte', - 'lt', - 'lte', - 'ne', - 'like', - 'in', - 'all', - 'elemMatch', - 'setQueryDomain', - 'addCriteria' -]; + 'page', + 'pageSize', + 'pageParam', + 'asc', + 'desc', + 'count', + 'like', + 'eq', + 'gt', + 'gte', + 'lt', + 'lte', + 'ne', + 'like', + 'in', + 'all', + 'elemMatch', + 'setQueryDomain', + 'addCriteria' +] var CONFIG = { - clientId: 'clientId', - clientSecret: 'clientSecret', - scopes: 'scopes', - - urlBase: 'https://{{module}}-qa.bqws.io/v1.0/' -}; - -describe('corbel resources request-params module', function() { - - var sandbox = sinon.sandbox.create(), - corbelDriver, - resources; - - before(function() { - corbelDriver = corbel.getDriver(CONFIG); - resources = corbelDriver.resources; - }); + clientId: 'clientId', + clientSecret: 'clientSecret', + scopes: 'scopes', + + urlBase: 'https://{{module}}-qa.bqws.io/v1.0/' +} + +describe('corbel resources request-params module', function () { + var sandbox = sinon.sandbox.create() + var corbelDriver + var resources + + before(function () { + corbelDriver = corbel.getDriver(CONFIG) + resources = corbelDriver.resources + }) + + after(function () {}) + + beforeEach(function () { + sandbox.stub(corbel.request, 'send').returns(Promise.resolve()) + }) + + afterEach(function () { + sandbox.restore() + }) + + it('collection has all request_params methods', function () { + for (var i = 0; i < REQUEST_PARAMS_METHODS.length; i++) { + expect(resources.collection('resource:entity')).respondTo(REQUEST_PARAMS_METHODS[i]) + } + }) + + it('relation has all request_params methods', function () { + for (var i = 0; i < REQUEST_PARAMS_METHODS.length; i++) { + expect(resources.relation('resource:entity', '', '')).respondTo(REQUEST_PARAMS_METHODS[i]) + } + }) + + it('resource has all request_params methods', function () { + for (var i = 0; i < REQUEST_PARAMS_METHODS.length; i++) { + expect(resources.resource('resource:entity', 'resource:id')).respondTo(REQUEST_PARAMS_METHODS[i]) + } + }) + + describe('for collections', function () { + var collection + var serviceSpy + + beforeEach(function () { + collection = resources.collection('resource:entities') + serviceSpy = sandbox.stub(corbel.Services.prototype, '_buildParams') + }) + + it('supports aggregations', function () { + collection.get({ + dataType: 'application/json', + aggregation: { + $count: 5 + } + }) - after(function() {}); + expect(serviceSpy.firstCall.args[0].query).to.be.equal(corbel.utils.serializeParams({ + aggregation: { + $count: 5 + } + })) + }) + + it('supports sort', function () { + collection.get({ + dataType: 'application/json', + sort: { + 'field': corbel.Resources.sort.ASC + } + }) - beforeEach(function() { - sandbox.stub(corbel.request, 'send').returns(Promise.resolve()); - }); + expect(serviceSpy.firstCall.args[0].query).to.be.equal(corbel.utils.serializeParams({ + sort: { + 'field': corbel.Resources.sort.ASC + } + })) + }) + + it('supports querys', function () { + collection.get({ + query: [{ + '$like': { + name: 'test-name' + } + }] + }) + + expect(serviceSpy.firstCall.args[0].query).to.be.equal(corbel.utils.serializeParams({ + query: [{ + '$like': { + name: 'test-name' + } + }] + })) + }) + + it('supports querys with accents', function () { + collection.get({ + query: [{ + '$like': { + name: 'test-nàmé' + } + }] + }) + + expect(serviceSpy.firstCall.args[0].query).to.be.equal(corbel.utils.serializeParams({ + query: [{ + '$like': { + name: 'test-nàmé' + } + }] + })) + }) + + it('support all chain request params methods', function () { + collection.page(1) + .pageParam(5, 10) + .in('name', 'test') + .elemMatch('name', 'test') + .ne('name', 'test') + .lte('name', 'test') + .lt('name', 'test') + .gte('name', 'test') + .all('name', 'test') + .eq('name', 'test') + .gt('name', 'test') + .like('name', 'test') + .desc('field') + .get({ + dataType: 'application/json' + }) + }) + + it('can chain for a request', function () { + collection.page(1).pageSize(7).like('name', 'test').asc('field').get({ + dataType: 'application/json' + }) + + expect(serviceSpy.firstCall.args[0].query).to.be.equal(corbel.utils.serializeParams({ + pagination: { + page: 1, + pageSize: 7 + }, + query: [{ + '$like': { + 'name': 'test' + } + }], + sort: { + field: corbel.Resources.sort.ASC + } + })) + }) - afterEach(function() { - sandbox.restore(); - }); + it('can chain an aggregation for a request', function () { + collection.count('*').get({ + dataType: 'application/json' + }) - it('collection has all request_params methods', function() { - for (var i = 0; i < REQUEST_PARAMS_METHODS.length; i++) { - expect(resources.collection('resource:entity')).respondTo(REQUEST_PARAMS_METHODS[i]); + expect(serviceSpy.firstCall.args[0].query).to.be.equal(corbel.utils.serializeParams({ + aggregation: { + '$count': '*' } - }); - - it('relation has all request_params methods', function() { - for (var i = 0; i < REQUEST_PARAMS_METHODS.length; i++) { - expect(resources.relation('resource:entity','','')).respondTo(REQUEST_PARAMS_METHODS[i]); + })) + }) + + it('can chain for a request with custom parameters on get call', function () { + collection.page(1).pageSize(7).like('name', 'test').desc('field').get({ + dataType: 'application/json', + pagination: { + page: 2, + pageSize: 7 + }, + sort: { + field: corbel.Resources.sort.ASC + } + }) + + expect(serviceSpy.firstCall.args[0].query).to.be.equal(corbel.utils.serializeParams({ + pagination: { + page: 2, + pageSize: 7 + }, + query: [{ + '$like': { + 'name': 'test' + } + }], + sort: { + field: corbel.Resources.sort.ASC + } + })) + }) + }) + + describe('for relations', function () { + var relation, + serviceSpy + + beforeEach(function () { + relation = resources.relation('resource:entities', '25', '26') + serviceSpy = sandbox.stub(corbel.Services.prototype, '_buildParams') + }) + + it('supports aggregations', function () { + relation.get(5, { + aggregation: { + $count: 5 } - }); + }) - it('resource has all request_params methods', function() { - for (var i = 0; i < REQUEST_PARAMS_METHODS.length; i++) { - expect(resources.resource('resource:entity', 'resource:id')).respondTo(REQUEST_PARAMS_METHODS[i]); + expect(serviceSpy.firstCall.args[0].query).to.be.equal(corbel.utils.serializeParams({ + aggregation: { + $count: 5 } - }); - - describe('for collections', function() { - - var collection, resource, - serviceSpy; - - beforeEach(function() { - collection = resources.collection('resource:entities'); - resource = resources.collection('resource:entities'); - serviceSpy = sandbox.stub(corbel.Services.prototype, '_buildParams'); - }); - - it('supports aggregations', function() { - collection.get({ - dataType: 'application/json', - aggregation: { - $count: 5 - } - }); - - expect(serviceSpy.firstCall.args[0].query).to.be.equal(corbel.utils.serializeParams({ - aggregation: { - $count: 5 - } - })); - - }); - - it('supports sort', function() { - collection.get({ - dataType: 'application/json', - sort: { - 'field': corbel.Resources.sort.ASC - } - }); - - expect(serviceSpy.firstCall.args[0].query).to.be.equal(corbel.utils.serializeParams({ - sort: { - 'field': corbel.Resources.sort.ASC - } - })); - - }); - - it('supports querys', function() { - collection.get({ - query: [{ - '$like': { - name: 'test-name' - } - }] - }); - - expect(serviceSpy.firstCall.args[0].query).to.be.equal(corbel.utils.serializeParams({ - query: [{ - '$like': { - name: 'test-name' - } - }] - })); - - }); - - it('supports querys with accents', function() { - collection.get({ - query: [{ - '$like': { - name: 'test-nàmé' - } - }] - }); - - expect(serviceSpy.firstCall.args[0].query).to.be.equal(corbel.utils.serializeParams({ - query: [{ - '$like': { - name: 'test-nàmé' - } - }] - })); - - }); - - it('support all chain request params methods', function() { - collection.page(1) - .pageParam(5, 10) - .in('name', 'test') - .elemMatch('name', 'test') - .ne('name', 'test') - .lte('name', 'test') - .lt('name', 'test') - .gte('name', 'test') - .all('name', 'test') - .eq('name', 'test') - .gt('name', 'test') - .like('name', 'test') - .desc('field') - .get({ - dataType: 'application/json' - }); - }); - - it('can chain for a request', function() { - collection.page(1).pageSize(7).like('name', 'test').asc('field').get({ - dataType: 'application/json' - }); - - expect(serviceSpy.firstCall.args[0].query).to.be.equal(corbel.utils.serializeParams({ - pagination: { - page: 1, - pageSize: 7 - }, - query: [{ - '$like': { - 'name': 'test' - } - }], - sort: { - field: corbel.Resources.sort.ASC - } - })); - }); - - it('can chain an aggregation for a request', function() { - collection.count('*').get({ - dataType: 'application/json' - }); - - expect(serviceSpy.firstCall.args[0].query).to.be.equal(corbel.utils.serializeParams({ - aggregation: { - '$count': '*' - } - })); - }); - - it('can chain for a request with custom parameters on get call', function() { - collection.page(1).pageSize(7).like('name', 'test').desc('field').get({ - dataType: 'application/json', - pagination: { - page: 2, - pageSize: 7 - }, - sort: { - field: corbel.Resources.sort.ASC - } - }); - - expect(serviceSpy.firstCall.args[0].query).to.be.equal(corbel.utils.serializeParams({ - pagination: { - page: 2, - pageSize: 7 - }, - query: [{ - '$like': { - 'name': 'test' - } - }], - sort: { - field: corbel.Resources.sort.ASC - } - })); - - }); - - }); - - describe('for relations', function() { - var relation, - serviceSpy; - - beforeEach(function() { - relation = resources.relation('resource:entities', '25', '26'); - serviceSpy = sandbox.stub(corbel.Services.prototype, '_buildParams'); - }); - - it('supports aggregations', function() { - relation.get(5, { - aggregation: { - $count: 5 - } - }); - - expect(serviceSpy.firstCall.args[0].query).to.be.equal(corbel.utils.serializeParams({ - aggregation: { - $count: 5 - } - })); - - }); - - it('supports querys', function() { - relation.get(5, { - query: [{ - '$like': { - name: 'test-name' - } - }] - }); - - expect(serviceSpy.firstCall.args[0].query).to.be.equal(corbel.utils.serializeParams({ - query: [{ - '$like': { - name: 'test-name' - } - }] - })); - - }); - - it('can chain for a request', function() { - relation.like('name', 'test').get(5, { - dataType: 'application/json' - }); - - expect(serviceSpy.firstCall.args[0].query).to.be.equal(corbel.utils.serializeParams({ - query: [{ - '$like': { - 'name': 'test' - } - }] - })); - - }); - - it('can chain for a request with custom parameters on get call', function() { - relation.like('name', 'test').get(5, { - query: [{ - $like: { - name: 'otro' - } - }] - }); - - expect(serviceSpy.firstCall.args[0].query).to.be.equal(corbel.utils.serializeParams({ - query: [{ - $like: { - name: 'otro' - } - }] - })); - - }); - - }); - - describe('for resources', function() { - var resource, - serviceSpy; - - beforeEach(function() { - resource = resources.resource('resource:entities', '25', '26'); - serviceSpy = sandbox.stub(corbel.Services.prototype, '_buildParams'); - }); - - it('supports querys', function() { - resource.get({ - query: [{ - '$like': { - name: 'test-name' - } - }] - }); - - expect(serviceSpy.firstCall.args[0].query).to.be.equal(corbel.utils.serializeParams({ - query: [{ - '$like': { - name: 'test-name' - } - }] - })); - - }); - - it('can chain for a request', function() { - resource.like('name', 'test').get({ - dataType: 'application/json' - }); - - expect(serviceSpy.firstCall.args[0].query).to.be.equal(corbel.utils.serializeParams({ - query: [{ - '$like': { - 'name': 'test' - } - }] - })); - - }); - - it('can chain for a request with custom parameters on get call', function() { - resource.like('name', 'test').get({ - query: [{ - $like: { - name: 'otro' - } - }] - }); - - expect(serviceSpy.firstCall.args[0].query).to.be.equal(corbel.utils.serializeParams({ - query: [{ - $like: { - name: 'otro' - } - }] - })); - - }); - - }); - -}); + })) + }) + + it('supports querys', function () { + relation.get(5, { + query: [{ + '$like': { + name: 'test-name' + } + }] + }) + + expect(serviceSpy.firstCall.args[0].query).to.be.equal(corbel.utils.serializeParams({ + query: [{ + '$like': { + name: 'test-name' + } + }] + })) + }) + + it('can chain for a request', function () { + relation.like('name', 'test').get(5, { + dataType: 'application/json' + }) + + expect(serviceSpy.firstCall.args[0].query).to.be.equal(corbel.utils.serializeParams({ + query: [{ + '$like': { + 'name': 'test' + } + }] + })) + }) + + it('can chain for a request with custom parameters on get call', function () { + relation.like('name', 'test').get(5, { + query: [{ + $like: { + name: 'otro' + } + }] + }) + + expect(serviceSpy.firstCall.args[0].query).to.be.equal(corbel.utils.serializeParams({ + query: [{ + $like: { + name: 'otro' + } + }] + })) + }) + }) + + describe('for resources', function () { + var resource, + serviceSpy + + beforeEach(function () { + resource = resources.resource('resource:entities', '25', '26') + serviceSpy = sandbox.stub(corbel.Services.prototype, '_buildParams') + }) + + it('supports querys', function () { + resource.get({ + query: [{ + '$like': { + name: 'test-name' + } + }] + }) + + expect(serviceSpy.firstCall.args[0].query).to.be.equal(corbel.utils.serializeParams({ + query: [{ + '$like': { + name: 'test-name' + } + }] + })) + }) + + it('can chain for a request', function () { + resource.like('name', 'test').get({ + dataType: 'application/json' + }) + + expect(serviceSpy.firstCall.args[0].query).to.be.equal(corbel.utils.serializeParams({ + query: [{ + '$like': { + 'name': 'test' + } + }] + })) + }) + + it('can chain for a request with custom parameters on get call', function () { + resource.like('name', 'test').get({ + query: [{ + $like: { + name: 'otro' + } + }] + }) + + expect(serviceSpy.firstCall.args[0].query).to.be.equal(corbel.utils.serializeParams({ + query: [{ + $like: { + name: 'otro' + } + }] + })) + }) + }) +}) diff --git a/test/node/unit/resources.js b/test/node/unit/resources.js index 8c71f06..afee88c 100644 --- a/test/node/unit/resources.js +++ b/test/node/unit/resources.js @@ -1,145 +1,136 @@ -/*jshint newcap: false */ -'use strict'; - -var corbel = require('../../../dist/corbel.js'), - chai = require('chai'), - sinon = require('sinon'), - expect = chai.expect; - -var TEST_ENDPOINT = 'https://resources-qa.bqws.io/v1.0/domain-example/', - - DEFAULT_QUERY_OBJECT_STRING = encodeURIComponent('[{"$eq":{"field3":true}},{"$eq":{"field4":true}},{"$gt":{"field5":"value"}},{"$gte":{"field5":"value"}},{"$lt":{"field5":"value"}},{"$lte":{"field5":"value"}},{"$ne":{"field5":"value"}},{"$in":{"field2":["pepe","juan"]}},{"$all":{"field5":["pepe","juan"]}},{"$like":{"field5":"value"}}]'), - - DEFAULT_SIMPLE_CONDITION_OBJECT_STRING = encodeURIComponent('[{\"$eq\":{\"test\":2}}]'), - - DEFAULT_MULTIPLE_CONDITION_OBJECT_STRING = encodeURIComponent('[{\"$eq\":{\"test\":2}}]') + '&api:condition=' + encodeURIComponent('[{\"$eq\":{\"test\":3}}]'), - - URL_COLLECTION_DECODED = TEST_ENDPOINT + 'resource/resource:entity?api:query=' + DEFAULT_QUERY_OBJECT_STRING + '&api:search=' + encodeURIComponent('{"text":"test"}') + '&api:distinct=' + encodeURIComponent('text,field1') + '&api:sort=' + encodeURIComponent('{"field1":"asc"}') + '&api:page=1&api:pageSize=5', - - URL_SIMPLE_CONDITION_DECODED = TEST_ENDPOINT + 'resource/resource:entity?api:condition=' + DEFAULT_SIMPLE_CONDITION_OBJECT_STRING, - - URL_MULTIPLE_CONDITION_DECODED = TEST_ENDPOINT + 'resource/resource:entity?api:condition=' + DEFAULT_MULTIPLE_CONDITION_OBJECT_STRING, - - - DEFAULT_QUERY_OBJECT = [{ - '$eq': { - field3: true - } - }, { - '$eq': { - field4: true - } - }, { - '$gt': { - field5: 'value' - } - }, { - '$gte': { - field5: 'value' - } - }, { - '$lt': { - field5: 'value' - } - }, { - '$lte': { - field5: 'value' - } - }, { - '$ne': { - field5: 'value' - } - }, { - '$in': { - field2: ['pepe', 'juan'] - } - }, { - '$all': { - field5: ['pepe', 'juan'] - } - }, { - '$like': { - field5: 'value' - } - }]; +/* jshint newcap: false */ +'use strict' +/* globals describe it before after beforeEach afterEach */ + +var corbel = require('../../../dist/corbel.js') +var chai = require('chai') +var sinon = require('sinon') +var expect = chai.expect + +var TEST_ENDPOINT = 'https://resources-qa.bqws.io/v1.0/domain-example/' + +var DEFAULT_QUERY_OBJECT_STRING = encodeURIComponent('[{"$eq":{"field3":true}},{"$eq":{"field4":true}},{"$gt":{"field5":"value"}},{"$gte":{"field5":"value"}},{"$lt":{"field5":"value"}},{"$lte":{"field5":"value"}},{"$ne":{"field5":"value"}},{"$in":{"field2":["pepe","juan"]}},{"$all":{"field5":["pepe","juan"]}},{"$like":{"field5":"value"}}]') + +var DEFAULT_SIMPLE_CONDITION_OBJECT_STRING = encodeURIComponent('[{"$eq":{"test":2}}]') + +var DEFAULT_MULTIPLE_CONDITION_OBJECT_STRING = encodeURIComponent('[{"$eq":{"test":2}}]') + '&api:condition=' + encodeURIComponent('[{"$eq":{"test":3}}]') + +var URL_COLLECTION_DECODED = TEST_ENDPOINT + 'resource/resource:entity?api:query=' + DEFAULT_QUERY_OBJECT_STRING + '&api:search=' + encodeURIComponent('{"text":"test"}') + '&api:distinct=' + encodeURIComponent('text,field1') + '&api:sort=' + encodeURIComponent('{"field1":"asc"}') + '&api:page=1&api:pageSize=5' + +var URL_SIMPLE_CONDITION_DECODED = TEST_ENDPOINT + 'resource/resource:entity?api:condition=' + DEFAULT_SIMPLE_CONDITION_OBJECT_STRING + +var URL_MULTIPLE_CONDITION_DECODED = TEST_ENDPOINT + 'resource/resource:entity?api:condition=' + DEFAULT_MULTIPLE_CONDITION_OBJECT_STRING + +var DEFAULT_QUERY_OBJECT = [{ + '$eq': { + field3: true + } +}, { + '$eq': { + field4: true + } +}, { + '$gt': { + field5: 'value' + } +}, { + '$gte': { + field5: 'value' + } +}, { + '$lt': { + field5: 'value' + } +}, { + '$lte': { + field5: 'value' + } +}, { + '$ne': { + field5: 'value' + } +}, { + '$in': { + field2: ['pepe', 'juan'] + } +}, { + '$all': { + field5: ['pepe', 'juan'] + } +}, { + '$like': { + field5: 'value' + } +}] var CONFIG = { clientId: 'clientId', clientSecret: 'clientSecret', scopes: 'scopes', - domain: 'domain-example', - urlBase: 'https://{{module}}-qa.bqws.io/v1.0/' -}; - -describe('corbel resources module', function() { - - var sandbox = sinon.sandbox.create(), - corbelDriver, - resources, - request; - - before(function() { - corbelDriver = corbel.getDriver(CONFIG); - resources = corbelDriver.resources; - }); - - after(function() {}); - - beforeEach(function() { - request = sandbox.stub(corbel.request, 'send').returns(Promise.resolve()); - }); - - afterEach(function() { - sandbox.restore(); - }); - - it('has all constants defined', function() { - expect(corbel.Resources.sort.ASC).to.be.equal('asc'); - expect(corbel.Resources.sort.DESC).to.be.equal('desc'); - }); - - describe('in collections', function() { - - it('has all operations', function() { - expect(resources.collection('id')).to.respondTo('get'); - expect(resources.collection('id')).to.respondTo('add'); - }); - - }); - - describe('in resources', function() { - - it('has all operations', function() { - expect(resources.resource('resource:entity', 'resource:anyId')).to.respondTo('get'); - expect(resources.resource('resource:entity', 'resource:anyId')).to.respondTo('update'); - expect(resources.resource('resource:entity', 'resource:anyId')).to.respondTo('delete'); - }); - - }); - - describe('in relations', function() { - - it('has all operations', function() { - expect(resources.relation('','','')).to.respondTo('get'); - expect(resources.relation('','','')).to.respondTo('add'); - }); - - }); - - it('generate single condition correctly', function() { +} + +describe('corbel resources module', function () { + var sandbox = sinon.sandbox.create() + var corbelDriver + var resources + var request + + before(function () { + corbelDriver = corbel.getDriver(CONFIG) + resources = corbelDriver.resources + }) + + after(function () {}) + + beforeEach(function () { + request = sandbox.stub(corbel.request, 'send').returns(Promise.resolve()) + }) + + afterEach(function () { + sandbox.restore() + }) + + it('has all constants defined', function () { + expect(corbel.Resources.sort.ASC).to.be.equal('asc') + expect(corbel.Resources.sort.DESC).to.be.equal('desc') + }) + + describe('in collections', function () { + it('has all operations', function () { + expect(resources.collection('id')).to.respondTo('get') + expect(resources.collection('id')).to.respondTo('add') + }) + }) + + describe('in resources', function () { + it('has all operations', function () { + expect(resources.resource('resource:entity', 'resource:anyId')).to.respondTo('get') + expect(resources.resource('resource:entity', 'resource:anyId')).to.respondTo('update') + expect(resources.resource('resource:entity', 'resource:anyId')).to.respondTo('delete') + }) + }) + + describe('in relations', function () { + it('has all operations', function () { + expect(resources.relation('', '', '')).to.respondTo('get') + expect(resources.relation('', '', '')).to.respondTo('add') + }) + }) + + it('generate single condition correctly', function () { var params = { condition: [{ '$eq': { test: 2 } }] - }; - expect(resources.collection('resource:entity').getURL(params)).to.be.equal(URL_SIMPLE_CONDITION_DECODED); - }); + } + expect(resources.collection('resource:entity').getURL(params)).to.be.equal(URL_SIMPLE_CONDITION_DECODED) + }) - it('generate multi condition correctly', function() { + it('generate multi condition correctly', function () { var params = { conditions: [{ condition: [{ @@ -154,11 +145,11 @@ describe('corbel resources module', function() { } }] }] - }; - expect(resources.collection('resource:entity').getURL(params)).to.be.equal(URL_MULTIPLE_CONDITION_DECODED); - }); + } + expect(resources.collection('resource:entity').getURL(params)).to.be.equal(URL_MULTIPLE_CONDITION_DECODED) + }) - it('request the same condition in retry request', function(done) { + it('request the same condition in retry request', function (done) { var params = { conditions: [{ condition: [{ @@ -173,36 +164,36 @@ describe('corbel resources module', function() { } }] }] - }; + } var tokenObject = { accessToken: 'accessToken', expiresAt: 123123, refreshToken: 'refreshToken' - }; - resources.driver.config.set(corbel.Iam.IAM_TOKEN, tokenObject); - resources.driver.config.set(corbel.Iam.IAM_TOKEN_SCOPES, 'scopes'); + } + resources.driver.config.set(corbel.Iam.IAM_TOKEN, tokenObject) + resources.driver.config.set(corbel.Iam.IAM_TOKEN_SCOPES, 'scopes') request.onCall(0).returns(Promise.reject({ status: 401 - })); + })) request.onCall(1).returns(Promise.resolve({ status: 200, data: tokenObject - })); + })) request.onCall(2).returns(Promise.resolve({ status: 200 - })); + })) - expect(resources.collection('resource:entity').get(params)).to.be.fulfilled.then(function() { - expect(request.callCount).to.be.equal(3); - expect(request.getCall(0).args[0].url).to.be.equal(URL_MULTIPLE_CONDITION_DECODED); + expect(resources.collection('resource:entity').get(params)).to.be.fulfilled.then(function () { + expect(request.callCount).to.be.equal(3) + expect(request.getCall(0).args[0].url).to.be.equal(URL_MULTIPLE_CONDITION_DECODED) // call 1 is for token refresh - expect(request.getCall(2).args[0].url).to.be.equal(URL_MULTIPLE_CONDITION_DECODED); - }).should.notify(done); - }); + expect(request.getCall(2).args[0].url).to.be.equal(URL_MULTIPLE_CONDITION_DECODED) + }).should.notify(done) + }) - it('generate resource query correctly', function() { + it('generate resource query correctly', function () { var requestParams = { query: DEFAULT_QUERY_OBJECT, search: { @@ -216,13 +207,13 @@ describe('corbel resources module', function() { sort: { field1: corbel.Resources.sort.ASC } - }; - expect(resources.collection('resource:entity').getURL(requestParams)).to.be.equal(URL_COLLECTION_DECODED); - }); + } + expect(resources.collection('resource:entity').getURL(requestParams)).to.be.equal(URL_COLLECTION_DECODED) + }) - it('generate resource query correctly', function() { + it('generate resource query correctly', function () { var urlDecoded = TEST_ENDPOINT + 'resource/resource:entity?api:query=' + DEFAULT_QUERY_OBJECT_STRING + - '&api:search=' + encodeURIComponent('{"text":"test"}') + '&api:distinct=' + encodeURIComponent('text,field1') + '&api:sort=' + encodeURIComponent('{"field1":"asc"}') + '&api:page=0&api:pageSize=0'; + '&api:search=' + encodeURIComponent('{"text":"test"}') + '&api:distinct=' + encodeURIComponent('text,field1') + '&api:sort=' + encodeURIComponent('{"field1":"asc"}') + '&api:page=0&api:pageSize=0' var requestParams = { query: DEFAULT_QUERY_OBJECT, search: { @@ -236,11 +227,11 @@ describe('corbel resources module', function() { sort: { field1: corbel.Resources.sort.ASC } - }; - expect(resources.collection('resource:entity').getURL(requestParams)).to.be.equal(urlDecoded); - }); + } + expect(resources.collection('resource:entity').getURL(requestParams)).to.be.equal(urlDecoded) + }) - it('generate resource query correctly with a string search', function() { + it('generate resource query correctly with a string search', function () { var requestParams = { query: DEFAULT_QUERY_OBJECT, search: 'test', @@ -252,12 +243,12 @@ describe('corbel resources module', function() { sort: { field1: corbel.Resources.sort.ASC } - }; + } - expect(resources.collection('resource:entity').getURL(requestParams)).to.be.equal(URL_COLLECTION_DECODED.replace('api:search=' + encodeURIComponent('{"text":"test"}'), 'api:search=' + encodeURIComponent('test'))); - }); + expect(resources.collection('resource:entity').getURL(requestParams)).to.be.equal(URL_COLLECTION_DECODED.replace('api:search=' + encodeURIComponent('{"text":"test"}'), 'api:search=' + encodeURIComponent('test'))) + }) - it('generate resource query correctly with custom query string', function() { + it('generate resource query correctly with custom query string', function () { var requestParams = { query: 'customQueryString', search: { @@ -271,24 +262,24 @@ describe('corbel resources module', function() { sort: { field1: corbel.Resources.sort.ASC } - }; + } - expect(resources.collection('resource:entity').getURL(requestParams)).to.be.equal(URL_COLLECTION_DECODED.replace(DEFAULT_QUERY_OBJECT_STRING, 'customQueryString')); - }); + expect(resources.collection('resource:entity').getURL(requestParams)).to.be.equal(URL_COLLECTION_DECODED.replace(DEFAULT_QUERY_OBJECT_STRING, 'customQueryString')) + }) - it('generates a query with weird characters', function() { + it('generates a query with weird characters', function () { var requestParams = { query: [{ '$eq': { 'name': 'Chewaçcá Sä+^*quñardel' } }] - }; + } - expect(resources.collection('resource:entity').getURL(requestParams)).to.be.equal(TEST_ENDPOINT + 'resource/resource:entity?api:query=' + encodeURIComponent('[{\"$eq\":{\"name\":\"Chewaçcá Sä+^*quñardel\"}}]')); - }); + expect(resources.collection('resource:entity').getURL(requestParams)).to.be.equal(TEST_ENDPOINT + 'resource/resource:entity?api:query=' + encodeURIComponent('[{"$eq":{"name":"Chewaçcá Sä+^*quñardel"}}]')) + }) - it('generate resource multi query (OR)', function() { + it('generate resource multi query (OR)', function () { var requestParams = { queries: [{ query: DEFAULT_QUERY_OBJECT @@ -306,12 +297,12 @@ describe('corbel resources module', function() { sort: { field1: corbel.Resources.sort.ASC } - }; + } - expect(resources.collection('resource:entity').getURL(requestParams)).to.be.equal(TEST_ENDPOINT + 'resource/resource:entity?api:query=' + encodeURIComponent('[{\"$eq\":{\"field3\":true}},{\"$eq\":{\"field4\":true}},{\"$gt\":{\"field5\":\"value\"}},{\"$gte\":{\"field5\":\"value\"}},{\"$lt\":{\"field5\":\"value\"}},{\"$lte\":{\"field5\":\"value\"}},{\"$ne\":{\"field5\":\"value\"}},{\"$in\":{\"field2\":[\"pepe\",\"juan\"]}},{\"$all\":{\"field5\":[\"pepe\",\"juan\"]}},{\"$like\":{\"field5\":\"value\"}}]') + '&api:query=' + encodeURIComponent('[{\"$eq\":{\"field3\":true}},{\"$eq\":{\"field4\":true}},{\"$gt\":{\"field5\":\"value\"}},{\"$gte\":{\"field5\":\"value\"}},{\"$lt\":{\"field5\":\"value\"}},{\"$lte\":{\"field5\":\"value\"}},{\"$ne\":{\"field5\":\"value\"}},{\"$in\":{\"field2\":[\"pepe\",\"juan\"]}},{\"$all\":{\"field5\":[\"pepe\",\"juan\"]}},{\"$like\":{\"field5\":\"value\"}}]') + '&api:search=' + encodeURIComponent('{\"text\":\"test\"}') + '&api:distinct=' + encodeURIComponent('text,field1') + '&api:sort=' + encodeURIComponent('{\"field1\":\"asc\"}') + '&api:page=1&api:pageSize=5'); - }); + expect(resources.collection('resource:entity').getURL(requestParams)).to.be.equal(TEST_ENDPOINT + 'resource/resource:entity?api:query=' + encodeURIComponent('[{"$eq":{"field3":true}},{"$eq":{"field4":true}},{"$gt":{"field5":"value"}},{"$gte":{"field5":"value"}},{"$lt":{"field5":"value"}},{"$lte":{"field5":"value"}},{"$ne":{"field5":"value"}},{"$in":{"field2":["pepe","juan"]}},{"$all":{"field5":["pepe","juan"]}},{"$like":{"field5":"value"}}]') + '&api:query=' + encodeURIComponent('[{"$eq":{"field3":true}},{"$eq":{"field4":true}},{"$gt":{"field5":"value"}},{"$gte":{"field5":"value"}},{"$lt":{"field5":"value"}},{"$lte":{"field5":"value"}},{"$ne":{"field5":"value"}},{"$in":{"field2":["pepe","juan"]}},{"$all":{"field5":["pepe","juan"]}},{"$like":{"field5":"value"}}]') + '&api:search=' + encodeURIComponent('{"text":"test"}') + '&api:distinct=' + encodeURIComponent('text,field1') + '&api:sort=' + encodeURIComponent('{"field1":"asc"}') + '&api:page=1&api:pageSize=5') + }) - it('generate resource multi query (OR)', function() { + it('generate resource multi query (OR)', function () { var requestParams = { 'queries': [{ 'query': [{ @@ -355,181 +346,181 @@ describe('corbel resources module', function() { sort: { field1: corbel.Resources.sort.ASC } - }; + } - expect(resources.collection('resource:entity').getURL(requestParams)).to.be.equal(TEST_ENDPOINT + 'resource/resource:entity?api:query=' + encodeURIComponent('[{\"$like\":{\"title\":\"Praga\"}},{\"$in\":{\"_dst_id\":[\"books:Book/f44ee834b058d9f383acaece2d44613c\",\"books:Book/9979a1daf7c6eebf04375bd0fc37f3c3\"]}}]') + '&api:query=' + encodeURIComponent('[{\"$elem_match\":{\"authors\":[{\"$like\":{\"name\":\"Praga\"}}]}},{\"$in\":{\"_dst_id\":[\"books:Book/f44ee834b058d9f383acaece2d44613c\"]}}]') + '&api:search=' + encodeURIComponent('{\"text\":\"test\"}') + '&api:distinct=' + encodeURIComponent('text,field1') + '&api:sort=' + encodeURIComponent('{\"field1\":\"asc\"}') + '&api:page=1&api:pageSize=5'); - }); + expect(resources.collection('resource:entity').getURL(requestParams)).to.be.equal(TEST_ENDPOINT + 'resource/resource:entity?api:query=' + encodeURIComponent('[{"$like":{"title":"Praga"}},{"$in":{"_dst_id":["books:Book/f44ee834b058d9f383acaece2d44613c","books:Book/9979a1daf7c6eebf04375bd0fc37f3c3"]}}]') + '&api:query=' + encodeURIComponent('[{"$elem_match":{"authors":[{"$like":{"name":"Praga"}}]}},{"$in":{"_dst_id":["books:Book/f44ee834b058d9f383acaece2d44613c"]}}]') + '&api:search=' + encodeURIComponent('{"text":"test"}') + '&api:distinct=' + encodeURIComponent('text,field1') + '&api:sort=' + encodeURIComponent('{"field1":"asc"}') + '&api:page=1&api:pageSize=5') + }) - it('resources.collection has mandatory parameters', function() { - expect(function(){ - resources.collection(); - }).to.throw('type value is mandatory and cannot be undefined'); - }); + it('resources.collection has mandatory parameters', function () { + expect(function () { + resources.collection() + }).to.throw('type value is mandatory and cannot be undefined') + }) - it('gets all resources in a collection correctly', function() { - resources.collection('books:Book').get(); + it('gets all resources in a collection correctly', function () { + resources.collection('books:Book').get() - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(TEST_ENDPOINT + 'resource/books:Book'); - expect(callRequestParam.method).to.be.equal('GET'); - }); + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(TEST_ENDPOINT + 'resource/books:Book') + expect(callRequestParam.method).to.be.equal('GET') + }) - it('gets all resources in a collection with undefined collectionId', function() { - expect(function(){ - resources.collection().get(); - }).to.throw('type value is mandatory and cannot be undefined'); - }); + it('gets all resources in a collection with undefined collectionId', function () { + expect(function () { + resources.collection().get() + }).to.throw('type value is mandatory and cannot be undefined') + }) - it('gets all resources in a collection with a mediaType', function() { + it('gets all resources in a collection with a mediaType', function () { resources.collection('books:Book').get({ dataType: 'epub' - }); - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(TEST_ENDPOINT + 'resource/books:Book'); - expect(callRequestParam.method).to.be.equal('GET'); - expect(callRequestParam.headers.Accept).to.be.equal('epub'); - }); - - it('add model to a collection', function() { + }) + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(TEST_ENDPOINT + 'resource/books:Book') + expect(callRequestParam.method).to.be.equal('GET') + expect(callRequestParam.headers.Accept).to.be.equal('epub') + }) + + it('add model to a collection', function () { resources.collection('books:Book').add({ name: 'test1', data: 'test-data' - }); - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(TEST_ENDPOINT + 'resource/books:Book'); - expect(callRequestParam.method).to.be.equal('POST'); - }); - - it('resources.resource has mandatory parameters', function() { - expect(function(){ - resources.resource('type', undefined); - }).to.throw('id value is mandatory and cannot be undefined'); - - expect(function(){ - resources.resource(undefined, 'id'); - }).to.throw('type value is mandatory and cannot be undefined'); - }); - - it('update a resource', function() { + }) + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(TEST_ENDPOINT + 'resource/books:Book') + expect(callRequestParam.method).to.be.equal('POST') + }) + + it('resources.resource has mandatory parameters', function () { + expect(function () { + resources.resource('type', undefined) + }).to.throw('id value is mandatory and cannot be undefined') + + expect(function () { + resources.resource(undefined, 'id') + }).to.throw('type value is mandatory and cannot be undefined') + }) + + it('update a resource', function () { resources.resource('books:Book', '123').update({ name: 'test' - }); - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(TEST_ENDPOINT + 'resource/books:Book/123'); - expect(callRequestParam.method).to.be.equal('PUT'); - expect(callRequestParam.headers.Accept).to.be.equal('application/json'); - }); - - it('delete a resource', function() { - resources.resource('books:Book', '123').delete(); - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(TEST_ENDPOINT + 'resource/books:Book/123'); - expect(callRequestParam.method).to.be.equal('DELETE'); - expect(callRequestParam.headers.Accept).to.be.equal('application/json'); - }); - - //Sanity check SILKROAD-712 - it('get a resource with mediaType and noContent', function() { + }) + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(TEST_ENDPOINT + 'resource/books:Book/123') + expect(callRequestParam.method).to.be.equal('PUT') + expect(callRequestParam.headers.Accept).to.be.equal('application/json') + }) + + it('delete a resource', function () { + resources.resource('books:Book', '123').delete() + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(TEST_ENDPOINT + 'resource/books:Book/123') + expect(callRequestParam.method).to.be.equal('DELETE') + expect(callRequestParam.headers.Accept).to.be.equal('application/json') + }) + + // Sanity check SILKROAD-712 + it('get a resource with mediaType and noContent', function () { resources.resource('books:Book', '123').get({ dataType: 'application/json', noRedirect: true - }); - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(TEST_ENDPOINT + 'resource/books:Book/123'); - expect(callRequestParam.method).to.be.equal('GET'); - expect(callRequestParam.headers.Accept).to.be.equal('application/json'); - expect(callRequestParam.headers['No-Redirect']).to.be.equal(true); - }); - - it('update a resource acl', function() { + }) + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(TEST_ENDPOINT + 'resource/books:Book/123') + expect(callRequestParam.method).to.be.equal('GET') + expect(callRequestParam.headers.Accept).to.be.equal('application/json') + expect(callRequestParam.headers['No-Redirect']).to.be.equal(true) + }) + + it('update a resource acl', function () { resources.resource('books:Book', '123').updateAcl({ name: 'test' - }); - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(TEST_ENDPOINT + 'resource/books:Book/123'); - expect(callRequestParam.method).to.be.equal('PUT'); - expect(callRequestParam.headers.Accept).to.be.equal('application/corbel.acl+json'); - }); - - it('resources.relation has mandatory parameters', function() { - expect(function(){ - resources.relation(); - }).to.throw('type value is mandatory and cannot be undefined'); - - expect(function(){ - resources.relation(undefined, 'srcId', 'destType'); - }).to.throw('type value is mandatory and cannot be undefined'); - - expect(function(){ - resources.relation('type', undefined, 'destType'); - }).to.throw('srcId value is mandatory and cannot be undefined'); - - expect(function(){ - resources.relation('type', 'srcId', undefined); - }).to.throw('destType value is mandatory and cannot be undefined'); - }); - - it('should move a relation', function() { - resources.relation('books:Book', '123', '456').move('test', 1); - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.method).to.be.equal('PUT'); - expect(callRequestParam.headers.Accept).to.be.equal('application/json'); - expect(callRequestParam.data._order).to.be.equal('$pos(1)'); - expect(callRequestParam.url).to.be.equal(TEST_ENDPOINT + 'resource/books:Book/123/456;r=456/test'); - }); - - it('cannot move a relation with undefined values', function() { - expect(function(){ - resources.relation('books:Book', '123', '456').move(); - }).to.throw('destId value is mandatory and cannot be undefined'); - }); - - it('should move a relation with composed Id', function() { - resources.relation('books:Book', '123', '456').move('notImportant/test', 1); - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.method).to.be.equal('PUT'); - expect(callRequestParam.headers.Accept).to.be.equal('application/json'); - expect(callRequestParam.data._order).to.be.equal('$pos(1)'); - expect(callRequestParam.url).to.be.equal(TEST_ENDPOINT + 'resource/books:Book/123/456;r=456/test'); - }); - - it('delete a relation', function() { - resources.relation('books:Book', '123', '456').delete(); - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.url).to.be.equal(TEST_ENDPOINT + 'resource/books:Book/123/456'); - expect(callRequestParam.method).to.be.equal('DELETE'); - expect(callRequestParam.headers.Accept).to.be.equal('application/json'); - }); - - it('add a relation', function() { + }) + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(TEST_ENDPOINT + 'resource/books:Book/123') + expect(callRequestParam.method).to.be.equal('PUT') + expect(callRequestParam.headers.Accept).to.be.equal('application/corbel.acl+json') + }) + + it('resources.relation has mandatory parameters', function () { + expect(function () { + resources.relation() + }).to.throw('type value is mandatory and cannot be undefined') + + expect(function () { + resources.relation(undefined, 'srcId', 'destType') + }).to.throw('type value is mandatory and cannot be undefined') + + expect(function () { + resources.relation('type', undefined, 'destType') + }).to.throw('srcId value is mandatory and cannot be undefined') + + expect(function () { + resources.relation('type', 'srcId', undefined) + }).to.throw('destType value is mandatory and cannot be undefined') + }) + + it('should move a relation', function () { + resources.relation('books:Book', '123', '456').move('test', 1) + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.method).to.be.equal('PUT') + expect(callRequestParam.headers.Accept).to.be.equal('application/json') + expect(callRequestParam.data._order).to.be.equal('$pos(1)') + expect(callRequestParam.url).to.be.equal(TEST_ENDPOINT + 'resource/books:Book/123/456;r=456/test') + }) + + it('cannot move a relation with undefined values', function () { + expect(function () { + resources.relation('books:Book', '123', '456').move() + }).to.throw('destId value is mandatory and cannot be undefined') + }) + + it('should move a relation with composed Id', function () { + resources.relation('books:Book', '123', '456').move('notImportant/test', 1) + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.method).to.be.equal('PUT') + expect(callRequestParam.headers.Accept).to.be.equal('application/json') + expect(callRequestParam.data._order).to.be.equal('$pos(1)') + expect(callRequestParam.url).to.be.equal(TEST_ENDPOINT + 'resource/books:Book/123/456;r=456/test') + }) + + it('delete a relation', function () { + resources.relation('books:Book', '123', '456').delete() + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.url).to.be.equal(TEST_ENDPOINT + 'resource/books:Book/123/456') + expect(callRequestParam.method).to.be.equal('DELETE') + expect(callRequestParam.headers.Accept).to.be.equal('application/json') + }) + + it('add a relation', function () { resources.relation('books:Book', '123', '456').add('457', { name: 'test', data: 'test' - }); + }) - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.method).to.be.equal('PUT'); - expect(callRequestParam.headers.Accept).to.be.equal('application/json'); - }); + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.method).to.be.equal('PUT') + expect(callRequestParam.headers.Accept).to.be.equal('application/json') + }) - it('cannot add a relation with undefined values', function() { - expect(function(){ - resources.relation('books:Book', '123', '456').add(); - }).to.throw('destId value is mandatory and cannot be undefined'); - }); + it('cannot add a relation with undefined values', function () { + expect(function () { + resources.relation('books:Book', '123', '456').add() + }).to.throw('destId value is mandatory and cannot be undefined') + }) - it('add an anonymous relation', function() { + it('add an anonymous relation', function () { resources.relation('books:Book', '123', '456').addAnonymous({ name: 'test', data: 'test' - }); + }) - var callRequestParam = corbel.request.send.firstCall.args[0]; - expect(callRequestParam.method).to.be.equal('POST'); - expect(callRequestParam.headers.Accept).to.be.equal('application/json'); - }); + var callRequestParam = corbel.request.send.firstCall.args[0] + expect(callRequestParam.method).to.be.equal('POST') + expect(callRequestParam.headers.Accept).to.be.equal('application/json') + }) - it('generates the correct URL for relations', function() { - expect(resources.relation('cars:Car', 'id123', 'cars:Store').getURL()).to.be.equal(TEST_ENDPOINT + 'resource/cars:Car/id123/cars:Store'); - }); -}); + it('generates the correct URL for relations', function () { + expect(resources.relation('cars:Car', 'id123', 'cars:Store').getURL()).to.be.equal(TEST_ENDPOINT + 'resource/cars:Car/id123/cars:Store') + }) +}) diff --git a/test/node/unit/scheduler.js b/test/node/unit/scheduler.js index e63683b..1a1e34f 100644 --- a/test/node/unit/scheduler.js +++ b/test/node/unit/scheduler.js @@ -1,97 +1,96 @@ -'use strict'; +'use strict' /* jshint camelcase:false */ +/* globals describe it beforeEach afterEach */ -var corbel = require('../../../dist/corbel.js'), - chai = require('chai'), - sinon = require('sinon'), - expect = chai.expect; +var corbel = require('../../../dist/corbel.js') +var chai = require('chai') +var sinon = require('sinon') +var expect = chai.expect -describe('In Scheduler module we can', function() { +describe('In Scheduler module we can', function () { + var sandbox = sinon.sandbox.create() - var sandbox = sinon.sandbox.create(); + var CONFIG = { + clientId: 'clientId', + clientSecret: 'clientSecret', - var CONFIG = { + urlBase: 'https://{{module}}-corbel.io/' - clientId: 'clientId', - clientSecret: 'clientSecret', + } - urlBase: 'https://{{module}}-corbel.io/' + var TASK_ID = 'task:id' - }; - - var TASK_ID = 'task:id'; + var TASK_DATA = { 'data': 'data' } - var TASK_DATA = { 'data': 'data' }; + var SCHEDULER_URL = CONFIG.urlBase.replace('{{module}}', corbel.Scheduler.moduleName) + 'tasks' - var SCHEDULER_URL = CONFIG.urlBase.replace('{{module}}', corbel.Scheduler.moduleName) + 'tasks'; + var corbelDriver = corbel.getDriver(CONFIG) - var corbelDriver = corbel.getDriver(CONFIG); + var corbelRequestStub - var corbelRequestStub; + beforeEach(function () { + corbelRequestStub = sandbox.stub(corbel.request, 'send') + }) - beforeEach(function() { - corbelRequestStub = sandbox.stub(corbel.request, 'send'); - }); + afterEach(function () { + sandbox.restore() + }) - afterEach(function() { - sandbox.restore(); - }); + it('generate a scheduler task correctly', function () { + corbelRequestStub.returns(Promise.resolve()) + corbelDriver.scheduler.task().create(TASK_DATA) - it('generate a scheduler task correctly', function() { - corbelRequestStub.returns(Promise.resolve()); - corbelDriver.scheduler.task().create(TASK_DATA); + var callRequestParam = corbelRequestStub.getCall(0).args[0] + expect(callRequestParam.url).to.be.equal(SCHEDULER_URL) + expect(callRequestParam.method).to.be.equal('POST') + expect(callRequestParam.data).to.be.equal(TASK_DATA) + }) - var callRequestParam = corbelRequestStub.getCall(0).args[0]; - expect(callRequestParam.url).to.be.equal(SCHEDULER_URL); - expect(callRequestParam.method).to.be.equal('POST'); - expect(callRequestParam.data).to.be.equal(TASK_DATA); - }); + it('task cannot be retrieved without an id', function () { + corbelRequestStub.returns(Promise.resolve('OK')) + expect(function () { + corbelDriver.scheduler.task().get() + }).to.throw('id value is mandatory and cannot be undefined') + }) - it('task cannot be retrieved without an id', function() { - corbelRequestStub.returns(Promise.resolve('OK')); - expect(function(){ - corbelDriver.scheduler.task().get(); - }).to.throw('id value is mandatory and cannot be undefined'); - }); + it('retrieve a scheduler task correctly', function () { + corbelRequestStub.returns(Promise.resolve()) + corbelDriver.scheduler.task(TASK_ID).get() - it('retrieve a scheduler task correctly', function() { - corbelRequestStub.returns(Promise.resolve()); - corbelDriver.scheduler.task(TASK_ID).get(); + var callRequestParam = corbelRequestStub.getCall(0).args[0] + expect(callRequestParam.url).to.be.equal(SCHEDULER_URL + '/' + TASK_ID) + expect(callRequestParam.method).to.be.equal('GET') + }) - var callRequestParam = corbelRequestStub.getCall(0).args[0]; - expect(callRequestParam.url).to.be.equal(SCHEDULER_URL +'/'+ TASK_ID); - expect(callRequestParam.method).to.be.equal('GET'); - }); + it('task cannot be updated without an id', function () { + corbelRequestStub.returns(Promise.resolve('OK')) + expect(function () { + corbelDriver.scheduler.task().update() + }).to.throw('id value is mandatory and cannot be undefined') + }) - it('task cannot be updated without an id', function() { - corbelRequestStub.returns(Promise.resolve('OK')); - expect(function(){ - corbelDriver.scheduler.task().update(); - }).to.throw('id value is mandatory and cannot be undefined'); - }); + it('update a scheduler task correctly', function () { + corbelRequestStub.returns(Promise.resolve()) + corbelDriver.scheduler.task(TASK_ID).update(TASK_DATA) - it('update a scheduler task correctly', function() { - corbelRequestStub.returns(Promise.resolve()); - corbelDriver.scheduler.task(TASK_ID).update(TASK_DATA); + var callRequestParam = corbelRequestStub.getCall(0).args[0] + expect(callRequestParam.url).to.be.equal(SCHEDULER_URL + '/' + TASK_ID) + expect(callRequestParam.method).to.be.equal('PUT') + }) - var callRequestParam = corbelRequestStub.getCall(0).args[0]; - expect(callRequestParam.url).to.be.equal(SCHEDULER_URL +'/'+ TASK_ID); - expect(callRequestParam.method).to.be.equal('PUT'); - }); + it('task cannot be delete without an id', function () { + corbelRequestStub.returns(Promise.resolve('OK')) + expect(function () { + corbelDriver.scheduler.task().delete() + }).to.throw('id value is mandatory and cannot be undefined') + }) - it('task cannot be delete without an id', function() { - corbelRequestStub.returns(Promise.resolve('OK')); - expect(function(){ - corbelDriver.scheduler.task().delete(); - }).to.throw('id value is mandatory and cannot be undefined'); - }); + it('delete a scheduler task correctly', function () { + corbelRequestStub.returns(Promise.resolve()) + corbelDriver.scheduler.task(TASK_ID).delete() - it('delete a scheduler task correctly', function() { - corbelRequestStub.returns(Promise.resolve()); - corbelDriver.scheduler.task(TASK_ID).delete(); - - var callRequestParam = corbelRequestStub.getCall(0).args[0]; - expect(callRequestParam.url).to.be.equal(SCHEDULER_URL +'/'+ TASK_ID); - expect(callRequestParam.method).to.be.equal('DELETE'); - }); -}); + var callRequestParam = corbelRequestStub.getCall(0).args[0] + expect(callRequestParam.url).to.be.equal(SCHEDULER_URL + '/' + TASK_ID) + expect(callRequestParam.method).to.be.equal('DELETE') + }) +}) diff --git a/test/node/unit/services.js b/test/node/unit/services.js index 5de82e4..900f559 100644 --- a/test/node/unit/services.js +++ b/test/node/unit/services.js @@ -1,555 +1,502 @@ -'use strict'; - -var corbel = require('../../../dist/corbel.js'), - chai = require('chai'), - expect = chai.expect, - sinon = require('sinon'); - -describe('corbel.Services module', function() { - - var sandbox, - driver = corbel.getDriver({ - urlBase: 'urlBase/', - clientId: 'clientId', - clientSecret: 'clientSecret', - audience: 'audience', - scopes: 'scopes' - }), - service, - requestStub; - - this.timeout(4000); - - beforeEach(function() { - sandbox = sinon.sandbox.create(); - service = new corbel.Services(driver); - requestStub = sandbox.stub(corbel.request, 'send'); - }); - - afterEach(function() { - sandbox.restore(); - }); - - it('contains expected static methods', function() { - expect(corbel.Services).to.include.key('getLocationId'); - expect(corbel.Services).to.include.key('addEmptyJson'); - }); - - it('contains expected static constants', function() { - expect(corbel.Services._FORCE_UPDATE_TEXT).to.be.a('string'); - expect(corbel.Services._FORCE_UPDATE_MAX_RETRIES).to.be.a('number'); - expect(corbel.Services._FORCE_UPDATE_STATUS).to.be.a('string'); - expect(corbel.Services._FORCE_UPDATE_STATUS_CODE).to.be.a('number'); - expect(corbel.Services._UNAUTHORIZED_STATUS_CODE).to.be.a('number'); - }); - - it('has expected methods', function() { - expect(service).to.respondTo('request'); - expect(service).to.respondTo('_doRequest'); - expect(service).to.respondTo('_refreshHandler'); - expect(service).to.respondTo('_addAuthorization'); - expect(service).to.respondTo('_buildParams'); - expect(service).to.respondTo('_buildUri'); - }); - - describe('in `request` method', function() { - +'use strict' +/* globals describe it beforeEach afterEach */ + +var corbel = require('../../../dist/corbel.js') +var chai = require('chai') +var expect = chai.expect +var sinon = require('sinon') + +describe('corbel.Services module', function () { + var sandbox + var driver = corbel.getDriver({ + urlBase: 'urlBase/', + clientId: 'clientId', + clientSecret: 'clientSecret', + audience: 'audience', + scopes: 'scopes' + }) + var service + var requestStub + + this.timeout(4000) + + beforeEach(function () { + sandbox = sinon.sandbox.create() + service = new corbel.Services(driver) + requestStub = sandbox.stub(corbel.request, 'send') + }) + + afterEach(function () { + sandbox.restore() + }) + + it('contains expected static methods', function () { + expect(corbel.Services).to.include.key('getLocationId') + expect(corbel.Services).to.include.key('addEmptyJson') + }) + + it('contains expected static constants', function () { + expect(corbel.Services._FORCE_UPDATE_TEXT).to.be.a('string') + expect(corbel.Services._FORCE_UPDATE_MAX_RETRIES).to.be.a('number') + expect(corbel.Services._FORCE_UPDATE_STATUS).to.be.a('string') + expect(corbel.Services._FORCE_UPDATE_STATUS_CODE).to.be.a('number') + expect(corbel.Services._UNAUTHORIZED_STATUS_CODE).to.be.a('number') + }) + + it('has expected methods', function () { + expect(service).to.respondTo('request') + expect(service).to.respondTo('_doRequest') + expect(service).to.respondTo('_refreshHandler') + expect(service).to.respondTo('_addAuthorization') + expect(service).to.respondTo('_buildParams') + expect(service).to.respondTo('_buildUri') + }) + + describe('in `request` method', function () { var spyRefreshHandler, spyTrigger, spyDoRequest, stubTokenBuilder, spyTokenCreate, spyTokenRefresh, - spyConfigSet; + spyConfigSet var generatedAccessToken = corbel.jwt.generate({ iss: 'example', aud: 'example', scope: 'example' - }, 'secret'); + }, 'secret') var generatedRefreshToken = corbel.jwt.generate({ iss: 'example', aud: 'example', scope: 'example' - }, 'secret'); + }, 'secret') var tokenUser = { accessToken: generatedAccessToken, refreshToken: 'refreshToken', expiresAt: 111111 - }; + } var tokenRefresh = { accessToken: generatedRefreshToken, refreshToken: 'newRefreshToken', expiresAt: 222222 - }; + } var tokenClient = { accessToken: generatedAccessToken, expiresAt: 333333 - }; + } var unAuthorizeResponse = Promise.reject({ status: corbel.Services._UNAUTHORIZED_STATUS_CODE, error: 'unauthorized' - }); - - beforeEach(function() { - spyRefreshHandler = sandbox.spy(service, '_refreshHandler'); - spyTrigger = sandbox.spy(driver, 'trigger'); - spyDoRequest = sandbox.spy(service, '_doRequest'); - - var tokenBuilder = driver.iam.token(); - spyTokenCreate = sandbox.spy(tokenBuilder, 'create'); - spyTokenRefresh = sandbox.spy(tokenBuilder, 'refresh'); - stubTokenBuilder = sandbox.stub(driver.iam, 'token').returns(tokenBuilder); - - spyConfigSet = sandbox.spy(driver.config, 'set'); + }) - }); + beforeEach(function () { + spyRefreshHandler = sandbox.spy(service, '_refreshHandler') + spyTrigger = sandbox.spy(driver, 'trigger') + spyDoRequest = sandbox.spy(service, '_doRequest') - describe('with a success response', function() { + var tokenBuilder = driver.iam.token() + spyTokenCreate = sandbox.spy(tokenBuilder, 'create') + spyTokenRefresh = sandbox.spy(tokenBuilder, 'refresh') + stubTokenBuilder = sandbox.stub(driver.iam, 'token').returns(tokenBuilder) - beforeEach(function() { - requestStub.returns(Promise.resolve('data')); - }); + spyConfigSet = sandbox.spy(driver.config, 'set') + }) - it('returns success response', function(done) { + describe('with a success response', function () { + beforeEach(function () { + requestStub.returns(Promise.resolve('data')) + }) + it('returns success response', function (done) { expect(service.request({ method: 'GET', url: 'url' - })).to.be.fulfilled.then(function(response) { - expect(response).to.be.equal('data'); - }).should.notify(done); - - }); - - it('do not retry the request', function(done) { + })).to.be.fulfilled.then(function (response) { + expect(response).to.be.equal('data') + }).should.notify(done) + }) + it('do not retry the request', function (done) { expect(service.request({ method: 'GET', url: 'url' - })).to.be.fulfilled.then(function() { - expect(spyRefreshHandler.callCount).to.be.equal(0); - }).should.notify(done); - - }); - - it('`service:request:before` and `service:request:after` events are triggered once', function(done) { + })).to.be.fulfilled.then(function () { + expect(spyRefreshHandler.callCount).to.be.equal(0) + }).should.notify(done) + }) + it('`service:request:before` and `service:request:after` events are triggered once', function (done) { expect(service.request({ method: 'GET', url: 'url' - })).to.be.fulfilled.then(function() { - expect(spyTrigger.withArgs('service:request:before').callCount).to.be.equal(1); - expect(spyTrigger.withArgs('service:request:after').callCount).to.be.equal(1); - }).should.notify(done); - - }); - - }); - - describe('with a rejected response', function() { - - describe('because of `force_update`', function() { - - - beforeEach(function() { - + })).to.be.fulfilled.then(function () { + expect(spyTrigger.withArgs('service:request:before').callCount).to.be.equal(1) + expect(spyTrigger.withArgs('service:request:after').callCount).to.be.equal(1) + }).should.notify(done) + }) + }) + + describe('with a rejected response', function () { + describe('because of `force_update`', function () { + beforeEach(function () { // reset force_update counter - driver.config.set(corbel.Services._FORCE_UPDATE_STATUS, 0); + driver.config.set(corbel.Services._FORCE_UPDATE_STATUS, 0) // stub request requestStub.onCall(0).returns(Promise.reject({ status: corbel.Services._FORCE_UPDATE_STATUS_CODE, textStatus: corbel.Services._FORCE_UPDATE_TEXT - })); - - }); - - it('triggers force update handler and rejects promise', function(done) { + })) + }) + it('triggers force update handler and rejects promise', function (done) { expect(service.request({ method: 'GET', url: 'url' - })).to.be.rejected.then(function() { - expect(driver.config.get(corbel.Services._FORCE_UPDATE_STATUS)).to.be.equal(1); - - expect(spyRefreshHandler.callCount).to.be.equal(0); - expect(stubTokenBuilder.callCount).to.be.equal(0); - expect(spyDoRequest.callCount).to.be.equal(1); - }).should.notify(done); - - }); - + })).to.be.rejected.then(function () { + expect(driver.config.get(corbel.Services._FORCE_UPDATE_STATUS)).to.be.equal(1) - it('`service:request:before` and `service:request:after` events are triggered once', function(done) { + expect(spyRefreshHandler.callCount).to.be.equal(0) + expect(stubTokenBuilder.callCount).to.be.equal(0) + expect(spyDoRequest.callCount).to.be.equal(1) + }).should.notify(done) + }) + it('`service:request:before` and `service:request:after` events are triggered once', function (done) { expect(service.request({ method: 'GET', url: 'url' - })).to.be.rejected.then(function() { - expect(driver.config.get(corbel.Services._FORCE_UPDATE_STATUS)).to.be.equal(1); - expect(spyTrigger.withArgs('service:request:before').callCount).to.be.equal(1); - expect(spyTrigger.withArgs('service:request:after').callCount).to.be.equal(1); - }).should.notify(done); - - }); - - it('`force:update` event are triggered once', function(done) { - + })).to.be.rejected.then(function () { + expect(driver.config.get(corbel.Services._FORCE_UPDATE_STATUS)).to.be.equal(1) + expect(spyTrigger.withArgs('service:request:before').callCount).to.be.equal(1) + expect(spyTrigger.withArgs('service:request:after').callCount).to.be.equal(1) + }).should.notify(done) + }) + + it('`force:update` event are triggered once', function (done) { expect(service.request({ method: 'GET', url: 'url' - })).to.be.rejected.then(function() { - expect(driver.config.get(corbel.Services._FORCE_UPDATE_STATUS)).to.be.equal(1); - expect(spyTrigger.withArgs('force:update').callCount).to.be.equal(1); - }).should.notify(done); - - }); - - }); - - describe('because of unauthorized', function() { - - beforeEach(function() { - driver.config.set(corbel.Iam.IAM_TOKEN, tokenUser); - driver.config.set(corbel.Iam.IAM_TOKEN_SCOPES, 'scopesExample'); + })).to.be.rejected.then(function () { + expect(driver.config.get(corbel.Services._FORCE_UPDATE_STATUS)).to.be.equal(1) + expect(spyTrigger.withArgs('force:update').callCount).to.be.equal(1) + }).should.notify(done) + }) + }) + + describe('because of unauthorized', function () { + beforeEach(function () { + driver.config.set(corbel.Iam.IAM_TOKEN, tokenUser) + driver.config.set(corbel.Iam.IAM_TOKEN_SCOPES, 'scopesExample') // stub request - requestStub.onCall(0).returns(unAuthorizeResponse); - - }); - - it('tries to refresh token', function(done) { + requestStub.onCall(0).returns(unAuthorizeResponse) + }) + it('tries to refresh token', function (done) { // stub refresh token requestStub.onCall(1).returns(Promise.resolve({ status: 200, data: tokenRefresh - })); + })) // stub retry request requestStub.onCall(2).returns(Promise.resolve({ status: 200, data: 'responseData' - })); + })) expect(service.request({ method: 'GET', url: 'url' - })).to.be.fulfilled.then(function() { - expect(spyRefreshHandler.calledOnce).to.be.equal(true); - expect(stubTokenBuilder.calledOnce).to.be.equal(true); - expect(spyTokenRefresh.calledOnce).to.be.equal(true); + })).to.be.fulfilled.then(function () { + expect(spyRefreshHandler.calledOnce).to.be.equal(true) + expect(stubTokenBuilder.calledOnce).to.be.equal(true) + expect(spyTokenRefresh.calledOnce).to.be.equal(true) // events are triggered once - expect(spyTrigger.withArgs('service:request:before').callCount).to.be.equal(1); - expect(spyTrigger.withArgs('service:request:after').callCount).to.be.equal(1); - expect(spyTrigger.withArgs('token:refresh').callCount).to.be.equal(1); - - }).should.notify(done); - - }); - - it('rejects after limit UNAUTHORIZED retries', function(done) { + expect(spyTrigger.withArgs('service:request:before').callCount).to.be.equal(1) + expect(spyTrigger.withArgs('service:request:after').callCount).to.be.equal(1) + expect(spyTrigger.withArgs('token:refresh').callCount).to.be.equal(1) + }).should.notify(done) + }) + it('rejects after limit UNAUTHORIZED retries', function (done) { // stub refresh token requestStub.onCall(1).returns(Promise.resolve({ status: 200, data: tokenRefresh - })); + })) // stub retry request - requestStub.onCall(2).returns(unAuthorizeResponse); + requestStub.onCall(2).returns(unAuthorizeResponse) // stub refresh token requestStub.onCall(3).returns(Promise.resolve({ status: 200, data: tokenRefresh - })); - //stub retry request - requestStub.onCall(4).returns(unAuthorizeResponse); + })) + // stub retry request + requestStub.onCall(4).returns(unAuthorizeResponse) // stub refresh token requestStub.onCall(5).returns(Promise.resolve({ status: 200, data: tokenRefresh - })); + })) // stub retry request requestStub.onCall(6).returns(Promise.resolve({ status: 200, data: 'responseData' - })); + })) expect(service.request({ method: 'GET', url: 'url' - })).to.be.rejected.then(function(response) { - expect(response.status).to.equals(401); - expect(requestStub.callCount).to.be.equal(3); - expect(spyRefreshHandler.callCount).to.be.equal(1); - expect(stubTokenBuilder.callCount).to.be.equal(1); - expect(spyTokenRefresh.callCount).to.be.equal(1); + })).to.be.rejected.then(function (response) { + expect(response.status).to.equals(401) + expect(requestStub.callCount).to.be.equal(3) + expect(spyRefreshHandler.callCount).to.be.equal(1) + expect(stubTokenBuilder.callCount).to.be.equal(1) + expect(spyTokenRefresh.callCount).to.be.equal(1) // events are triggered once - expect(spyTrigger.withArgs('service:request:before').callCount).to.be.equal(1); - expect(spyTrigger.withArgs('service:request:after').callCount).to.be.equal(1); - expect(spyTrigger.withArgs('token:refresh').callCount).to.be.equal(1); - }).should.notify(done); - - }); - - it('rejects after 1 retries, when the refresh token fails', function(done) { + expect(spyTrigger.withArgs('service:request:before').callCount).to.be.equal(1) + expect(spyTrigger.withArgs('service:request:after').callCount).to.be.equal(1) + expect(spyTrigger.withArgs('token:refresh').callCount).to.be.equal(1) + }).should.notify(done) + }) + it('rejects after 1 retries, when the refresh token fails', function (done) { // stub refresh token - requestStub.onCall(1).returns(unAuthorizeResponse); + requestStub.onCall(1).returns(unAuthorizeResponse) // stub retry request - requestStub.onCall(2).returns(unAuthorizeResponse); + requestStub.onCall(2).returns(unAuthorizeResponse) // stub refresh token - requestStub.onCall(3).returns(unAuthorizeResponse); + requestStub.onCall(3).returns(unAuthorizeResponse) // stub retry request - requestStub.onCall(4).returns(unAuthorizeResponse); + requestStub.onCall(4).returns(unAuthorizeResponse) expect(service.request({ method: 'GET', url: 'url' - })).to.be.rejected.then(function(response) { - expect(response.status).to.equals(401); - expect(requestStub.callCount).to.be.equal(2); - expect(spyRefreshHandler.callCount).to.be.equal(1); - expect(stubTokenBuilder.callCount).to.be.equal(1); - expect(spyTokenRefresh.callCount).to.be.equal(1); + })).to.be.rejected.then(function (response) { + expect(response.status).to.equals(401) + expect(requestStub.callCount).to.be.equal(2) + expect(spyRefreshHandler.callCount).to.be.equal(1) + expect(stubTokenBuilder.callCount).to.be.equal(1) + expect(spyTokenRefresh.callCount).to.be.equal(1) // events are triggered once - expect(spyTrigger.withArgs('service:request:before').callCount).to.be.equal(1); - expect(spyTrigger.withArgs('service:request:after').callCount).to.be.equal(1); - expect(spyTrigger.withArgs('token:refresh').callCount).to.be.equal(0); - }).should.notify(done); - - }); + expect(spyTrigger.withArgs('service:request:before').callCount).to.be.equal(1) + expect(spyTrigger.withArgs('service:request:after').callCount).to.be.equal(1) + expect(spyTrigger.withArgs('token:refresh').callCount).to.be.equal(0) + }).should.notify(done) + }) - it('works correctly when the driver has no clientSecret', function(done) { + it('works correctly when the driver has no clientSecret', function (done) { var corbelDriver = corbel.getDriver({ urlBase: 'urlBase/' - }); - var serviceDriver = new corbel.Services(corbelDriver); - var spyRefHandler = sandbox.spy(serviceDriver, '_refreshHandler'); + }) + var serviceDriver = new corbel.Services(corbelDriver) + var spyRefHandler = sandbox.spy(serviceDriver, '_refreshHandler') - var tokenBuilder = corbelDriver.iam.token(); - var spyTokenCreate = sandbox.spy(tokenBuilder, 'create'); - var stubTokenBuilder = sandbox.stub(corbelDriver.iam, 'token').returns(tokenBuilder); + var tokenBuilder = corbelDriver.iam.token() + var spyTokenCreate = sandbox.spy(tokenBuilder, 'create') + var stubTokenBuilder = sandbox.stub(corbelDriver.iam, 'token').returns(tokenBuilder) - // stub refresh token + // stub refresh token requestStub.onCall(1).returns(Promise.resolve({ status: 200, data: tokenRefresh - })); + })) // stub retry request - requestStub.onCall(2).returns(unAuthorizeResponse); + requestStub.onCall(2).returns(unAuthorizeResponse) // stub refresh token requestStub.onCall(3).returns(Promise.resolve({ status: 200, data: tokenRefresh - })); - //stub retry request - requestStub.onCall(4).returns(unAuthorizeResponse); + })) + // stub retry request + requestStub.onCall(4).returns(unAuthorizeResponse) expect(serviceDriver.request({ method: 'GET', url: 'url' - })).to.be.rejected.then(function(response) { - expect(response.status).to.equals(401); - expect(requestStub.callCount).to.be.equal(1); - expect(spyRefHandler.callCount).to.be.equal(1); - expect(stubTokenBuilder.callCount).to.be.equal(1); - expect(spyTokenCreate.callCount).to.be.equal(1); - - }).should.notify(done); - - }); - - describe('in refresh token handler', function() { - - it('can be triggered only once at same time', function(done) { - - driver.config.set(corbel.Iam.IAM_TOKEN, tokenClient); + })).to.be.rejected.then(function (response) { + expect(response.status).to.equals(401) + expect(requestStub.callCount).to.be.equal(1) + expect(spyRefHandler.callCount).to.be.equal(1) + expect(stubTokenBuilder.callCount).to.be.equal(1) + expect(spyTokenCreate.callCount).to.be.equal(1) + }) + .should.notify(done) + }) + + describe('in refresh token handler', function () { + it('can be triggered only once at same time', function (done) { + driver.config.set(corbel.Iam.IAM_TOKEN, tokenClient) // stub request - requestStub.returns(unAuthorizeResponse); + requestStub.returns(unAuthorizeResponse) - var promises = []; + var promises = [] for (var i = 0; i < 10; i++) { promises.push(service.request({ method: 'GET', url: 'url' - })); + })) } - expect(Promise.all(promises)).to.be.rejected.then(function() { + expect(Promise.all(promises)).to.be.rejected.then(function () { // number of refresh token requests - expect(spyRefreshHandler.callCount).to.be.equal(10); + expect(spyRefreshHandler.callCount).to.be.equal(10) // number of token builder requests - expect(stubTokenBuilder.callCount).to.be.equal(1); + expect(stubTokenBuilder.callCount).to.be.equal(1) // `service:request:before` and `service:request:after` events are triggered as expected // events are triggered once - expect(spyTrigger.withArgs('service:request:before').callCount).to.be.equal(10); - expect(spyTrigger.withArgs('service:request:after').callCount).to.be.equal(10); - expect(spyTrigger.withArgs('token:refresh').callCount).to.be.equal(0); - - }).should.notify(done); - - }); - - - it('if fails, return original error', function(done) { - + expect(spyTrigger.withArgs('service:request:before').callCount).to.be.equal(10) + expect(spyTrigger.withArgs('service:request:after').callCount).to.be.equal(10) + expect(spyTrigger.withArgs('token:refresh').callCount).to.be.equal(0) + }) + .should.notify(done) + }) + + it('if fails, return original error', function (done) { // stub request with custom error requestStub.onCall(0).returns(Promise.reject({ status: corbel.Services._UNAUTHORIZED_STATUS_CODE, error: 'original_error' - })); + })) // stub refresh token - requestStub.onCall(1).returns(unAuthorizeResponse); + requestStub.onCall(1).returns(unAuthorizeResponse) expect(service.request({ method: 'GET', url: 'url' - })).to.be.rejected.then(function(response) { - expect(spyRefreshHandler.calledOnce).to.be.equal(true); - expect(stubTokenBuilder.calledOnce).to.be.equal(true); - expect(spyTokenRefresh.calledOnce).to.be.equal(true); - expect(spyDoRequest.calledOnce).to.be.equal(true); + })).to.be.rejected.then(function (response) { + expect(spyRefreshHandler.calledOnce).to.be.equal(true) + expect(stubTokenBuilder.calledOnce).to.be.equal(true) + expect(spyTokenRefresh.calledOnce).to.be.equal(true) + expect(spyDoRequest.calledOnce).to.be.equal(true) - expect(response.status).to.be.equal(401); - expect(response.error).to.be.equal('original_error'); + expect(response.status).to.be.equal(401) + expect(response.error).to.be.equal('original_error') // events are triggered once - expect(spyTrigger.withArgs('service:request:before').callCount).to.be.equal(1); - expect(spyTrigger.withArgs('service:request:after').callCount).to.be.equal(1); - expect(spyTrigger.withArgs('token:refresh').callCount).to.be.equal(0); - - }).should.notify(done); - - }); - - describe('if success', function() { - - beforeEach(function() { - + expect(spyTrigger.withArgs('service:request:before').callCount).to.be.equal(1) + expect(spyTrigger.withArgs('service:request:after').callCount).to.be.equal(1) + expect(spyTrigger.withArgs('token:refresh').callCount).to.be.equal(0) + }) + .should.notify(done) + }) + + describe('if success', function () { + beforeEach(function () { // stub refresh token requestStub.onCall(1).returns(Promise.resolve({ status: 200, data: tokenRefresh - })); - - }); - - it('retries request', function(done) { + })) + }) + it('retries request', function (done) { // stub retry request requestStub.onCall(2).returns(Promise.resolve({ status: 200, data: 'responseData' - })); + })) expect(service.request({ method: 'GET', url: 'url' - })).to.be.fulfilled.then(function() { - expect(spyRefreshHandler.callCount).to.be.equal(1); - expect(spyDoRequest.callCount).to.be.equal(2); - expect(stubTokenBuilder.calledOnce).to.be.equal(true); - expect(spyTokenRefresh.calledOnce).to.be.equal(true); - - var args0 = spyDoRequest.getCall(0).args[0]; - var args1 = spyDoRequest.getCall(1).args[0]; - - expect(args0.url).to.be.equal(args1.url); - expect(args0.method).to.be.equal(args1.method); - expect(args0.contentType).to.be.equal(args1.contentType); - expect(args0.dataType).to.be.equal(args1.dataType); - expect(args0.data).to.be.equal(args1.data); - - expect(args0.headers.Authorization).to.be.equal('Bearer ' + generatedAccessToken); - expect(args1.headers.Authorization).to.be.equal('Bearer ' + generatedRefreshToken); - - // events are triggered once - expect(spyTrigger.withArgs('service:request:before').callCount).to.be.equal(1); - expect(spyTrigger.withArgs('service:request:after').callCount).to.be.equal(1); - expect(spyTrigger.withArgs('token:refresh').callCount).to.be.equal(1); - - }).should.notify(done); - - - }); - - describe('in retry request', function() { - - it('if success, returns response', function(done) { - + })) + .to.be.fulfilled + .then(function () { + expect(spyRefreshHandler.callCount).to.be.equal(1) + expect(spyDoRequest.callCount).to.be.equal(2) + expect(stubTokenBuilder.calledOnce).to.be.equal(true) + expect(spyTokenRefresh.calledOnce).to.be.equal(true) + + var args0 = spyDoRequest.getCall(0).args[0] + var args1 = spyDoRequest.getCall(1).args[0] + + expect(args0.url).to.be.equal(args1.url) + expect(args0.method).to.be.equal(args1.method) + expect(args0.contentType).to.be.equal(args1.contentType) + expect(args0.dataType).to.be.equal(args1.dataType) + expect(args0.data).to.be.equal(args1.data) + + expect(args0.headers.Authorization).to.be.equal('Bearer ' + generatedAccessToken) + expect(args1.headers.Authorization).to.be.equal('Bearer ' + generatedRefreshToken) + + // events are triggered once + expect(spyTrigger.withArgs('service:request:before').callCount).to.be.equal(1) + expect(spyTrigger.withArgs('service:request:after').callCount).to.be.equal(1) + expect(spyTrigger.withArgs('token:refresh').callCount).to.be.equal(1) + }) + .should.notify(done) + }) + + describe('in retry request', function () { + it('if success, returns response', function (done) { // stub retry request requestStub.onCall(2).returns(Promise.resolve({ status: 200, data: 'responseData' - })); + })) expect(service.request({ method: 'GET', url: 'url' - })).to.be.fulfilled.then(function(response) { - expect(response.data).to.be.equal('responseData'); - }).should.notify(done); - - }); - - it('if error, return retry error', function(done) { + })).to.be.fulfilled.then(function (response) { + expect(response.data).to.be.equal('responseData') + }).should.notify(done) + }) + it('if error, return retry error', function (done) { // stub retry request requestStub.onCall(2).returns(Promise.reject({ status: 444, error: 'retry_error' - })); + })) expect(service.request({ method: 'GET', url: 'url' - })).to.be.rejected.then(function(response) { - expect(spyRefreshHandler.calledOnce).to.be.equal(true); - expect(stubTokenBuilder.calledOnce).to.be.equal(true); - expect(spyTokenRefresh.calledOnce).to.be.equal(true); - expect(spyDoRequest.calledTwice).to.be.equal(true); - - expect(response.status).to.be.equal(444); - expect(response.error).to.be.equal('retry_error'); - }).should.notify(done); - - }); - - }); - - }); - - }); - - describe('with client authorization', function() { - - afterEach(function() { - corbel.Services._UNAUTHORIZED_MAX_RETRIES = 1; - }); - - describe('Configured with credentials', function() { - - beforeEach(function() { - driver.config.set(corbel.Iam.IAM_TOKEN, tokenClient); - corbel.Services._UNAUTHORIZED_MAX_RETRIES = 3; - }); - - it('refreshes token more than one time if needed', function(done) { - + })).to.be.rejected.then(function (response) { + expect(spyRefreshHandler.calledOnce).to.be.equal(true) + expect(stubTokenBuilder.calledOnce).to.be.equal(true) + expect(spyTokenRefresh.calledOnce).to.be.equal(true) + expect(spyDoRequest.calledTwice).to.be.equal(true) + + expect(response.status).to.be.equal(444) + expect(response.error).to.be.equal('retry_error') + }) + .should.notify(done) + }) + }) + }) + }) + + describe('with client authorization', function () { + afterEach(function () { + corbel.Services._UNAUTHORIZED_MAX_RETRIES = 1 + }) + + describe('Configured with credentials', function () { + beforeEach(function () { + driver.config.set(corbel.Iam.IAM_TOKEN, tokenClient) + corbel.Services._UNAUTHORIZED_MAX_RETRIES = 3 + }) + + it('refreshes token more than one time if needed', function (done) { /** * refreshToken response with client token because it will call * `iam.token().create()` instead of `iam.token.refresh()` @@ -559,197 +506,178 @@ describe('corbel.Services module', function() { requestStub.onCall(1).returns(Promise.resolve({ status: 200, data: tokenClient - })); + })) // stub retry request - requestStub.onCall(2).returns(unAuthorizeResponse); + requestStub.onCall(2).returns(unAuthorizeResponse) // stub refresh token requestStub.onCall(3).returns(Promise.resolve({ status: 200, data: tokenClient - })); + })) // stub retry request requestStub.onCall(4).returns(Promise.resolve({ status: 203, data: 'responseData' - })); + })) expect(service.request({ method: 'GET', url: 'url' - })).to.be.fulfilled.then(function(response) { - expect(response.status).to.equals(203); - //It has setted in the config the new data - expect(spyConfigSet.callCount).to.be.above(2); - expect(spyConfigSet.calledWith(corbel.Iam.IAM_TOKEN)).to.be.equal(true); - expect(spyConfigSet.calledWith(corbel.Iam.IAM_DOMAIN)).to.be.equal(true); - expect(spyConfigSet.calledWith(corbel.Iam.IAM_TOKEN_SCOPES)).to.be.equal(true); - - expect(spyRefreshHandler.callCount).to.be.equal(2); - expect(stubTokenBuilder.callCount).to.be.equal(2); - expect(spyTokenCreate.callCount).to.be.equal(2); + })).to.be.fulfilled.then(function (response) { + expect(response.status).to.equals(203) + // It has setted in the config the new data + expect(spyConfigSet.callCount).to.be.above(2) + expect(spyConfigSet.calledWith(corbel.Iam.IAM_TOKEN)).to.be.equal(true) + expect(spyConfigSet.calledWith(corbel.Iam.IAM_DOMAIN)).to.be.equal(true) + expect(spyConfigSet.calledWith(corbel.Iam.IAM_TOKEN_SCOPES)).to.be.equal(true) + + expect(spyRefreshHandler.callCount).to.be.equal(2) + expect(stubTokenBuilder.callCount).to.be.equal(2) + expect(spyTokenCreate.callCount).to.be.equal(2) // events are triggered once - expect(spyTrigger.withArgs('service:request:before').callCount).to.be.equal(1); - expect(spyTrigger.withArgs('service:request:after').callCount).to.be.equal(1); - expect(spyTrigger.withArgs('token:refresh').callCount).to.be.equal(2); - - }).should.notify(done); - - }); - - }); - - describe('Configured without credentials, only with iamToken', function() { - - beforeEach(function() { - - driver.config.set(corbel.Iam.IAM_TOKEN, tokenClient); - driver.config.set('clientSecret', null); - driver.config.set('clientId', null); - driver.config.set('scopes', null); - - }); - - it('tries to refresh token but fails as credentials are not provided', function(done) { + expect(spyTrigger.withArgs('service:request:before').callCount).to.be.equal(1) + expect(spyTrigger.withArgs('service:request:after').callCount).to.be.equal(1) + expect(spyTrigger.withArgs('token:refresh').callCount).to.be.equal(2) + }) + .should.notify(done) + }) + }) + + describe('Configured without credentials, only with iamToken', function () { + beforeEach(function () { + driver.config.set(corbel.Iam.IAM_TOKEN, tokenClient) + driver.config.set('clientSecret', null) + driver.config.set('clientId', null) + driver.config.set('scopes', null) + }) + + it('tries to refresh token but fails as credentials are not provided', function (done) { // stub refresh token (has not to be called), but leave it for mocking a failing case // otherwise it will pass the test but the functionality may be broken requestStub.onCall(1).returns(Promise.resolve({ status: 200, data: tokenClient - })); + })) // stub retry request (has not to be called), but leave it for mocking a failing case // otherwise it will pass the test but the functionality may be broken requestStub.onCall(2).returns(Promise.resolve({ status: 203, data: 'responseData' - })); + })) expect(service.request({ method: 'GET', url: 'url' - })).to.be.rejected.then(function(response) { - expect(response.status).to.equals(401); - //It has setted in the config the new data - expect(requestStub.callCount).to.be.equal(1); - expect(spyConfigSet.withArgs(corbel.Services._UNAUTHORIZED_NUM_RETRIES, 0).callCount).to.be.equal(1); - expect(spyConfigSet.calledWith(corbel.Services._UNAUTHORIZED_NUM_RETRIES, 0)).to.be.equal(true); - expect(spyRefreshHandler.callCount).to.be.equal(1); - expect(stubTokenBuilder.callCount).to.be.equal(1); - expect(spyTokenCreate.callCount).to.be.equal(1); + })).to.be.rejected.then(function (response) { + expect(response.status).to.equals(401) + // It has setted in the config the new data + expect(requestStub.callCount).to.be.equal(1) + expect(spyConfigSet.withArgs(corbel.Services._UNAUTHORIZED_NUM_RETRIES, 0).callCount).to.be.equal(1) + expect(spyConfigSet.calledWith(corbel.Services._UNAUTHORIZED_NUM_RETRIES, 0)).to.be.equal(true) + expect(spyRefreshHandler.callCount).to.be.equal(1) + expect(stubTokenBuilder.callCount).to.be.equal(1) + expect(spyTokenCreate.callCount).to.be.equal(1) // events are triggered once - expect(spyTrigger.withArgs('service:request:before').callCount).to.be.equal(1); - expect(spyTrigger.withArgs('service:request:after').callCount).to.be.equal(1); - expect(spyTrigger.withArgs('token:refresh').callCount).to.be.equal(0); - - }).should.notify(done); - - }); - - }); - - }); - - }); - - - }); - - }); - - describe('in `getLocationId` method', function() { - - it('returns undefined with invalid response or location', function() { + expect(spyTrigger.withArgs('service:request:before').callCount).to.be.equal(1) + expect(spyTrigger.withArgs('service:request:after').callCount).to.be.equal(1) + expect(spyTrigger.withArgs('token:refresh').callCount).to.be.equal(0) + }) + .should.notify(done) + }) + }) + }) + }) + }) + }) + + describe('in `getLocationId` method', function () { + it('returns undefined with invalid response or location', function () { // undefined responseObject - var response = corbel.Services.getLocationId(); - expect(response).to.be.equal(undefined); + var response = corbel.Services.getLocationId() + expect(response).to.be.equal(undefined) // empty responseObject - response = corbel.Services.getLocationId({}); - expect(response).to.be.equal(undefined); + response = corbel.Services.getLocationId({}) + expect(response).to.be.equal(undefined) // empty xhr location header response = corbel.Services.getLocationId({ xhr: { - getResponseHeader: function() { - return undefined; + getResponseHeader: function () { + return undefined } } - }); - expect(response).to.be.equal(undefined); + }) + expect(response).to.be.equal(undefined) // empty location header response = corbel.Services.getLocationId({ response: { headers: {} } - }); - expect(response).to.be.equal(undefined); - }); + }) + expect(response).to.be.equal(undefined) + }) - it('returns id with valid response or location', function() { - - var validLocation = '/some/location/locationId'; + it('returns id with valid response or location', function () { + var validLocation = '/some/location/locationId' var browserResponse = { xhr: { - getResponseHeader: function() { - return validLocation; + getResponseHeader: function () { + return validLocation } } - }; + } var nodeResponse = { response: { headers: { location: validLocation } } - }; - - var response = corbel.Services.getLocationId(browserResponse); - expect(response).to.be.equal('locationId'); - - response = corbel.Services.getLocationId(nodeResponse); - expect(response).to.be.equal('locationId'); - - }); - - }); - - describe('in `addEmptyJson` method', function() { + } - it('returns expected value with falsy values for "json" types', function() { - var response = corbel.Services.addEmptyJson(undefined, 'json'); - expect(response).to.be.equal('{}'); + var response = corbel.Services.getLocationId(browserResponse) + expect(response).to.be.equal('locationId') - response = corbel.Services.addEmptyJson(false, 'json'); - expect(response).to.be.equal('{}'); + response = corbel.Services.getLocationId(nodeResponse) + expect(response).to.be.equal('locationId') + }) + }) - response = corbel.Services.addEmptyJson(0, 'json'); - expect(response).to.be.equal('{}'); + describe('in `addEmptyJson` method', function () { + it('returns expected value with falsy values for "json" types', function () { + var response = corbel.Services.addEmptyJson(undefined, 'json') + expect(response).to.be.equal('{}') - response = corbel.Services.addEmptyJson('', 'json'); - expect(response).to.be.equal('{}'); - }); + response = corbel.Services.addEmptyJson(false, 'json') + expect(response).to.be.equal('{}') - it('returns expected value with falsy values for "no-json" types', function() { - var response = corbel.Services.addEmptyJson(undefined, 'text'); - expect(response).to.be.equal(undefined); + response = corbel.Services.addEmptyJson(0, 'json') + expect(response).to.be.equal('{}') - response = corbel.Services.addEmptyJson(false, 'text'); - expect(response).to.be.equal(false); + response = corbel.Services.addEmptyJson('', 'json') + expect(response).to.be.equal('{}') + }) - response = corbel.Services.addEmptyJson(0, 'text'); - expect(response).to.be.equal(0); + it('returns expected value with falsy values for "no-json" types', function () { + var response = corbel.Services.addEmptyJson(undefined, 'text') + expect(response).to.be.equal(undefined) - response = corbel.Services.addEmptyJson('', 'text'); - expect(response).to.be.equal(''); - }); + response = corbel.Services.addEmptyJson(false, 'text') + expect(response).to.be.equal(false) - }); + response = corbel.Services.addEmptyJson(0, 'text') + expect(response).to.be.equal(0) -}); + response = corbel.Services.addEmptyJson('', 'text') + expect(response).to.be.equal('') + }) + }) +}) diff --git a/test/node/unit/utils.js b/test/node/unit/utils.js index 932a27f..ee4e21c 100644 --- a/test/node/unit/utils.js +++ b/test/node/unit/utils.js @@ -1,71 +1,71 @@ -'use strict'; +'use strict' /* jshint camelcase:false */ +/* globals describe it */ -var corbel = require('../../../dist/corbel.js'), - chai = require('chai'), - expect = chai.expect; +var corbel = require('../../../dist/corbel.js') +var chai = require('chai') +var expect = chai.expect -describe('In utils module', function() { +describe('In utils module', function () { + it('an Array can be copied', function () { + var arrayOrigin = [1, 2, 3] - it('an Array can be copied', function() { - var arrayOrigin = [1, 2, 3]; + var copiedArray = corbel.utils.copyArray(arrayOrigin) - var copiedArray = corbel.utils.copyArray(arrayOrigin); + expect(copiedArray.length).to.equals(3) - expect(copiedArray.length).to.equals(3); + for (var i = 0; i < copiedArray.length; i++) { + expect(copiedArray[i]).to.equals(arrayOrigin[i]) + } + }) - for(var i = 0; i < copiedArray.length; i++){ - expect(copiedArray[i]).to.equals(arrayOrigin[i]); - } - }); + it('array references are not maintained', function () { + var arrayOrigin = [1, 2, 3] - it('array references are not maintained', function() { - var arrayOrigin = [1, 2, 3]; + var copiedArray = corbel.utils.copyArray(arrayOrigin) - var copiedArray = corbel.utils.copyArray(arrayOrigin); + copiedArray.pop() - copiedArray.pop(); + expect(arrayOrigin.length).to.equals(3) + expect(copiedArray.length).to.equals(2) + }) - expect(arrayOrigin.length).to.equals(3); - expect(copiedArray.length).to.equals(2); - }); + it('is JSON evaluation (true)', function () { + var testJson = '{"a": 1, "b": 2}' - it('is JSON evaluation (true)', function() { - var testJson = '{"a": 1, "b": 2}'; + expect(corbel.utils.isJSON(testJson)).to.be.equal(true) + }) - expect(corbel.utils.isJSON(testJson)).to.be.equal(true); - }); + it('is JSON evaluation (false)', function () { + var notJson = 'notJson' - it('is JSON evaluation (false)', function() { - var notJson = 'notJson'; + expect(corbel.utils.isJSON(notJson)).to.be.equal(false) + }) - expect(corbel.utils.isJSON(notJson)).to.be.equal(false); - }); + it('is stream evaluation (true)', function () { + var Stream = require('stream') + var stream = new Stream() - it('is stream evaluation (true)', function() { - var Stream = require('stream'); - var stream = new Stream(); + expect(corbel.utils.isStream(stream)).to.be.equal(true) + }) - expect(corbel.utils.isStream(stream)).to.be.equal(true); - }); + it('is stream evaluation (false)', function () { + var notStream = 'notStream' - it('is stream evaluation (false)', function() { - var notStream = 'notStream'; + expect(corbel.utils.isStream(notStream)).to.be.equal(false) + }) - expect(corbel.utils.isStream(notStream)).to.be.equal(false); - }); + it('an array is converted to object', function () { + var arr = ['a', 'b'] + var obj = {0: 'a', 1: 'b'} - it('an array is converted to object', function() { - var arr = ['a', 'b']; - var obj = {0: 'a', 1: 'b'}; + expect(corbel.utils.arrayToObject(arr)).to.deep.equal(obj) + }) - expect(corbel.utils.arrayToObject(arr)).to.deep.equal(obj); - }); - - it('keys are converted to lowercase', function() { - var upperObj = {A: 'a', B: 'b'}; - var lowerObj = {a: 'a', b: 'b'}; + it('keys are converted to lowercase', function () { + var upperObj = {A: 'a', B: 'b'} + var lowerObj = {a: 'a', b: 'b'} - expect(corbel.utils.keysToLowerCase(upperObj)).to.deep.equal(lowerObj); - }); -}); + expect(corbel.utils.keysToLowerCase(upperObj)).to.deep.equal(lowerObj) + }) +}) diff --git a/test/node/unit/validate.js b/test/node/unit/validate.js index e1d9e63..dbc9661 100644 --- a/test/node/unit/validate.js +++ b/test/node/unit/validate.js @@ -1,192 +1,178 @@ -'use strict'; +'use strict' /* jshint camelcase:false */ - -var corbel = require('../../../dist/corbel.js'), - chai = require('chai'), - expect = chai.expect; - -describe('Validate module', function() { - - it('exists and is an object', function() { - expect(corbel.validate).to.be.an('object'); - }); - - it('has all namespace properties', function() { - expect(corbel.validate).to.include.keys( - 'values', - 'value', - 'isDefined', - 'isNotNull', - 'isValue', - 'isGreaterThan', - 'isGreaterThanOrEqual' - ); - }); - - describe('corbel.validate.values', function() { - - it('returns true when values are defined', function() { - expect(corbel.validate.values(['id', 'value'], { - 'id':'1', - 'value': 'value' - })).to.be.equal(true); - }); - - it('throws an error when a certain value is undefined', function() { - expect(function() { - corbel.validate.values(['id', 'value'], { - 'value': 'value' - }); - }).to.throw('id value is mandatory and cannot be undefined'); - }); - }); - - describe('corbel.validate.isDefined', function() { - - it('returns false when value = undefined', function() { - expect(corbel.validate.isDefined(undefined)).to.be.equal(false); - }); - - it('can throw custom messages when return value is false', function() { - expect(function() { - corbel.validate.isDefined(undefined, 'message'); - }).to.throw('message'); - }); - - it('returns true when value != undefined', function() { - expect(corbel.validate.isDefined(0)).to.be.equal(true); - expect(corbel.validate.isDefined('string')).to.be.equal(true); - expect(corbel.validate.isDefined(NaN)).to.be.equal(true); - expect(corbel.validate.isDefined(null)).to.be.equal(true); - expect(corbel.validate.isDefined({})).to.be.equal(true); - expect(corbel.validate.isDefined([])).to.be.equal(true); - }); - - }); - - describe('corbel.validate.isNotNull', function() { - - it('returns false when value = null', function() { - expect(corbel.validate.isNotNull(null)).to.be.equal(false); - }); - - it('can throw custom messages when return value is false', function() { - expect(function() { - corbel.validate.isNotNull(null, 'message'); - }).to.throw('message'); - }); - - it('returns true when value != null', function() { - expect(corbel.validate.isNotNull(0)).to.be.equal(true); - expect(corbel.validate.isNotNull('string')).to.be.equal(true); - expect(corbel.validate.isNotNull(NaN)).to.be.equal(true); - expect(corbel.validate.isNotNull(undefined)).to.be.equal(true); - expect(corbel.validate.isNotNull({})).to.be.equal(true); - expect(corbel.validate.isNotNull([])).to.be.equal(true); - }); - - }); - - describe('corbel.validate.isValue', function() { - - it('returns false when value = (null || undefined)', function() { - expect(corbel.validate.isValue(null)).to.be.equal(false); - expect(corbel.validate.isValue(undefined)).to.be.equal(false); - }); - - it('can throw custom messages when return value is false', function() { - expect(function() { - corbel.validate.isValue(null, 'message'); - }).to.throw('message'); - - expect(function() { - corbel.validate.isValue(undefined, 'message'); - }).to.throw('message'); - }); - - it('returns true when value != (null && undefined)', function() { - expect(corbel.validate.isValue(0)).to.be.equal(true); - expect(corbel.validate.isValue('string')).to.be.equal(true); - expect(corbel.validate.isValue(NaN)).to.be.equal(true); - expect(corbel.validate.isValue({})).to.be.equal(true); - expect(corbel.validate.isValue([])).to.be.equal(true); - }); - - }); - - describe('corbel.validate.isGreaterThan', function() { - - it('works with same type', function() { - expect(corbel.validate.isGreaterThan(0, 1)).to.be.equal(false); - expect(corbel.validate.isGreaterThan(0, 0)).to.be.equal(false); - expect(corbel.validate.isGreaterThan('a', 'b')).to.be.equal(false); - expect(corbel.validate.isGreaterThan('a', 'a')).to.be.equal(false); - expect(corbel.validate.isGreaterThan('A', 'a')).to.be.equal(false); - - expect(corbel.validate.isGreaterThan(1, 0)).to.be.equal(true); - expect(corbel.validate.isGreaterThan('b', 'a')).to.be.equal(true); - expect(corbel.validate.isGreaterThan('a', 'A')).to.be.equal(true); - - }); - - it('works with differents type', function() { - expect(corbel.validate.isGreaterThan(0, '1')).to.be.equal(false); - expect(corbel.validate.isGreaterThan(3, '4')).to.be.equal(false); - expect(corbel.validate.isGreaterThan(0, '0')).to.be.equal(false); - expect(corbel.validate.isGreaterThan(0, '0.0')).to.be.equal(false); - expect(corbel.validate.isGreaterThan(1, '1.1')).to.be.equal(false); - expect(corbel.validate.isGreaterThan(1, 'a')).to.be.equal(false); - // @todo: this is pretty bizarre... - expect(corbel.validate.isGreaterThan(555555, 'a')).to.be.equal(false); - - expect(corbel.validate.isGreaterThan(1, '0')).to.be.equal(true); - expect(corbel.validate.isGreaterThan(4, '3')).to.be.equal(true); - expect(corbel.validate.isGreaterThan(4, '3.4')).to.be.equal(true); - }); - - it('can throw custom messages when return value is false', function() { - expect(function() { - corbel.validate.isGreaterThan(0, 1, 'message'); - }).to.throw('message'); - }); - - }); - - describe('corbel.validate.isGreaterThanOrEqual', function() { - - it('works with same type', function() { - expect(corbel.validate.isGreaterThanOrEqual(0, 1)).to.be.equal(false); - expect(corbel.validate.isGreaterThanOrEqual('a', 'b')).to.be.equal(false); - expect(corbel.validate.isGreaterThanOrEqual('A', 'a')).to.be.equal(false); - - expect(corbel.validate.isGreaterThanOrEqual(0, 0)).to.be.equal(true); - expect(corbel.validate.isGreaterThanOrEqual('a', 'a')).to.be.equal(true); - expect(corbel.validate.isGreaterThanOrEqual(1, 0)).to.be.equal(true); - expect(corbel.validate.isGreaterThanOrEqual('b', 'a')).to.be.equal(true); - expect(corbel.validate.isGreaterThanOrEqual('a', 'A')).to.be.equal(true); - - }); - - it('works with differents type', function() { - expect(corbel.validate.isGreaterThanOrEqual(0, '1')).to.be.equal(false); - expect(corbel.validate.isGreaterThanOrEqual(3, '4')).to.be.equal(false); - expect(corbel.validate.isGreaterThanOrEqual(1, '1.1')).to.be.equal(false); - expect(corbel.validate.isGreaterThanOrEqual(1, 'a')).to.be.equal(false); - expect(corbel.validate.isGreaterThanOrEqual(555555, 'a')).to.be.equal(false); - - expect(corbel.validate.isGreaterThanOrEqual(0, '0')).to.be.equal(true); - expect(corbel.validate.isGreaterThanOrEqual(0, '0.0')).to.be.equal(true); - expect(corbel.validate.isGreaterThanOrEqual(1, '0')).to.be.equal(true); - expect(corbel.validate.isGreaterThanOrEqual(4, '3')).to.be.equal(true); - expect(corbel.validate.isGreaterThanOrEqual(4, '3.4')).to.be.equal(true); - }); - - it('can throw custom messages when return value is false', function() { - expect(function() { - corbel.validate.isGreaterThanOrEqual(0, 1, 'message'); - }).to.throw('message'); - }); - - }); - -}); +/* globals describe it */ + +var corbel = require('../../../dist/corbel.js') +var chai = require('chai') +var expect = chai.expect + +describe('Validate module', function () { + it('exists and is an object', function () { + expect(corbel.validate).to.be.an('object') + }) + + it('has all namespace properties', function () { + expect(corbel.validate).to.include.keys( + 'values', + 'value', + 'isDefined', + 'isNotNull', + 'isValue', + 'isGreaterThan', + 'isGreaterThanOrEqual' + ) + }) + + describe('corbel.validate.values', function () { + it('returns true when values are defined', function () { + expect(corbel.validate.values(['id', 'value'], { + 'id': '1', + 'value': 'value' + })).to.be.equal(true) + }) + + it('throws an error when a certain value is undefined', function () { + expect(function () { + corbel.validate.values(['id', 'value'], { + 'value': 'value' + }) + }).to.throw('id value is mandatory and cannot be undefined') + }) + }) + + describe('corbel.validate.isDefined', function () { + it('returns false when value = undefined', function () { + expect(corbel.validate.isDefined(undefined)).to.be.equal(false) + }) + + it('can throw custom messages when return value is false', function () { + expect(function () { + corbel.validate.isDefined(undefined, 'message') + }).to.throw('message') + }) + + it('returns true when value != undefined', function () { + expect(corbel.validate.isDefined(0)).to.be.equal(true) + expect(corbel.validate.isDefined('string')).to.be.equal(true) + expect(corbel.validate.isDefined(NaN)).to.be.equal(true) + expect(corbel.validate.isDefined(null)).to.be.equal(true) + expect(corbel.validate.isDefined({})).to.be.equal(true) + expect(corbel.validate.isDefined([])).to.be.equal(true) + }) + }) + + describe('corbel.validate.isNotNull', function () { + it('returns false when value = null', function () { + expect(corbel.validate.isNotNull(null)).to.be.equal(false) + }) + + it('can throw custom messages when return value is false', function () { + expect(function () { + corbel.validate.isNotNull(null, 'message') + }).to.throw('message') + }) + + it('returns true when value != null', function () { + expect(corbel.validate.isNotNull(0)).to.be.equal(true) + expect(corbel.validate.isNotNull('string')).to.be.equal(true) + expect(corbel.validate.isNotNull(NaN)).to.be.equal(true) + expect(corbel.validate.isNotNull(undefined)).to.be.equal(true) + expect(corbel.validate.isNotNull({})).to.be.equal(true) + expect(corbel.validate.isNotNull([])).to.be.equal(true) + }) + }) + + describe('corbel.validate.isValue', function () { + it('returns false when value = (null || undefined)', function () { + expect(corbel.validate.isValue(null)).to.be.equal(false) + expect(corbel.validate.isValue(undefined)).to.be.equal(false) + }) + + it('can throw custom messages when return value is false', function () { + expect(function () { + corbel.validate.isValue(null, 'message') + }).to.throw('message') + + expect(function () { + corbel.validate.isValue(undefined, 'message') + }).to.throw('message') + }) + + it('returns true when value != (null && undefined)', function () { + expect(corbel.validate.isValue(0)).to.be.equal(true) + expect(corbel.validate.isValue('string')).to.be.equal(true) + expect(corbel.validate.isValue(NaN)).to.be.equal(true) + expect(corbel.validate.isValue({})).to.be.equal(true) + expect(corbel.validate.isValue([])).to.be.equal(true) + }) + }) + + describe('corbel.validate.isGreaterThan', function () { + it('works with same type', function () { + expect(corbel.validate.isGreaterThan(0, 1)).to.be.equal(false) + expect(corbel.validate.isGreaterThan(0, 0)).to.be.equal(false) + expect(corbel.validate.isGreaterThan('a', 'b')).to.be.equal(false) + expect(corbel.validate.isGreaterThan('a', 'a')).to.be.equal(false) + expect(corbel.validate.isGreaterThan('A', 'a')).to.be.equal(false) + + expect(corbel.validate.isGreaterThan(1, 0)).to.be.equal(true) + expect(corbel.validate.isGreaterThan('b', 'a')).to.be.equal(true) + expect(corbel.validate.isGreaterThan('a', 'A')).to.be.equal(true) + }) + + it('works with differents type', function () { + expect(corbel.validate.isGreaterThan(0, '1')).to.be.equal(false) + expect(corbel.validate.isGreaterThan(3, '4')).to.be.equal(false) + expect(corbel.validate.isGreaterThan(0, '0')).to.be.equal(false) + expect(corbel.validate.isGreaterThan(0, '0.0')).to.be.equal(false) + expect(corbel.validate.isGreaterThan(1, '1.1')).to.be.equal(false) + expect(corbel.validate.isGreaterThan(1, 'a')).to.be.equal(false) + // @todo: this is pretty bizarre... + expect(corbel.validate.isGreaterThan(555555, 'a')).to.be.equal(false) + + expect(corbel.validate.isGreaterThan(1, '0')).to.be.equal(true) + expect(corbel.validate.isGreaterThan(4, '3')).to.be.equal(true) + expect(corbel.validate.isGreaterThan(4, '3.4')).to.be.equal(true) + }) + + it('can throw custom messages when return value is false', function () { + expect(function () { + corbel.validate.isGreaterThan(0, 1, 'message') + }).to.throw('message') + }) + }) + + describe('corbel.validate.isGreaterThanOrEqual', function () { + it('works with same type', function () { + expect(corbel.validate.isGreaterThanOrEqual(0, 1)).to.be.equal(false) + expect(corbel.validate.isGreaterThanOrEqual('a', 'b')).to.be.equal(false) + expect(corbel.validate.isGreaterThanOrEqual('A', 'a')).to.be.equal(false) + + expect(corbel.validate.isGreaterThanOrEqual(0, 0)).to.be.equal(true) + expect(corbel.validate.isGreaterThanOrEqual('a', 'a')).to.be.equal(true) + expect(corbel.validate.isGreaterThanOrEqual(1, 0)).to.be.equal(true) + expect(corbel.validate.isGreaterThanOrEqual('b', 'a')).to.be.equal(true) + expect(corbel.validate.isGreaterThanOrEqual('a', 'A')).to.be.equal(true) + }) + + it('works with differents type', function () { + expect(corbel.validate.isGreaterThanOrEqual(0, '1')).to.be.equal(false) + expect(corbel.validate.isGreaterThanOrEqual(3, '4')).to.be.equal(false) + expect(corbel.validate.isGreaterThanOrEqual(1, '1.1')).to.be.equal(false) + expect(corbel.validate.isGreaterThanOrEqual(1, 'a')).to.be.equal(false) + expect(corbel.validate.isGreaterThanOrEqual(555555, 'a')).to.be.equal(false) + + expect(corbel.validate.isGreaterThanOrEqual(0, '0')).to.be.equal(true) + expect(corbel.validate.isGreaterThanOrEqual(0, '0.0')).to.be.equal(true) + expect(corbel.validate.isGreaterThanOrEqual(1, '0')).to.be.equal(true) + expect(corbel.validate.isGreaterThanOrEqual(4, '3')).to.be.equal(true) + expect(corbel.validate.isGreaterThanOrEqual(4, '3.4')).to.be.equal(true) + }) + + it('can throw custom messages when return value is false', function () { + expect(function () { + corbel.validate.isGreaterThanOrEqual(0, 1, 'message') + }).to.throw('message') + }) + }) +}) diff --git a/test/node/unit/webfs.js b/test/node/unit/webfs.js index 78b750d..2bd63bb 100644 --- a/test/node/unit/webfs.js +++ b/test/node/unit/webfs.js @@ -1,78 +1,76 @@ -'use strict'; +'use strict' /* jshint camelcase:false */ +/* globals describe it beforeEach afterEach */ -var corbel = require('../../../dist/corbel.js'), - chai = require('chai'), - sinon = require('sinon'), - expect = chai.expect; +var corbel = require('../../../dist/corbel.js') +var chai = require('chai') +var sinon = require('sinon') +var expect = chai.expect -describe('In Webfs module we can', function() { +describe('In Webfs module we can', function () { + var sandbox = sinon.sandbox.create() + var CONFIG = { + clientId: 'clientId', + clientSecret: 'clientSecret', - var sandbox = sinon.sandbox.create(); - var CONFIG = { + scopes: ['silkroad-qa:client', 'resources:send_event_bus', 'resources:test:test_operations', 'resources:music:read_catalog', 'resources:music:streaming'], - clientId: 'clientId', - clientSecret: 'clientSecret', + urlBase: 'https://{{module}}-corbel.io/v1.0/' - scopes: ['silkroad-qa:client', 'resources:send_event_bus', 'resources:test:test_operations', 'resources:music:read_catalog', 'resources:music:streaming'], + } - urlBase: 'https://{{module}}-corbel.io/v1.0/' + var WEBFS_URL = CONFIG.urlBase.replace('{{module}}', 'webfs') + var RESOURCE_ID = 'index.html' - }; + var corbelDriver = corbel.getDriver(CONFIG) - var WEBFS_URL = CONFIG.urlBase.replace('{{module}}', 'webfs'); - var RESOURCE_ID = 'index.html'; + var corbelRequestStub - var corbelDriver = corbel.getDriver(CONFIG); + beforeEach(function () { + corbelRequestStub = sandbox.stub(corbel.request, 'send') + }) - var corbelRequestStub; + afterEach(function () { + sandbox.restore() + }) - beforeEach(function() { - corbelRequestStub = sandbox.stub(corbel.request, 'send'); - }); + it('retrieve a resource from S3', function () { + corbelRequestStub.returns(Promise.resolve('OK')) - afterEach(function() { - sandbox.restore(); - }); + corbelDriver.webfs.webfs(RESOURCE_ID).get() - it('retrieve a resource from S3', function() { - corbelRequestStub.returns(Promise.resolve('OK')); + var callRequestParam = corbelRequestStub.getCall(0).args[0] + expect(callRequestParam).to.have.property('url', WEBFS_URL + RESOURCE_ID) + expect(callRequestParam).to.have.property('method', 'GET') + }) - corbelDriver.webfs.webfs(RESOURCE_ID).get(); + it('retrieve a resource from S3 with specific contentType', function () { + corbelRequestStub.returns(Promise.resolve('OK')) - var callRequestParam = corbelRequestStub.getCall(0).args[0]; - expect(callRequestParam).to.have.property('url', WEBFS_URL + RESOURCE_ID); - expect(callRequestParam).to.have.property('method', 'GET'); - }); + corbelDriver.webfs.webfs(RESOURCE_ID).get({contentType: 'text/xml'}) - it('retrieve a resource from S3 with specific contentType', function() { - corbelRequestStub.returns(Promise.resolve('OK')); + var callRequestParam = corbelRequestStub.getCall(0).args[0] + expect(callRequestParam).to.have.property('url', WEBFS_URL + RESOURCE_ID) + expect(callRequestParam).to.have.property('method', 'GET') + expect(callRequestParam).to.have.property('contentType', 'text/xml') + }) - corbelDriver.webfs.webfs(RESOURCE_ID).get({contentType: 'text/xml'}); + it('retrieve a resource from S3 with specific Accept header', function () { + corbelRequestStub.returns(Promise.resolve('OK')) - var callRequestParam = corbelRequestStub.getCall(0).args[0]; - expect(callRequestParam).to.have.property('url', WEBFS_URL + RESOURCE_ID); - expect(callRequestParam).to.have.property('method', 'GET'); - expect(callRequestParam).to.have.property('contentType', 'text/xml'); - }); + corbelDriver.webfs.webfs(RESOURCE_ID).get({Accept: 'text/xml'}) - it('retrieve a resource from S3 with specific Accept header', function() { - corbelRequestStub.returns(Promise.resolve('OK')); + var callRequestParam = corbelRequestStub.getCall(0).args[0] + expect(callRequestParam).to.have.property('url', WEBFS_URL + RESOURCE_ID) + expect(callRequestParam).to.have.property('method', 'GET') + expect(callRequestParam).to.have.deep.property('headers.Accept', 'text/xml') + }) - corbelDriver.webfs.webfs(RESOURCE_ID).get({Accept: 'text/xml'}); + it('an error is thrown if resourceId is undefined', function () { + corbelRequestStub.returns(Promise.resolve('OK')) - var callRequestParam = corbelRequestStub.getCall(0).args[0]; - expect(callRequestParam).to.have.property('url', WEBFS_URL + RESOURCE_ID); - expect(callRequestParam).to.have.property('method', 'GET'); - expect(callRequestParam).to.have.deep.property('headers.Accept', 'text/xml'); - }); - - it('an error is thrown if resourceId is undefined', function() { - corbelRequestStub.returns(Promise.resolve('OK')); - - expect(function() { - corbelDriver.webfs.webfs().get(); - }).to.throw('id value is mandatory and cannot be undefined'); - }); - -}); + expect(function () { + corbelDriver.webfs.webfs().get() + }).to.throw('id value is mandatory and cannot be undefined') + }) +})