├── .codeclimate.yml ├── .gitignore ├── .jsbeautifyrc ├── .jsdoc ├── .jshintrc ├── .travis.yml ├── CHANGELOG.md ├── Gruntfile.js ├── LICENSE ├── README.md ├── bower.json ├── dist ├── corbel.js ├── corbel.min.js └── corbel.with-polyfills.js ├── examples ├── express │ ├── app.js │ └── res │ │ └── res.json ├── nodeapp │ └── main.js └── webapp │ ├── index.html │ ├── livereload.js │ ├── res │ └── res.json │ └── scripts │ └── main.js ├── package.json ├── sonar-project.properties ├── src ├── assets │ ├── assets-builder.js │ └── assets.js ├── borrow │ ├── borrow.js │ ├── borrowBuilder.js │ ├── lenderBuilder.js │ └── userBuilder.js ├── build │ ├── default.js │ └── with-polyfills.js ├── composr │ ├── composr.js │ ├── phraseBuilder.js │ └── requestBuilder.js ├── config.js ├── corbel.js ├── cryptography.js ├── domain │ └── domain.js ├── ec │ ├── ec.js │ ├── orderBuilder.js │ ├── paymentBuilder.js │ ├── paymentMethodsBuilder.js │ ├── paymentPlanBuilder.js │ ├── productBuilder.js │ └── purchaseBuilder.js ├── evci │ ├── evci.js │ └── eventBuilder.js ├── iam │ ├── clientBuilder.js │ ├── domainBuilder.js │ ├── emailBuilder.js │ ├── groupsBuilder.js │ ├── iam.js │ ├── scopeBuilder.js │ ├── tokenBuilder.js │ ├── usernameBuilder.js │ └── usersBuilder.js ├── jwt.js ├── notifications │ ├── base-notifications.js │ ├── notifications.js │ ├── notificationsBuilder.js │ ├── notificationsDomainBuilder.js │ └── notificationsTemplateBuilder.js ├── oauth │ ├── authorizationBuilder.js │ ├── oauth.js │ ├── tokenBuilder.js │ └── userBuilder.js ├── object.js ├── request-params │ ├── aggregation-builder.js │ ├── page-builder.js │ ├── query-builder.js │ ├── request-params-builder.js │ └── sort-builder.js ├── request.js ├── resources │ ├── base-resource.js │ ├── collection.js │ ├── relation.js │ ├── resource.js │ └── resources.js ├── scheduler │ ├── scheduler.js │ └── schedulerBuilder.js ├── services.js ├── utils.js ├── validate.js └── webfs │ ├── webfs.js │ └── webfsBuilder.js ├── test ├── browser │ ├── index.html │ ├── test-suite.js │ └── unit │ │ ├── request.js │ │ └── resource-binary.js ├── karma.conf.js └── node │ ├── test-suite.js │ └── unit │ ├── assets.js │ ├── baseUrlIntegrity.js │ ├── borrow.js │ ├── composr.js │ ├── config.js │ ├── corbel.js │ ├── domain.js │ ├── ec.js │ ├── evci.js │ ├── iam.js │ ├── jwt.js │ ├── notifications.js │ ├── oauth.js │ ├── request.js │ ├── resources-request-params.js │ ├── resources.js │ ├── scheduler.js │ ├── services.js │ ├── utils.js │ ├── validate.js │ └── webfs.js └── vendor └── sinon-js └── sinon-1.12.2.js /.codeclimate.yml: -------------------------------------------------------------------------------- 1 | languages: 2 | JavaScript: true 3 | exclude_paths: 4 | - test/**/* 5 | - dist/**/* 6 | - vendor/**/* 7 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | examples/webserver/node_modules 3 | bower_components 4 | .tmp 5 | doc 6 | *.log 7 | .storage 8 | *.swp 9 | .idea 10 | .report 11 | corbel-js.iml -------------------------------------------------------------------------------- /.jsbeautifyrc: -------------------------------------------------------------------------------- 1 | { 2 | "html": { 3 | "allowed_file_extensions": ["htm", "html", "xhtml", "shtml", "xml", "svg"], 4 | "brace_style": "collapse", 5 | "end_with_newline": false, 6 | "indent_char": " ", 7 | "indent_handlebars": false, 8 | "indent_inner_html": false, 9 | "indent_scripts": "keep", 10 | "indent_size": 2, 11 | "max_preserve_newlines": 0, 12 | "preserve_newlines": true, 13 | "unformatted": ["a", "span", "img", "code", "pre", "sub", "sup", "em", "strong", "b", "i", "u", "strike", "big", "small", "pre", "h1", "h2", "h3", "h4", "h5", "h6"], 14 | "wrap_line_length": 0 15 | }, 16 | "css": { 17 | "allowed_file_extensions": ["css", "scss", "sass", "less"], 18 | "end_with_newline": false, 19 | "indent_char": " ", 20 | "indent_size": 2, 21 | "newline_between_rules": true, 22 | "selector_separator": " ", 23 | "selector_separator_newline": true 24 | }, 25 | "js": { 26 | "allowed_file_extensions": ["js", "json", "jshintrc", "jsbeautifyrc"], 27 | "brace_style": "collapse", 28 | "break_chained_methods": false, 29 | "e4x": false, 30 | "end_with_newline": false, 31 | "indent_char": " ", 32 | "indent_level": 0, 33 | "indent_size": 2, 34 | "indent_with_tabs": false, 35 | "jslint_happy": false, 36 | "keep_array_indentation": false, 37 | "keep_function_indentation": false, 38 | "max_preserve_newlines": 0, 39 | "preserve_newlines": true, 40 | "space_after_anon_function": false, 41 | "space_before_conditional": true, 42 | "space_in_empty_paren": false, 43 | "space_in_paren": false, 44 | "unescape_strings": false, 45 | "wrap_line_length": 0 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /.jsdoc: -------------------------------------------------------------------------------- 1 | { 2 | "tags": { 3 | "allowUnknownTags" : true 4 | }, 5 | "plugins": ["plugins/markdown"], 6 | "templates": { 7 | "cleverLinks": true, 8 | "monospaceLinks": true, 9 | "default": { 10 | "outputSourceFiles" : true 11 | }, 12 | "applicationName": "corbel-js", 13 | "disqus": "", 14 | "googleAnalytics": "", 15 | "openGraph": { 16 | "title": "", 17 | "type": "website", 18 | "image": "", 19 | "site_name": "", 20 | "url": "" 21 | }, 22 | "meta": { 23 | "title": "corbel-js", 24 | "description": "corbel-js Documentation", 25 | "keyword": "corbel js" 26 | } 27 | }, 28 | "markdown": { 29 | "parser": "gfm", 30 | "hardwrap": true, 31 | "tags": ["examples"] 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /.jshintrc: -------------------------------------------------------------------------------- 1 | { 2 | "node": true, 3 | "browser": true, 4 | "esnext": true, 5 | "bitwise": true, 6 | "camelcase": true, 7 | "curly": true, 8 | "eqeqeq": true, 9 | "immed": true, 10 | "indent": 4, 11 | "latedef": false, 12 | "newcap": true, 13 | "noarg": true, 14 | "quotmark": "single", 15 | "regexp": true, 16 | "undef": true, 17 | "unused": true, 18 | "strict": true, 19 | "trailing": true, 20 | "smarttabs": true, 21 | "jquery": true, 22 | "mocha": true, 23 | "globals": { 24 | "root": true, 25 | "define": true, 26 | "corbel": true, 27 | "expect": true, 28 | "sinon": true, 29 | "mocha": true, 30 | "chai": true 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - 4.2 4 | addons: 5 | code_climate: 6 | repo_token: 9276fd7503bb80c213fca12dc6b11577e4a3d3dd4a1efed4a04d33ffd0d48e4a 7 | before_install: 8 | - npm install -g grunt-cli 9 | - npm install -g codeclimate-test-reporter 10 | before_script: bower install 11 | script: 12 | - grunt test 13 | - grunt coverage:node 14 | - grunt coveralls 15 | after_script: 16 | - codeclimate-test-reporter < .tmp/lcov.info 17 | - ./node_modules/.bin/codacy-coverage < .tmp/lcov.info 18 | sudo: false -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | 2 | # Changelog 3 | 4 | ### v0.6.0 [view commit logs](https://github.com/bq/corbel-js/compare/v0.5.0...v0.6.0) 5 | 6 | #### Features 7 | 8 | - EC admin interface 9 | - Relations now accepts mediaType 10 | 11 | #### Fix 12 | 13 | - React native does not define window.location 14 | - Atob to base 64 15 | - Some browsers not define xhr onLoad onError 16 | 17 | 18 | ### v0.5.0 [view commit logs](https://github.com/bq/corbel-js/compare/v0.4.0...v0.5.0) 19 | 20 | #### Breaking changes 21 | 22 | - [Corbel] Review IAM plural endpoints 23 | - `/sessions` to `/session` 24 | - `/groups` to `/group` 25 | - `/scopes` to `/scope` 26 | - `/devices` to `/device` 27 | 28 | #### Features 29 | 30 | - Iam endpoints with domain parameters 31 | - Adds a util that checks delay between server-client 32 | - Delete endpoint for webfs and path prefix 33 | 34 | #### Fixes 35 | 36 | - fix encoding problem in reset password methods 37 | - changed paymentplan builder 38 | - evci does not return location in header 39 | - fix request without credentials 40 | - Path & Domain order inversion in webfs 41 | 42 | ### v0.4.0 [view commit logs](https://github.com/bq/corbel-js/compare/v0.3.10...v0.4.0) 43 | 44 | #### Breaking changes 45 | 46 | Devices api changes: 47 | * iam.user().registerMyDevice(data) -> iam.user().registerMyDevice(deviceId, data) 48 | * iam.user().registerDevice(data) -> iam.user().registerDevice(deviceId, data) 49 | 50 | update to devices from device endpoint 51 | 52 | #### Features 53 | 54 | * iam get session endpoints 55 | * minification 56 | 57 | ### v0.3.10 [view commit logs](https://github.com/bq/corbel-js/compare/v0.3.9...v0.3.10) 58 | 59 | #### Breaking changes 60 | 61 | Notifications api changes: 62 | * notifications.notification.create -> notifications.template.create 63 | * notifications.notification.get -> notifications.template.get 64 | * notifications.notification.update -> notifications.template.update 65 | * notifications.notification.delete -> notifications.template.delete 66 | * notifications.notification.sendNotification -> notifications.notification.send 67 | 68 | #### Features 69 | 70 | * Added notifications domain interface 71 | 72 | ### v0.3.9 [view commit logs](https://github.com/bq/corbel-js/compare/v0.3.8...v0.3.9) 73 | 74 | #### Feature 75 | 76 | * Updated EC module with payment methods 77 | * Updated lodash 78 | 79 | ### v0.3.8 [view commit logs](https://github.com/bq/corbel-js/compare/v0.3.7...v0.3.8) 80 | 81 | #### Features 82 | * Oauth support updated 83 | 84 | #### Test 85 | * Updated oauth tests 86 | 87 | #### Fix 88 | * Fixes codeclimate build 89 | * Reset password does not return location header 90 | 91 | ### v0.3.7 [view commit logs](https://github.com/bq/corbel-js/compare/v0.3.6...v0.3.7) 92 | 93 | #### Fix 94 | 95 | * Fixes refresh token handler 96 | 97 | ### v0.3.6 [view commit logs](https://github.com/bq/corbel-js/compare/v0.3.5...v0.3.6) 98 | 99 | #### Fix 100 | 101 | * Fixes ftsearch query 102 | 103 | ### v0.3.5 [view commit logs](https://github.com/bq/corbel-js/compare/v0.3.4...v0.3.5) 104 | 105 | #### Features 106 | 107 | * Binaries and blob support 108 | * Get current endpoint function 109 | 110 | ### v0.3.4 [view commit logs](https://github.com/bq/corbel-js/compare/v0.3.3...v0.3.4) 111 | 112 | #### Features 113 | 114 | * Merged with 0.2.X, adds `.domain` implementation 115 | 116 | ### v0.3.3 [view commit logs](https://github.com/bq/corbel-js/compare/v0.3.2...v0.3.3) 117 | 118 | #### Features 119 | 120 | * Refactor to encode query params in SerializeParams function 121 | 122 | ### v0.3.2 [view commit logs](https://github.com/bq/corbel-js/compare/v0.3.0...v0.3.2) 123 | 124 | #### Features 125 | 126 | * Includes updates ACL 127 | * Webfs 128 | 129 | ### v0.3.0 [view commit logs](https://github.com/bq/corbel-js/compare/v0.2.10...v0.3.0) 130 | 131 | #### Features 132 | 133 | * Added `blob`, `dataURI`, `stream` serializers to `request.js` 134 | 135 | ### v0.2.21 [view commit logs](https://github.com/bq/corbel-js/compare/v0.2.10...v0.2.21) 136 | 137 | #### Fixes 138 | 139 | * Fixes bug with encoded urls 140 | * Support requests in IE 141 | * Only 1 token refresh at the time 142 | * Fixed events hashmap 143 | 144 | #### Features 145 | 146 | * Added `.domain` implementation for custom domain requests 147 | 148 | ### v0.2.10 [view commit logs](https://github.com/bq/corbel-js/compare/v0.2.9...v0.2.10) 149 | 150 | #### Features 151 | 152 | * Event handler support `addEventListener/on`, `removeEventListener/off` and `dispatch/trigger` 153 | 154 | 155 | ### v0.2.8 [view commit logs](https://github.com/bq/corbel-js/compare/v0.2.0...v0.2.8) 156 | 157 | #### Breaking changes 158 | 159 | * Assets and notifications' API have changed so now, both modules follow the main syntax 160 | 161 | ``` 162 | corbelDriver.assets(.*).get() -> corbelDriver.assets.asset(.*).get() 163 | corbelDriver.notifications(.*).get() -> corbelDriver.notifications.notification(.*).get() 164 | 165 | ``` 166 | 167 | 168 | ### v0.2.0 [view commit logs](https://github.com/bq/corbel-js/compare/v0.1.2...v0.2.0) 169 | 170 | #### Breaking changes 171 | 172 | * In users in module IAM, the existing methods `sendResetPasswordEmail`, `create`, `get` and `getProfiles` now require the constructor `users()` instead of `user()` 173 | 174 | ``` 175 | corbelDriver.iam.users().create(data) 176 | 177 | ``` 178 | * It's important to note that `get` method exist also with constructor `user()`, but is equivalent to write `user('me')`, and if you had it implemented in previous version, now you must use `users()` 179 | 180 | 181 | ### v0.1.0 [view commit logs](https://github.com/bq/corbel-js/compare/v0.0.10...v0.1.0) 182 | 183 | #### Breaking changes 184 | 185 | * Pagination change in query, `size` renamed to `pageSize` 186 | 187 | ``` 188 | { 189 | pagination : { 190 | page : 1, 191 | pageSize : 10 192 | } 193 | } 194 | 195 | ``` 196 | 197 | #### Fixes 198 | 199 | * Response errornow it responds with an object instead of a string. 200 | 201 | 202 | 203 | 204 | 205 | ## Changelog template 206 | 207 | ### vX.Y.Z [view commit logs](https://github.com/marionettejs/backbone.marionette/compare/vX.Y.Z...vX.Y.[Z-1]) 208 | 209 | #### Breaking changes 210 | 211 | * ... 212 | 213 | #### Fixes 214 | 215 | * ... 216 | 217 | #### Docs 218 | 219 | * ... 220 | 221 | #### Misc 222 | 223 | * ... 224 | -------------------------------------------------------------------------------- /bower.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "corbel-js", 3 | "description": "corbel SDK compatible with browser and nodejs", 4 | "version": "0.6.6", 5 | "main": "dist/corbel.min.js", 6 | "license": "Apache-2.0", 7 | "keywords": [ 8 | "request", 9 | "http", 10 | "ajax", 11 | "cors", 12 | "corbel", 13 | "nodejs", 14 | "resources", 15 | "iam", 16 | "jwt" 17 | ], 18 | "authors": [ 19 | "Daniel García González ", 20 | "Anthanh Pham Trinh <@antaipt>", 21 | "Iván Rodríguez <@ivanrod>", 22 | "Rafael Pedrola Gimeno<@rafinskipg>", 23 | "Francisco Sanchez <@francisco-sanchez-molina>", 24 | "Ismael Madirolas <@ismadirolas>", 25 | "Josep Arpi <@jarpi>", 26 | "Victor Perez Rey <@vipereybq>", 27 | "Ricardo Martinez Calvo <@rmartinezcalvo>", 28 | "Samuel Martin <@samuelmartingc>", 29 | "Laura Sada <@lauritaSada>", 30 | "Rubén Carrasco <@rcfsegovia>", 31 | "Cristian del Cerro <@cristiandelcerro>", 32 | "Alex De Leon <@alexdeleon>" 33 | ], 34 | "homepage": "http://opensource.bq.com/corbel-js/", 35 | "repository": { 36 | "type": "git", 37 | "url": "https://github.com/bq/corbel-js.git" 38 | }, 39 | "ignore": [ 40 | "**/.*", 41 | "node_modules", 42 | "bower_components", 43 | "test", 44 | "tests" 45 | ], 46 | "dependencies": {}, 47 | "devDependencies": { 48 | "mocha": "^2.5.3", 49 | "sinon.js": "sinon-js#^1.15.4", 50 | "chai": "^3.5.0", 51 | "chai-as-promised": "^5.3.0", 52 | "underscore": "^1.8.3", 53 | "jquery": "^2.2.4", 54 | "es6-promise": "^3.2.2" 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /examples/express/app.js: -------------------------------------------------------------------------------- 1 | /* jshint node: true, strict: false */ 2 | 3 | var express = require('express'), 4 | cors = require('cors'), 5 | bodyParser = require('body-parser'), 6 | app = express(); 7 | 8 | var timeout = require('connect-timeout'); 9 | app.use(timeout(10000)); 10 | 11 | // app.use(bodyParser.json()); 12 | 13 | app.use(bodyParser.urlencoded({ 14 | extended: false 15 | })); 16 | 17 | 18 | var corsOptions = { 19 | origin: function(origin, callback) { 20 | callback(null, true); 21 | }, 22 | exposedHeaders: ['location'], 23 | credentials: true 24 | }; 25 | 26 | app.use(cors(corsOptions)); 27 | 28 | app.options('*', cors(corsOptions)); 29 | 30 | var HTTP_VERBS = ['get', 'put', 'post', 'delete', 'head', 'patch']; 31 | 32 | // var CUSTOM_HEADERS = ['X-Custom1', 'X-Custom2']; 33 | // var buildResponse = function(headers, body) { 34 | 35 | 36 | ////////////////////////// 37 | // return response; // 38 | // }; // 39 | // // 40 | ////////////////////////// 41 | 42 | HTTP_VERBS.forEach(function(verb) { 43 | app[verb]('/', function(req, res) { 44 | res.setHeader('location', 'http://domain.com/path/locationId'); 45 | 46 | var headers = req.headers; 47 | var body = req.body; 48 | 49 | var response = { 50 | headers: headers, 51 | body: body 52 | }; 53 | 54 | res.send(response); 55 | }); 56 | 57 | app[verb]('request/fail', function(req, res) { 58 | var headers = req.headers; 59 | var body = req.body; 60 | 61 | var response = { 62 | headers: headers, 63 | body: body 64 | }; 65 | 66 | res.status(404); 67 | res.send(response); 68 | }); 69 | 70 | }); 71 | 72 | 73 | // Since this is the last non-error-handling 74 | // middleware use()d, we assume 404, as nothing else 75 | // responded. 76 | 77 | // $ curl http://localhost:3000/notfound 78 | // $ curl http://localhost:3000/notfound -H "Accept: application/json" 79 | // $ curl http://localhost:3000/notfound -H "Accept: text/plain" 80 | 81 | app.use(function(req, res, next) { 82 | res.status(404); 83 | 84 | // respond with html page 85 | if (req.accepts('html')) { 86 | res.status(404).send('
' + req.url + '
'); 87 | return; 88 | } 89 | 90 | // respond with json 91 | if (req.accepts('json')) { 92 | res.send({ 93 | error: 'Not found' 94 | }); 95 | return; 96 | } 97 | 98 | // default to plain-text. send() 99 | res.type('txt').send('Not found'); 100 | next(); 101 | }); 102 | 103 | 104 | module.exports = app.listen; 105 | module.exports = app.use(function() {}); 106 | -------------------------------------------------------------------------------- /examples/express/res/res.json: -------------------------------------------------------------------------------- 1 | { 2 | "widget": { 3 | "debug": "on", 4 | "window": { 5 | "title": "Sample Konfabulator Widget", 6 | "name": "main_window", 7 | "width": 500, 8 | "height": 500 9 | }, 10 | "image": { 11 | "src": "Images/Sun.png", 12 | "name": "sun1", 13 | "hOffset": 250, 14 | "vOffset": 250, 15 | "alignment": "center" 16 | }, 17 | "text": { 18 | "data": "Click Here", 19 | "size": 36, 20 | "style": "bold", 21 | "name": "text1", 22 | "hOffset": 250, 23 | "vOffset": 100, 24 | "alignment": "center", 25 | "onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;" 26 | } 27 | } 28 | } -------------------------------------------------------------------------------- /examples/nodeapp/main.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | var corbel = require('../../dist/corbel.js'); 3 | 4 | var CONFIG = { 5 | clientId: 'clientId', 6 | clientSecret: 'clientSecret', 7 | 8 | scopes: ['silkroad-qa:client', 'resources:send_event_bus', 'resources:test:test_operations', 'resources:music:read_catalog', 'resources:music:streaming'], 9 | 10 | urlBase: 'https://{{module}}-qa.bqws.io/v1.0/' 11 | }; 12 | 13 | var cd = corbel.getDriver(CONFIG); 14 | 15 | cd.iam.token().create().then(function() { 16 | console.log('ok'); 17 | }).catch(function() { 18 | console.log('error'); 19 | }); 20 | -------------------------------------------------------------------------------- /examples/webapp/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | corbel-js 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 19 | 20 | 21 | 22 | 23 |

corbelJS

24 | 25 |
26 |
27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /examples/webapp/livereload.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bq/corbel-js/00074882676b592d2ac16868279c58b0c4faf1e2/examples/webapp/livereload.js -------------------------------------------------------------------------------- /examples/webapp/res/res.json: -------------------------------------------------------------------------------- 1 | { 2 | "widget": { 3 | "debug": "on", 4 | "window": { 5 | "title": "Sample Konfabulator Widget", 6 | "name": "main_window", 7 | "width": 500, 8 | "height": 500 9 | }, 10 | "image": { 11 | "src": "Images/Sun.png", 12 | "name": "sun1", 13 | "hOffset": 250, 14 | "vOffset": 250, 15 | "alignment": "center" 16 | }, 17 | "text": { 18 | "data": "Click Here", 19 | "size": 36, 20 | "style": "bold", 21 | "name": "text1", 22 | "hOffset": 250, 23 | "vOffset": 100, 24 | "alignment": "center", 25 | "onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;" 26 | } 27 | } 28 | } -------------------------------------------------------------------------------- /examples/webapp/scripts/main.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | (function(corbel) { 4 | 5 | var CONFIG = { 6 | clientId: 'clientId', 7 | clientSecret: 'clientSecret', 8 | scopes: 'scopes1 scopes2', 9 | urlBase: 'https://{{module}}-corbel.io/' 10 | }; 11 | 12 | var cd = corbel.getDriver(CONFIG); 13 | 14 | var TEST_OBJECT = { 15 | test: 'test', 16 | test2: 'test2', 17 | test3: 1, 18 | test4: 1.3, 19 | test5: { 20 | t1: 1.3, 21 | t2: [1, 2, 3.3] 22 | } 23 | }; 24 | var COLLECTION_NAME_CRUD = 'test:CoreJSObjectCrud' + Date.now(); 25 | var resourceId; 26 | 27 | cd.iam.token().create().then(function(response) { 28 | console.log('token.response', response); 29 | 30 | return cd.resources.collection(COLLECTION_NAME_CRUD).add(TEST_OBJECT); 31 | }).then(function(response) { 32 | resourceId = response; 33 | TEST_OBJECT.test6 = true; 34 | TEST_OBJECT.test = 'modified'; 35 | return cd.resources.resource(COLLECTION_NAME_CRUD, resourceId).update(TEST_OBJECT); 36 | }).then(function() { 37 | 38 | $('#test').append(''); 39 | var canvas = document.getElementById('myCanvas'); 40 | var context = canvas.getContext('2d'); 41 | var imageObj = new Image(); 42 | 43 | context.drawImage(imageObj, 0, 0); 44 | var blob = corbel.utils.dataURItoBlob(canvas.toDataURL()); 45 | 46 | return cd.resources.resource(COLLECTION_NAME_CRUD, resourceId).update(blob, { 47 | dataType: 'blob' 48 | }); 49 | 50 | }).then(function() { 51 | return cd.resources.resource(COLLECTION_NAME_CRUD, resourceId).delete({ 52 | dataType: 'image/png' 53 | }); 54 | }).then(function(response) { 55 | console.log('ok', response); 56 | }).catch(function(error) { 57 | console.log('error', error); 58 | }); 59 | 60 | 61 | function readSingleFile(evt) { 62 | //Retrieve the first (and only!) File from the FileList object 63 | var file = evt.target.files[0]; 64 | 65 | if (file) { 66 | console.log('file', file); 67 | 68 | cd.iam.token().create().then(function(response) { 69 | console.log('token.response', response); 70 | 71 | return cd.resources.collection(COLLECTION_NAME_CRUD).add(TEST_OBJECT); 72 | }).then(function(response) { 73 | resourceId = response; 74 | 75 | return cd.resources.resource(COLLECTION_NAME_CRUD, resourceId).update(file, { 76 | dataType: 'blob' 77 | }); 78 | }).then(function() { 79 | return cd.resources.resource(COLLECTION_NAME_CRUD, resourceId).get({ 80 | dataType: 'image/png', 81 | responseType: 'blob' 82 | }); 83 | }).then(function(response) { 84 | var blob = response.xhr.response; 85 | var img = document.createElement('img'); 86 | img.onload = function() { 87 | window.URL.revokeObjectURL(img.src); // Clean up after yourself. 88 | }; 89 | img.src = window.URL.createObjectURL(blob); 90 | document.body.appendChild(img); 91 | }).then(function() { 92 | return cd.resources.resource(COLLECTION_NAME_CRUD, resourceId).delete({ 93 | dataType: 'image/png' 94 | }); 95 | }); 96 | 97 | } else { 98 | console.error('Failed to load file'); 99 | } 100 | } 101 | 102 | $('#fileinput').on('change', readSingleFile); 103 | 104 | })(window.corbel); 105 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "corbel-js", 3 | "description": "corbel SDK compatible with browser and nodejs", 4 | "version": "0.6.6", 5 | "main": "dist/corbel.min.js", 6 | "license": "Apache-2.0", 7 | "keywords": [ 8 | "request", 9 | "http", 10 | "ajax", 11 | "cors", 12 | "corbel", 13 | "nodejs", 14 | "resources", 15 | "iam", 16 | "jwt" 17 | ], 18 | "contributors": [ 19 | "Daniel García González ", 20 | "Anthanh Pham Trinh <@antaipt>", 21 | "Iván Rodríguez <@ivanrod>", 22 | "Rafael Pedrola Gimeno<@rafinskipg>", 23 | "Francisco Sanchez <@francisco-sanchez-molina>", 24 | "Ismael Madirolas <@ismadirolas>", 25 | "Josep Arpi <@jarpi>", 26 | "Victor Perez Rey <@vipereybq>", 27 | "Ricardo Martinez Calvo <@rackdon>", 28 | "Samuel Martin <@samuelmartingc>", 29 | "Laura Sada <@lauritaSada>", 30 | "Rubén Carrasco <@rcfsegovia>", 31 | "Cristian del Cerro <@cristiandelcerro>", 32 | "Alex De Leon <@alexdeleon>" 33 | ], 34 | "homepage": "http://opensource.bq.com/corbel-js/", 35 | "repository": { 36 | "type": "git", 37 | "url": "https://github.com/bq/corbel-js.git" 38 | }, 39 | "bugs": { 40 | "url": "https://github.com/bq/corbel-js/issues" 41 | }, 42 | "directories": { 43 | "example": "examples", 44 | "test": "test" 45 | }, 46 | "engines": { 47 | "node": "~4.2.3" 48 | }, 49 | "dependencies": { 50 | "base-64": "^0.1.0", 51 | "btoa": "1.1.2", 52 | "es6-promise": "3.0.2", 53 | "node-localstorage": "1.1.2", 54 | "request": "^2.72.0" 55 | }, 56 | "devDependencies": { 57 | "blanket": "1.2.1", 58 | "body-parser": "1.14.2", 59 | "bower": "^1.7.7", 60 | "chai": "^3.5.0", 61 | "chai-as-promised": "5.2.0", 62 | "codacy-coverage": "^1.1.3", 63 | "connect": "^3.4.1", 64 | "connect-timeout": "1.7.0", 65 | "cors": "2.7.1", 66 | "express": "^4.13.4", 67 | "grunt": "0.4.5", 68 | "grunt-blanket": "0.0.10", 69 | "grunt-cli": "0.1.13", 70 | "grunt-contrib-clean": "0.7.0", 71 | "grunt-contrib-concat": "0.5.1", 72 | "grunt-contrib-connect": "0.11.2", 73 | "grunt-contrib-copy": "0.8.2", 74 | "grunt-contrib-cssmin": "0.14.0", 75 | "grunt-contrib-jshint": "^0.12.0", 76 | "grunt-contrib-uglify": "^1.0.0", 77 | "grunt-contrib-watch": "0.6.1", 78 | "grunt-coveralls": "1.0.0", 79 | "grunt-exec": "0.4.6", 80 | "grunt-execute": "0.2.2", 81 | "grunt-express": "1.4.1", 82 | "grunt-filerev": "2.3.1", 83 | "grunt-jsbeautifier": "0.2.10", 84 | "grunt-karma": "^0.12.1", 85 | "grunt-line-remover": "0.0.2", 86 | "grunt-mocha-phantomjs": "3.0.0", 87 | "grunt-mocha-test": "0.12.7", 88 | "grunt-open": "0.2.3", 89 | "grunt-parallel": "^0.4.1", 90 | "grunt-preprocess": "5.0.1", 91 | "grunt-release": "0.13.0", 92 | "grunt-requirejs": "0.4.2", 93 | "grunt-usemin": "3.1.1", 94 | "grunt-version-check": "0.3.2", 95 | "i": "^0.3.4", 96 | "jaguarjs-jsdoc": "0.0.1", 97 | "jsdoc": "3.4.0", 98 | "jshint-stylish": "2.1.0", 99 | "karma": "^0.13.9", 100 | "karma-chai-plugins": "^0.6.0", 101 | "karma-chrome-launcher": "0.2.2", 102 | "karma-mocha": "^0.2.0", 103 | "karma-mocha-debug": "^0.1.2", 104 | "karma-mocha-reporter": "^1.0.2", 105 | "karma-phantomjs-launcher": "^1.0.0", 106 | "karma-sinon": "^1.0.4", 107 | "karma-tap-reporter": "0.0.6", 108 | "load-grunt-tasks": "3.4.0", 109 | "lodash": "^4.5.1", 110 | "mocha": "^2.5.3", 111 | "mocha-lcov-reporter": "1.0.0", 112 | "phantomjs-prebuilt": "^2.1.3", 113 | "serve-static": "^1.10.2", 114 | "sinon": "1.17.3", 115 | "travis-cov": "0.2.5", 116 | "underscore": "1.8.3" 117 | }, 118 | "scripts": { 119 | "prepublish": "bower install && grunt dist && git add dist/*", 120 | "test": "node $(which grunt) test:node", 121 | "test:node:debug": "node-debug $(which grunt) test:node", 122 | "test:browser:debug": "node-debug $(which grunt) test:browser", 123 | "clean": "rm -rf node_modules bower_components", 124 | "build": "grunt dist", 125 | "coverage": "grunt coverage:node" 126 | }, 127 | "config": { 128 | "travis-cov": { 129 | "threshold": 80 130 | } 131 | } 132 | } 133 | -------------------------------------------------------------------------------- /sonar-project.properties: -------------------------------------------------------------------------------- 1 | # Required metadata 2 | sonar.projectKey=org.sonarqube:corbel-js 3 | sonar.projectName=Corbel-JS 4 | sonar.projectVersion=0.2.0 5 | 6 | # Comma-separated paths to directories with sources (required) 7 | sonar.sources=src 8 | 9 | # Language 10 | sonar.language=js 11 | 12 | # Encoding of sources files 13 | sonar.sourceEncoding=UTF-8 14 | -------------------------------------------------------------------------------- /src/assets/assets-builder.js: -------------------------------------------------------------------------------- 1 | //@exclude 2 | 'use strict'; 3 | //@endexclude 4 | 5 | (function() { 6 | 7 | /** 8 | * Module for organize user assets 9 | * @exports AssetsBuilder 10 | * @namespace 11 | * @extends corbel.Services 12 | * @memberof corbel.Assets 13 | */ 14 | var AssetsBuilder = corbel.Assets.AssetsBuilder = corbel.Services.inherit({ 15 | 16 | /** 17 | * Creates a new AssetsBuilder 18 | * @memberof corbel.Assets.AssetsBuilder.prototype 19 | * @param {string} id string with the asset id or `all` key 20 | * @return {corbel.Assets.AssetsBuilder} 21 | */ 22 | constructor: function(driver, id) { 23 | this.driver = driver; 24 | this.uri = 'asset'; 25 | this.id = id; 26 | }, 27 | 28 | /** 29 | * Gets my user assets 30 | * @memberof corbel.Assets.AssetsBuilder.prototype 31 | * @param {object} [params] Params of a {@link corbel.request} 32 | * @return {Promise} Promise that resolves with an Asset or rejects with a {@link CorbelError} 33 | */ 34 | get: function(params) { 35 | 36 | var options = params ? corbel.utils.clone(params) : {}; 37 | 38 | var args = corbel.utils.extend(options, { 39 | url: this._buildUri(this.uri, this.id), 40 | method: corbel.request.method.GET, 41 | query: params ? corbel.utils.serializeParams(params) : null 42 | }); 43 | 44 | return this.request(args); 45 | 46 | }, 47 | 48 | /** 49 | * Gets all assets 50 | * @memberof corbel.Assets.AssetsBuilder.prototype 51 | * @param {object} [params] Params of a {@link corbel.request} 52 | * @return {Promise} Promise that resolves with an Asset or rejects with a {@link CorbelError} 53 | */ 54 | getAll: function(params){ 55 | var options = params ? corbel.utils.clone(params) : {}; 56 | 57 | var args = corbel.utils.extend(options, { 58 | url: this._buildUri(this.uri, 'all'), 59 | method: corbel.request.method.GET, 60 | query: params ? corbel.utils.serializeParams(params) : null 61 | }); 62 | return this.request(args); 63 | }, 64 | 65 | /** 66 | * Delete asset 67 | * @memberof corbel.Assets.AssetsBuilder.prototype 68 | * @return {Promise} Promise that resolves to undefined (void) or rejects with a {@link CorbelError} 69 | */ 70 | delete: function() { 71 | corbel.validate.value('id', this.id); 72 | return this.request({ 73 | url: this._buildUri(this.uri, this.id), 74 | method: corbel.request.method.DELETE 75 | }); 76 | }, 77 | 78 | /** 79 | * Creates a new asset 80 | * @memberof corbel.Assets.AssetsBuilder.prototype 81 | * @param {object} data Contains the data of the new asset 82 | * @param {string} data.userId The user id 83 | * @param {string} data.name The asset name 84 | * @param {date} data.expire Expire date 85 | * @param {boolean} data.active If asset is active 86 | * @param {array} data.scopes Scopes of the asset 87 | * @return {Promise} Promise that resolves in the new asset id or rejects with a {@link CorbelError} 88 | */ 89 | create: function(data) { 90 | return this.request({ 91 | url: this._buildUri(this.uri), 92 | method: corbel.request.method.POST, 93 | data: data 94 | }). 95 | then(function(res) { 96 | return corbel.Services.getLocationId(res); 97 | }); 98 | }, 99 | 100 | /** 101 | * Generates a JWT that contains the scopes of the actual user's assets and redirects to iam to upgrade user's token 102 | * @memberof corbel.Assets.AssetsBuilder.prototype 103 | * @return {Promise} Promise that resolves to a redirection to iam/oauth/token/upgrade or rejects with a {@link CorbelError} 104 | */ 105 | access: function(params) { 106 | var args = params ? corbel.utils.clone(params) : {}; 107 | args.url = this._buildUri(this.uri + '/access'); 108 | args.method = corbel.request.method.GET; 109 | args.noRedirect = true; 110 | 111 | var that = this; 112 | 113 | return this.request(args). 114 | then(function(response) { 115 | return that.request({ 116 | noRetry: args.noRetry, 117 | method: corbel.request.method.POST, 118 | contentType: 'application/x-www-form-urlencoded; charset=UTF-8', 119 | data:response.data, 120 | url: response.headers.location 121 | }); 122 | }); 123 | }, 124 | 125 | _buildUri: function(path, id) { 126 | var uri = ''; 127 | var urlBase = this.driver.config.getCurrentEndpoint(corbel.Assets.moduleName, this._buildPort(this.driver.config)); 128 | 129 | uri = urlBase + path; 130 | if (id) { 131 | uri += '/' + id; 132 | } 133 | return uri; 134 | }, 135 | 136 | _buildPort: function(config) { 137 | return config.get('assetsPort', null) || corbel.Assets.defaultPort; 138 | } 139 | 140 | }, { 141 | 142 | /** 143 | * GET constant 144 | * @constant 145 | * @memberof corbel.Assets.AssetsBuilder 146 | * @type {string} 147 | * @default 148 | */ 149 | moduleName: 'assets', 150 | 151 | /** 152 | * Factory 153 | * @memberof corbel.Assets.AssetsBuilder 154 | * @type {string} 155 | * @default 156 | */ 157 | create: function(driver) { 158 | return new corbel.Assets.AssetsBuilder(driver); 159 | } 160 | 161 | }); 162 | 163 | return AssetsBuilder; 164 | 165 | })(); 166 | -------------------------------------------------------------------------------- /src/assets/assets.js: -------------------------------------------------------------------------------- 1 | (function() { 2 | //@exclude 3 | 'use strict'; 4 | //@endexclude 5 | 6 | /** 7 | * An assets API factory 8 | * @exports corbel.Assets 9 | * @namespace 10 | * @extends corbel.Object 11 | * @memberof corbel 12 | */ 13 | corbel.Assets = corbel.Object.inherit({ 14 | 15 | /** 16 | * Creates a new AssetsBuilder 17 | * @memberof corbel.Assets.prototype 18 | * @param {string} id String with the asset id or `all` key 19 | * @return {corbel.Assets.AssetsBuilder} 20 | */ 21 | constructor: function(driver) { 22 | this.driver = driver; 23 | }, 24 | 25 | asset: function(id) { 26 | return new corbel.Assets.AssetsBuilder(this.driver, id); 27 | } 28 | 29 | }, { 30 | 31 | /** 32 | * moduleName constant 33 | * @constant 34 | * @memberof corbel.Assets 35 | * @type {string} 36 | * @default 37 | */ 38 | moduleName: 'assets', 39 | 40 | /** 41 | * defaultPort constant 42 | * @constant 43 | * @memberof corbel.Assets 44 | * @type {Number} 45 | * @default 46 | */ 47 | defaultPort: 8092, 48 | 49 | /** 50 | * AssetsBuilder factory 51 | * @memberof corbel.Assets 52 | * @param {corbel} corbel instance driver 53 | * @return {corbel.Assets.AssetsBuilder} 54 | */ 55 | create: function(driver) { 56 | return new corbel.Assets(driver); 57 | } 58 | 59 | }); 60 | 61 | return corbel.Assets; 62 | 63 | })(); 64 | -------------------------------------------------------------------------------- /src/borrow/borrow.js: -------------------------------------------------------------------------------- 1 | //@exclude 2 | 'use strict'; 3 | //@endexclude 4 | 5 | (function() { 6 | 7 | /** 8 | * A module to make Borrow requests. 9 | * @exports Borrow 10 | * @namespace 11 | * @memberof app.corbel 12 | */ 13 | 14 | corbel.Borrow = corbel.Object.inherit({ 15 | 16 | constructor: function(driver) { 17 | this.driver = driver; 18 | }, 19 | 20 | 21 | 22 | /** 23 | * Create a BorrowBuilder for resource managing requests. 24 | * 25 | * @param {String} id The id of the borrow. 26 | * 27 | * @return {corbel.Borrow.BorrowBuilder} 28 | */ 29 | resource : function(id) { 30 | var resource = new corbel.Borrow.BorrowBuilder(id); 31 | resource.driver = this.driver; 32 | return resource; 33 | }, 34 | 35 | /** 36 | * Create a LenderBuilder for lender managing requests. 37 | * 38 | * @param {String} id The id of the lender. 39 | * 40 | * @return {corbel.Borrow.LenderBuilder} 41 | */ 42 | lender: function(id) { 43 | var lender = new corbel.Borrow.LenderBuilder(id); 44 | lender.driver = this.driver; 45 | return lender; 46 | }, 47 | 48 | /** 49 | * Create a UserBuilder for user managing requests. 50 | * 51 | * @param {String} id The id of the user. 52 | * 53 | * @return {corbel.Borrow.UserBuilder} 54 | */ 55 | user: function(id) { 56 | var user = new corbel.Borrow.UserBuilder(id); 57 | user.driver = this.driver; 58 | return user; 59 | } 60 | 61 | 62 | 63 | 64 | }, { 65 | moduleName: 'borrow', 66 | defaultPort: 8100, 67 | 68 | create: function(driver) { 69 | return new corbel.Borrow(driver); 70 | }, 71 | 72 | _buildUri: function() { 73 | var uri=''; 74 | Array.prototype.slice.call(arguments).forEach(function(argument) { 75 | if (argument){ 76 | uri+= '/' + argument; 77 | } 78 | }); 79 | 80 | var urlBase = this.driver.config.getCurrentEndpoint(corbel.Borrow.moduleName, corbel.Borrow._buildPort(this.driver.config)); 81 | 82 | if (urlBase.slice(-1) === '/') { 83 | urlBase = urlBase.substring(0, urlBase.length - 1); 84 | } 85 | 86 | return urlBase + uri; 87 | }, 88 | 89 | _buildPort: function(config) { 90 | return config.get('borrowPort', null) || corbel.Borrow.defaultPort; 91 | } 92 | }); 93 | 94 | return corbel.Borrow; 95 | 96 | 97 | 98 | 99 | 100 | })(); 101 | -------------------------------------------------------------------------------- /src/borrow/lenderBuilder.js: -------------------------------------------------------------------------------- 1 | //@exclude 2 | 'use strict'; 3 | //@endexclude 4 | 5 | (function() { 6 | 7 | 8 | /** 9 | * A builder for borrowed management requests. 10 | * 11 | * @param {String} id lender ID. 12 | * 13 | * @class 14 | * @memberOf corbel.Borrow.LenderBuilder 15 | */ 16 | corbel.Borrow.LenderBuilder = corbel.Services.inherit({ 17 | 18 | constructor: function(id) { 19 | this.id = id; 20 | this.uri = 'lender'; 21 | }, 22 | /** 23 | * Create a new Lender 24 | * @method 25 | * @memberOf corbel.Borrow.LenderBuilder 26 | * @param {Object} lender The lender data 27 | * @param {String} lender.id The lender name 28 | * @param {String} lender.borrowPeriod The borrow period 29 | * @param {String} lender.freeReturnPeriod Return without use 30 | * @param {String} lender.reservationPeriod Period to apply after wait on queue 31 | * @param {String} lender.maxConcurrentLoansPerUser Number of loans at same time 32 | * @param {String} lender.maxLoansPerUserInMonth Limit number of loans per user 33 | * @param {Object} lender.maxRenewalsPerResource Number of times user can renew his loans 34 | * @param {Object} lender.maxUsersInWaitingQueue Waiting queue size 35 | * @param {Object} lender.priority RENEW or RESERVE 36 | * @return {Promise} A promise with the id of the created loanable resources or fails 37 | * with a {@link corbelError}. 38 | */ 39 | create: function(lender) { 40 | console.log('borrowInterface.lender.create', lender); 41 | return this.request({ 42 | url: this._buildUri(this.uri), 43 | method: corbel.request.method.POST, 44 | data: lender 45 | }).then(function(res) { 46 | return corbel.Services.getLocationId(res); 47 | }); 48 | }, 49 | /** 50 | * Update a Lender. 51 | * 52 | * @method 53 | * @memberOf corbel.Borrow.LenderBuilder 54 | * 55 | * @param {Object} lender The lender data. 56 | * 57 | * @return {Promise} A promise resolves to undefined (void) or fails with a {@link corbelError}. 58 | */ 59 | update: function(lender) { 60 | console.log('borrowInterface.lender.update'); 61 | 62 | return this.request({ 63 | url: this._buildUri(this.uri, this.id), 64 | method: corbel.request.method.PUT, 65 | data: lender 66 | }); 67 | }, 68 | /** 69 | * Delete a Lender. 70 | * 71 | * @method 72 | * @memberOf corbel.Borrow.LenderBuilder 73 | * 74 | * @return {Promise} A promise resolves to undefined (void) or fails with a {@link corbelError}. 75 | */ 76 | delete: function() { 77 | console.log('borrowInterface.lender.delete'); 78 | 79 | return this.request({ 80 | url: this._buildUri(this.uri, this.id), 81 | method: corbel.request.method.DELETE 82 | }); 83 | }, 84 | /** 85 | * Get Lender. 86 | * 87 | * @method 88 | * @memberOf corbel.Borrow.LenderBuilder 89 | * 90 | * @return {Promise} A promise with lender {Object} or fails with a {@link corbelError}. 91 | */ 92 | get: function() { 93 | console.log('borrowInterface.lender.get'); 94 | 95 | return this.request({ 96 | url: this._buildUri(this.uri, this.id), 97 | method: corbel.request.method.GET 98 | }); 99 | }, 100 | /** 101 | * Get all Lenders. 102 | * 103 | * @method 104 | * @memberOf corbel.Borrow.LenderBuilder 105 | * 106 | * @return {Promise} A promise with all lenders {Object} or fails with a {@link corbelError}. 107 | */ 108 | getAll: function(params) { 109 | console.log('borrowInterface.lender.getAll'); 110 | return this.request({ 111 | url: this._buildUri(this.uri, 'all'), 112 | method: corbel.request.method.GET, 113 | query: params ? corbel.utils.serializeParams(params) : null 114 | }); 115 | }, 116 | /** 117 | * Get all reservations by lender. 118 | * 119 | * @method 120 | * @memberOf corbel.Borrow.LenderBuilder 121 | * 122 | * @return {Promise} A promise with all reservations {Object} by lender or fails with a {@link corbelError}. 123 | */ 124 | getAllReservations: function(params) { 125 | console.log('borrowInterface.lender.getAllReservations'); 126 | return this.request({ 127 | url: this._buildUri(this.uri, 'reservation'), 128 | method: corbel.request.method.GET, 129 | query: params ? corbel.utils.serializeParams(params) : null 130 | }); 131 | }, 132 | 133 | _buildUri: corbel.Borrow._buildUri 134 | }); 135 | })(); 136 | -------------------------------------------------------------------------------- /src/borrow/userBuilder.js: -------------------------------------------------------------------------------- 1 | //@exclude 2 | 'use strict'; 3 | //@endexclude 4 | 5 | (function() { 6 | 7 | 8 | /** 9 | * A builder for borrowed management requests. 10 | * 11 | * @param {String} id user ID. 12 | * 13 | * @class 14 | * @memberOf corbel.Borrow.UserBuilder 15 | */ 16 | corbel.Borrow.UserBuilder = corbel.Services.inherit({ 17 | 18 | constructor: function(id) { 19 | this.id = id || 'me'; 20 | this.uri = 'user'; 21 | }, 22 | /** 23 | * Get all reservations of a user. 24 | * 25 | * @method 26 | * @memberOf corbel.Borrow.UserBuilder 27 | * 28 | * @return {Promise} A promise with all user reservations {Object} or fails with a {@link corbelError}. 29 | */ 30 | getAllReservations: function() { 31 | console.log('borrowInterface.user.getAllReservations', this.id); 32 | return this.request({ 33 | url: this._buildUri(this.uri ,this.id, 'reservation'), 34 | method: corbel.request.method.GET 35 | }); 36 | }, 37 | /** 38 | * Get all loans of a user. 39 | * 40 | * @method 41 | * @memberOf corbel.Borrow.UserBuilder 42 | * 43 | * @return {Promise} A promise with all user loans {Object} or fails with a {@link corbelError}. 44 | */ 45 | getAllLoans: function() { 46 | console.log('borrowInterface.user.getAllLoans', this.id); 47 | return this.request({ 48 | url: this._buildUri(this.uri ,this.id, 'loan'), 49 | method: corbel.request.method.GET 50 | }); 51 | }, 52 | 53 | 54 | _buildUri: corbel.Borrow._buildUri 55 | }); 56 | })(); 57 | -------------------------------------------------------------------------------- /src/build/default.js: -------------------------------------------------------------------------------- 1 | (function(root, factory) { 2 | 'use strict'; 3 | /* jshint unused: false */ 4 | 5 | if (typeof define === 'function' && define.amd) { 6 | define([], function() { 7 | return factory(root); 8 | }); 9 | } else if (typeof module !== 'undefined' && module.exports) { 10 | module.exports = factory.call(root, root, process || undefined); 11 | } else if (root !== undefined) { 12 | root.corbel = factory(root); 13 | } 14 | 15 | })(this, function(root, process) { 16 | 'use strict'; 17 | /* jshint unused: false */ 18 | 19 | /** 20 | * corbel namespace 21 | * @exports corbel 22 | * @namespace 23 | */ 24 | var corbel = {}; 25 | 26 | //-----------Utils and libraries (exports into corbel namespace)--------------------------- 27 | 28 | // @include ../corbel.js 29 | 30 | // @include ../utils.js 31 | 32 | // @include ../validate.js 33 | 34 | // @include ../object.js 35 | 36 | // @include ../cryptography.js 37 | 38 | // @include ../jwt.js 39 | 40 | // @include ../request.js 41 | 42 | // @include ../services.js 43 | 44 | //----------corbel modules---------------- 45 | 46 | // @include ../config.js 47 | // @include ../iam/iam.js 48 | // @include ../iam/clientBuilder.js 49 | // @include ../iam/domainBuilder.js 50 | // @include ../iam/scopeBuilder.js 51 | // @include ../iam/tokenBuilder.js 52 | // @include ../iam/usernameBuilder.js 53 | // @include ../iam/usersBuilder.js 54 | // @include ../iam/groupsBuilder.js 55 | // @include ../iam/emailBuilder.js 56 | // @include ../request-params/aggregation-builder.js 57 | // @include ../request-params/query-builder.js 58 | // @include ../request-params/page-builder.js 59 | // @include ../request-params/sort-builder.js 60 | // @include ../request-params/request-params-builder.js 61 | // @include ../assets/assets.js 62 | // @include ../assets/assets-builder.js 63 | // @include ../scheduler/scheduler.js 64 | // @include ../scheduler/schedulerBuilder.js 65 | // @include ../resources/resources.js 66 | // @include ../resources/base-resource.js 67 | // @include ../resources/relation.js 68 | // @include ../resources/collection.js 69 | // @include ../resources/resource.js 70 | // @include ../oauth/oauth.js 71 | // @include ../oauth/authorizationBuilder.js 72 | // @include ../oauth/tokenBuilder.js 73 | // @include ../oauth/userBuilder.js 74 | // @include ../notifications/notifications.js 75 | // @include ../notifications/base-notifications.js 76 | // @include ../notifications/notificationsBuilder.js 77 | // @include ../notifications/notificationsTemplateBuilder.js 78 | // @include ../notifications/notificationsDomainBuilder.js 79 | // @include ../ec/ec.js 80 | // @include ../ec/orderBuilder.js 81 | // @include ../ec/paymentBuilder.js 82 | // @include ../ec/paymentMethodsBuilder.js 83 | // @include ../ec/paymentPlanBuilder.js 84 | // @include ../ec/productBuilder.js 85 | // @include ../ec/purchaseBuilder.js 86 | // @include ../evci/evci.js 87 | // @include ../evci/eventBuilder.js 88 | // @include ../borrow/borrow.js 89 | // @include ../borrow/borrowBuilder.js 90 | // @include ../borrow/userBuilder.js 91 | // @include ../borrow/lenderBuilder.js 92 | // @include ../composr/composr.js 93 | // @include ../composr/phraseBuilder.js 94 | // @include ../composr/requestBuilder.js 95 | // @include ../webfs/webfs.js 96 | // @include ../webfs/webfsBuilder.js 97 | // @include ../domain/domain.js 98 | 99 | return corbel; 100 | }); 101 | -------------------------------------------------------------------------------- /src/build/with-polyfills.js: -------------------------------------------------------------------------------- 1 | (function(root, factory) { 2 | 'use strict'; 3 | /* jshint unused: false */ 4 | 5 | if (typeof define === 'function' && define.amd) { 6 | define(['es6-promise'], function(promise) { 7 | promise.polyfill(); 8 | return factory(root); 9 | }); 10 | } else if (typeof module !== 'undefined' && module.exports) { 11 | var Promise = require('es6-promise').polyfill(); 12 | module.exports = factory.call(root); 13 | } else if (window !== undefined) { 14 | if (root.ES6Promise !== undefined && typeof root.ES6Promise.polyfill === 'function') { 15 | root.ES6Promise.polyfill(); 16 | } 17 | root.corbel = factory(root); 18 | } 19 | 20 | 21 | })(this, function(root) { 22 | 'use strict'; 23 | /* jshint unused: false */ 24 | 25 | // @include ../../bower_components/es6-promise/promise.js 26 | 27 | /** 28 | * corbel namespace 29 | * @exports corbel 30 | * @namespace 31 | */ 32 | var corbel = {}; 33 | 34 | //-----------Utils and libraries (exports into corbel namespace)--------------------------- 35 | 36 | // @include ../corbel.js 37 | 38 | // @include ../utils.js 39 | 40 | // @include ../validate.js 41 | 42 | // @include ../object.js 43 | 44 | // @include ../cryptography.js 45 | 46 | // @include ../jwt.js 47 | 48 | // @include ../request.js 49 | 50 | // @include ../services.js 51 | 52 | //----------corbel modules---------------- 53 | 54 | // @include ../config.js 55 | // @include ../iam/iam.js 56 | // @include ../iam/clientBuilder.js 57 | // @include ../iam/domainBuilder.js 58 | // @include ../iam/scopeBuilder.js 59 | // @include ../iam/tokenBuilder.js 60 | // @include ../iam/usernameBuilder.js 61 | // @include ../iam/usersBuilder.js 62 | // @include ../iam/groupsBuilder.js 63 | // @include ../iam/emailBuilder.js 64 | // @include ../assets/assets.js 65 | // @include ../assets/assets-builder.js 66 | // @include ../scheduler/scheduler.js 67 | // @include ../scheduler/schedulerBuilder.js 68 | // @include ../request-params/aggregation-builder.js 69 | // @include ../request-params/query-builder.js 70 | // @include ../request-params/page-builder.js 71 | // @include ../request-params/sort-builder.js 72 | // @include ../request-params/request-params-builder.js 73 | // @include ../resources/resources.js 74 | // @include ../resources/base-resource.js 75 | // @include ../resources/relation.js 76 | // @include ../resources/collection.js 77 | // @include ../resources/resource.js 78 | // @include ../oauth/oauth.js 79 | // @include ../oauth/authorizationBuilder.js 80 | // @include ../oauth/tokenBuilder.js 81 | // @include ../oauth/userBuilder.js 82 | // @include ../notifications/notifications.js 83 | // @include ../notifications/base-notifications.js 84 | // @include ../notifications/notificationsBuilder.js 85 | // @include ../notifications/notificationsDomainBuilder.js 86 | // @include ../notifications/notificationsTemplateBuilder.js 87 | // @include ../ec/ec.js 88 | // @include ../ec/orderBuilder.js 89 | // @include ../ec/productBuilder.js 90 | // @include ../evci/evci.js 91 | // @include ../evci/eventBuilder.js 92 | // @include ../borrow/borrow.js 93 | // @include ../borrow/borrowBuilder.js 94 | // @include ../borrow/userBuilder.js 95 | // @include ../borrow/lenderBuilder.js 96 | // @include ../composr/composr.js 97 | // @include ../composr/phraseBuilder.js 98 | // @include ../composr/requestBuilder.js 99 | // @include ../webfs/webfs.js 100 | // @include ../webfs/webfsBuilder.js 101 | // @include ../domain/domain.js 102 | 103 | return corbel; 104 | }); 105 | -------------------------------------------------------------------------------- /src/composr/composr.js: -------------------------------------------------------------------------------- 1 | //@exclude 2 | 'use strict'; 3 | //@endexclude 4 | 5 | (function() { 6 | 7 | /** 8 | * A module to make CompoSR requests. 9 | * @exports CompoSR 10 | * @namespace 11 | * @memberof app.corbel 12 | */ 13 | 14 | corbel.CompoSR = corbel.Object.inherit({ 15 | 16 | constructor: function(driver) { 17 | this.driver = driver; 18 | }, 19 | 20 | /** 21 | * Create a PhraseBuilder for phrase managing requests. 22 | * 23 | * @param {String} id The id of the phrase. 24 | * 25 | * @return {corbel.CompoSR.PhraseBuilder} 26 | */ 27 | phrase: function(id) { 28 | var phraseBuilder = new corbel.CompoSR.PhraseBuilder(id); 29 | phraseBuilder.driver = this.driver; 30 | return phraseBuilder; 31 | }, 32 | 33 | /** 34 | * Create a RequestBuilder for phrase requests. 35 | * 36 | * @param {String} id phrase id 37 | * @param {String} param1 path parameter 38 | * @param {String} param2 path parameter 39 | * @param {String} paramN path parameter 40 | * 41 | * @return {corbel.CompoSR.RequestBuilder} 42 | */ 43 | request: function() { 44 | var requestBuilder = new corbel.CompoSR.RequestBuilder(Array.prototype.slice.call(arguments)); 45 | requestBuilder.driver = this.driver; 46 | return requestBuilder; 47 | } 48 | 49 | 50 | }, { 51 | 52 | moduleName: 'composr', 53 | defaultPort: 3000, 54 | 55 | create: function(driver) { 56 | return new corbel.CompoSR(driver); 57 | }, 58 | 59 | _buildPort: function(config) { 60 | return config.get('composrPort', null) || corbel.CompoSR.defaultPort; 61 | }, 62 | 63 | _buildUri: function() { 64 | var urlBase = this.driver.config.getCurrentEndpoint(corbel.CompoSR.moduleName, corbel.CompoSR._buildPort(this.driver.config)); 65 | 66 | if (urlBase.slice(-1) === '/') { 67 | urlBase = urlBase.substring(0, urlBase.length - 1); 68 | } 69 | 70 | var uri = ''; 71 | Array.prototype.slice.call(arguments).forEach(function(argument) { 72 | if (argument) { 73 | uri += '/' + argument; 74 | } 75 | }); 76 | return urlBase + uri; 77 | } 78 | 79 | }); 80 | 81 | return corbel.CompoSR; 82 | 83 | })(); 84 | -------------------------------------------------------------------------------- /src/composr/phraseBuilder.js: -------------------------------------------------------------------------------- 1 | //@exclude 2 | 'use strict'; 3 | //@endexclude 4 | 5 | (function() { 6 | 7 | 8 | /** 9 | * A builder for composr phrase crud. 10 | * 11 | * @param {String} id phrase ID. 12 | * 13 | * @class 14 | * @memberOf corbel.CompoSR.PhraseBuilder 15 | */ 16 | corbel.CompoSR.PhraseBuilder = corbel.Services.inherit({ 17 | 18 | constructor: function(id) { 19 | this.id = id; 20 | }, 21 | 22 | put: function(body) { 23 | console.log('composrInterface.phrase.add'); 24 | 25 | return this.request({ 26 | url: this._buildUri('phrase', this.id), 27 | method: corbel.request.method.PUT, 28 | data: body 29 | }); 30 | }, 31 | 32 | get: function() { 33 | console.log('composrInterface.phrase.get'); 34 | corbel.validate.value('id', this.id); 35 | 36 | return this.request({ 37 | url: this._buildUri('phrase', this.id), 38 | method: corbel.request.method.GET 39 | }); 40 | }, 41 | 42 | getAll: function() { 43 | console.log('composrInterface.phrase.getAll'); 44 | return this.request({ 45 | url: this._buildUri('phrase'), 46 | method: corbel.request.method.GET 47 | }); 48 | }, 49 | 50 | delete: function() { 51 | console.log('composrInterface.phrase.delete'); 52 | corbel.validate.value('id', this.id); 53 | 54 | return this.request({ 55 | url: this._buildUri('phrase', this.id), 56 | method: corbel.request.method.DELETE 57 | }); 58 | }, 59 | 60 | _buildUri: corbel.CompoSR._buildUri 61 | 62 | }); 63 | })(); 64 | -------------------------------------------------------------------------------- /src/composr/requestBuilder.js: -------------------------------------------------------------------------------- 1 | //@exclude 2 | 'use strict'; 3 | //@endexclude 4 | 5 | (function() { 6 | 7 | 8 | /** 9 | * A builder for composr requests. 10 | * 11 | * 12 | * @class 13 | * @memberOf corbel.CompoSR.RequestBuilder 14 | */ 15 | corbel.CompoSR.RequestBuilder = corbel.Services.inherit({ 16 | 17 | constructor: function(pathsArray) { 18 | this.path = this.buildPath(pathsArray); 19 | }, 20 | 21 | post: function(data, options) { 22 | console.log('composrInterface.request.post'); 23 | this.options = options || {}; 24 | return this.request({ 25 | url: this._buildUri(this.path), 26 | method: corbel.request.method.POST, 27 | headers: this.options.headers, 28 | data: data, 29 | query: this.buildQueryPath(this.options.queryParams) 30 | }); 31 | }, 32 | 33 | get: function(options) { 34 | console.log('composrInterface.request.get'); 35 | this.options = options || {}; 36 | return this.request({ 37 | url: this._buildUri(this.path), 38 | method: corbel.request.method.GET, 39 | headers: this.options.headers, 40 | query: this.buildQueryPath(this.options.queryParams) 41 | }); 42 | }, 43 | 44 | put: function(data, options) { 45 | console.log('composrInterface.request.put'); 46 | this.options = options || {}; 47 | return this.request({ 48 | url: this._buildUri(this.path), 49 | method: corbel.request.method.PUT, 50 | data: data, 51 | headers: this.options.headers, 52 | query: this.buildQueryPath(this.options.queryParams) 53 | }); 54 | }, 55 | 56 | delete: function(options) { 57 | console.log('composrInterface.request.delete'); 58 | this.options = options || {}; 59 | return this.request({ 60 | url: this._buildUri(this.path), 61 | method: corbel.request.method.DELETE, 62 | headers: this.options.headers, 63 | query: this.buildQueryPath(this.options.queryParams) 64 | }); 65 | }, 66 | 67 | buildPath: function(pathArray) { 68 | var path = ''; 69 | path += pathArray.shift(); 70 | pathArray.forEach(function(entryPath) { 71 | path += '/' + entryPath; 72 | }); 73 | return path; 74 | }, 75 | 76 | buildQueryPath: function(dict) { 77 | var query = ''; 78 | if (dict) { 79 | var queries = []; 80 | Object.keys(dict).forEach(function(key) { 81 | queries.push(key + '=' + dict[key]); 82 | }); 83 | if (queries.length > 0) { 84 | query = queries.join('&'); 85 | } 86 | } 87 | return query; 88 | }, 89 | 90 | _buildUri: corbel.CompoSR._buildUri 91 | }); 92 | })(); 93 | -------------------------------------------------------------------------------- /src/config.js: -------------------------------------------------------------------------------- 1 | //@exclude 2 | 'use strict'; 3 | 4 | /* globals corbel */ 5 | 6 | //@endexclude 7 | 8 | function Config(config) { 9 | config = config || {}; 10 | // config default values 11 | this.config = {}; 12 | 13 | corbel.utils.extend(this.config, config); 14 | } 15 | 16 | Config.URL_BASE_PLACEHOLDER = '{{module}}'; 17 | Config.URL_BASE_PORT_PLACEHOLDER = '{{modulePort}}'; 18 | 19 | corbel.Config = Config; 20 | 21 | var processExist = function(){ 22 | return typeof(process) !== 'undefined' || {}.toString.call(process) === '[object process]'; 23 | }; 24 | 25 | 26 | if (typeof module !== 'undefined' && module.exports && processExist() && typeof window === 'undefined' ) { 27 | Config.__env__ = process.env.NODE_ENV === 'browser' ? 'browser' : 'node'; 28 | } else { 29 | Config.__env__ = 'browser'; 30 | } 31 | 32 | 33 | Config.isNode = Config.__env__ === 'node'; 34 | 35 | Config.isBrowser = Config.__env__ === 'browser'; 36 | 37 | /** 38 | * Client type 39 | * @type {String} 40 | * @default 41 | */ 42 | Config.clientType = Config.isNode ? 'NODE' : 'WEB'; 43 | 44 | if (Config.isNode || !window.location) { 45 | Config.wwwRoot = 'localhost'; 46 | } else { 47 | Config.wwwRoot = window.location.protocol + '//' + window.location.host + window.location.pathname; 48 | } 49 | 50 | /** 51 | * Returns all application config params 52 | * @return {Object} 53 | */ 54 | Config.create = function(config) { 55 | return new Config(config); 56 | }; 57 | 58 | /** 59 | * Returns all application config params 60 | * @return {Object} 61 | */ 62 | Config.prototype.getConfig = function() { 63 | return this.config; 64 | }; 65 | 66 | /** 67 | * Overrides current config with params object config 68 | * @param {Object} config An object with params to set as new config 69 | */ 70 | Config.prototype.setConfig = function(config) { 71 | this.config = corbel.utils.extend(this.config, config); 72 | return this; 73 | }; 74 | 75 | /** 76 | * Gets a specific config param 77 | * @param {String} field config param name 78 | * @param {Mixed} defaultValue Default value if undefined 79 | * @return {Mixed} 80 | */ 81 | Config.prototype.get = function(field, defaultValue) { 82 | if (this.config[field] === undefined) { 83 | if (defaultValue === undefined) { 84 | throw new Error('config:undefined:' + field + ''); 85 | } else { 86 | return defaultValue; 87 | } 88 | } 89 | 90 | return this.config[field]; 91 | }; 92 | 93 | Config.prototype.getCurrentEndpoint = function(moduleName, port){ 94 | var moduleEndpoint = moduleName + 'Endpoint'; 95 | var endpoint = this.get(moduleEndpoint, null) ? 96 | this.get(moduleEndpoint) : 97 | this.get('urlBase'); 98 | endpoint = endpoint.replace(corbel.Config.URL_BASE_PLACEHOLDER, moduleName); 99 | if (port) { 100 | endpoint = endpoint.replace(corbel.Config.URL_BASE_PORT_PLACEHOLDER, port); 101 | } 102 | return endpoint; 103 | }; 104 | 105 | 106 | /** 107 | * Sets a new value for specific config param 108 | * @param {String} field Config param name 109 | * @param {Mixed} value Config param value 110 | */ 111 | Config.prototype.set = function(field, value) { 112 | this.config[field] = value; 113 | }; 114 | -------------------------------------------------------------------------------- /src/corbel.js: -------------------------------------------------------------------------------- 1 | //@exclude 2 | 'use strict'; 3 | //@endexclude 4 | 5 | (function() { 6 | 7 | /** 8 | * @namespace 9 | * @memberOf corbel 10 | * @param {object} config 11 | * @return {CorbelDriver} 12 | */ 13 | function CorbelDriver(config, events) { 14 | 15 | if (events && typeof events === 'object'){ 16 | this._events = corbel.utils.clone(events); 17 | }else{ 18 | this._events = {}; 19 | } 20 | // create instance config 21 | this.guid = corbel.utils.guid(); 22 | this.config = corbel.Config.create(config); 23 | 24 | // create isntance modules with injected driver 25 | this.iam = corbel.Iam.create(this); 26 | this.resources = corbel.Resources.create(this); 27 | this.assets = corbel.Assets.create(this); 28 | this.oauth = corbel.Oauth.create(this); 29 | this.notifications = corbel.Notifications.create(this); 30 | this.ec = corbel.Ec.create(this); 31 | this.evci = corbel.Evci.create(this); 32 | this.borrow = corbel.Borrow.create(this); 33 | this.composr = corbel.CompoSR.create(this); 34 | this.scheduler = corbel.Scheduler.create(this); 35 | this.webfs = corbel.Webfs.create(this); 36 | this.domain = corbel.Domain.create(this); 37 | } 38 | 39 | /** 40 | * @return {CorbelDriver} A new instance of corbel driver with the same config 41 | */ 42 | CorbelDriver.prototype.clone = function() { 43 | return new CorbelDriver(this.config.getConfig(), this._events); 44 | }; 45 | 46 | /** 47 | * Adds an event handler for especific event 48 | * @param {string} name Event name 49 | * @param {Function} fn Function to call 50 | */ 51 | CorbelDriver.prototype.addEventListener = function(name, fn) { 52 | if (typeof fn !== 'function') { 53 | throw new Error('corbel:error:invalid:type'); 54 | } 55 | this._events[name] = this._events[name] || []; 56 | if (this._events[name].indexOf(fn) === -1) { 57 | this._events[name].push(fn); 58 | } 59 | }; 60 | 61 | /** 62 | * Removes the handler from event list 63 | * @param {string} name Event name 64 | * @param {Function} fn Function to remove 65 | */ 66 | CorbelDriver.prototype.removeEventListener = function(name, fn) { 67 | if (this._events[name]) { 68 | var index = this._events[name].indexOf(fn); 69 | if (index !== -1) { 70 | this._events[name].splice(index, 1); 71 | } 72 | } 73 | }; 74 | 75 | /** 76 | * Fires all events handlers for an specific event name 77 | * @param {string} name Event name 78 | * @param {Mixed} options Data for event handlers 79 | */ 80 | CorbelDriver.prototype.dispatch = function(name, options) { 81 | if (this._events[name] && this._events[name].length) { 82 | this._events[name].forEach(function(fn) { 83 | fn(options); 84 | }); 85 | } 86 | }; 87 | 88 | /** 89 | * Adds an event handler for especific event 90 | * @see CorbelDriver.prototype.addEventListener 91 | * @param {string} name Event name 92 | * @param {Function} fn Function to call 93 | */ 94 | CorbelDriver.prototype.on = CorbelDriver.prototype.addEventListener; 95 | 96 | /** 97 | * Removes the handler from event list 98 | * @see CorbelDriver.prototype.removeEventListener 99 | * @param {string} name Event name 100 | * @param {Function} fn Function to remove 101 | */ 102 | CorbelDriver.prototype.off = CorbelDriver.prototype.removeEventListener; 103 | 104 | /** 105 | * Fires all events handlers for an specific event name 106 | * @see CorbelDriver.prototype.dispatch 107 | * @param {string} name Event name 108 | * @param {Mixed} options Data for event handlers 109 | */ 110 | CorbelDriver.prototype.trigger = CorbelDriver.prototype.dispatch; 111 | 112 | corbel.CorbelDriver = CorbelDriver; 113 | 114 | /** 115 | * Instanciates new corbel driver 116 | * @memberOf corbel 117 | * @param {object} config 118 | * @param {string} config.urlBase 119 | * @param {string} [config.clientId] 120 | * @param {string} [config.clientSecret] 121 | * @param {string} [config.scopes] 122 | * @return {corbel.CorbelDriver} 123 | */ 124 | corbel.getDriver = function(config) { 125 | config = config || {}; 126 | 127 | if (!config.urlBase) { 128 | throw new Error('error:undefined:urlbase'); 129 | } 130 | 131 | return new CorbelDriver(config); 132 | }; 133 | 134 | })(); 135 | -------------------------------------------------------------------------------- /src/domain/domain.js: -------------------------------------------------------------------------------- 1 | (function() { 2 | //@exclude 3 | 'use strict'; 4 | //@endexclude 5 | 6 | /** 7 | * A custom domain configuration 8 | * @exports corbel.Domain 9 | * @namespace 10 | * @extends corbel.Object 11 | * @memberof corbel 12 | */ 13 | corbel.Domain = corbel.Object.inherit({ 14 | 15 | /** 16 | * Creates a new instance of corbelDriver with a custom domain 17 | * @memberof corbel.Domain.prototype 18 | * @param {string} id String with the custom domain value 19 | * @return {corbelDriver} 20 | */ 21 | constructor: function(driver) { 22 | this.driver = driver; 23 | 24 | return function(id) { 25 | driver.config.set(corbel.Domain.CUSTOM_DOMAIN, id); 26 | 27 | return driver; 28 | }; 29 | } 30 | 31 | 32 | }, { 33 | 34 | /** 35 | * moduleName constant 36 | * @constant 37 | * @memberof corbel.Domain 38 | * @type {string} 39 | * @default 40 | */ 41 | moduleName: 'domain', 42 | 43 | /** 44 | * customDomain constant 45 | * @constant 46 | * @memberof corbel.Domain 47 | * @type {Number} 48 | * @default 49 | */ 50 | CUSTOM_DOMAIN: 'customDomain', 51 | 52 | /** 53 | * Domain factory 54 | * @memberof corbel.Domain 55 | * @param {corbel} corbel instance driver 56 | * @return {function} 57 | */ 58 | create: function(driver) { 59 | return new corbel.Domain(driver); 60 | } 61 | 62 | }); 63 | 64 | return corbel.Domain; 65 | 66 | })(); 67 | -------------------------------------------------------------------------------- /src/ec/ec.js: -------------------------------------------------------------------------------- 1 | //@exclude 2 | 'use strict'; 3 | //@endexclude 4 | 5 | (function () { 6 | 7 | /** 8 | * A module to make Ec requests. 9 | * @exports Ec 10 | * @namespace 11 | * @memberof app.corbel 12 | */ 13 | 14 | var Ec = corbel.Ec = function (driver) { 15 | this.driver = driver; 16 | }; 17 | 18 | Ec.moduleName = 'ec'; 19 | Ec.defaultPort = 8088; 20 | 21 | Ec.create = function (driver) { 22 | return new Ec(driver); 23 | }; 24 | 25 | Ec._ec = { 26 | /** 27 | * @namespace 28 | */ 29 | purchaseStates: { 30 | /** 31 | * IN_PROCESS constant 32 | * @constant 33 | * @type {String} 34 | * @default 35 | */ 36 | IN_PROCESS: 'IN_PROCESS', 37 | 38 | /** 39 | * COMPLETED constant 40 | * @constant 41 | * @type {String} 42 | * @default 43 | */ 44 | COMPLETED: 'COMPLETED', 45 | 46 | /** 47 | * FAILED constant 48 | * @constant 49 | * @type {String} 50 | * @default 51 | */ 52 | FAILED: 'FAILED', 53 | 54 | /** 55 | * IN_PAYMENT constant 56 | * @constant 57 | * @type {String} 58 | * @default 59 | */ 60 | IN_PAYMENT: 'IN_PAYMENT', 61 | 62 | /** 63 | * CANCELLED constant 64 | * @constant 65 | * @type {String} 66 | * @default 67 | */ 68 | CANCELLED: 'CANCELLED' 69 | } 70 | }; 71 | 72 | /** 73 | * COMMON MIXINS 74 | */ 75 | 76 | // Ec._encrypt = function (data) { 77 | // return { 78 | // name: data.name, 79 | // data: cse.encrypt(data.number, data.holderName, data.cvc, data.expiryMonth, data.expiryYear) 80 | // }; 81 | // }; 82 | 83 | /** 84 | * Private method to build a string uri 85 | * @private 86 | * @param {String} uri 87 | * @param {String|Number} id 88 | * @param {String} extra 89 | * @return {String} 90 | */ 91 | Ec._buildUri = function (uri, id, extra, userId) { 92 | if (id) { 93 | uri += '/' + id; 94 | } 95 | if (extra) { 96 | uri += extra; 97 | } 98 | if(userId){ 99 | uri += '/user/' + userId; 100 | } 101 | var urlBase = this.driver.config.getCurrentEndpoint(Ec.moduleName, corbel.Ec._buildPort(this.driver.config)); 102 | 103 | return urlBase + uri; 104 | }; 105 | 106 | Ec._buildPort = function (config) { 107 | return config.get('ecPort', null) || corbel.Ec.defaultPort; 108 | }; 109 | 110 | })(); 111 | -------------------------------------------------------------------------------- /src/ec/orderBuilder.js: -------------------------------------------------------------------------------- 1 | //@exclude 2 | 'use strict'; 3 | //@endexclude 4 | 5 | (function () { 6 | 7 | /** 8 | * Create a OrderBuilder for order managing requests. 9 | * 10 | * @param {string} id The id of the order. 11 | * 12 | * @return {corbel.Ec.OrderBuilder} 13 | */ 14 | corbel.Ec.prototype.order = function (id) { 15 | var order = new OrderBuilder(id); 16 | order.driver = this.driver; 17 | return order; 18 | }; 19 | 20 | /** 21 | * A builder for order requests. 22 | * 23 | * @param {string} id order ID. 24 | * 25 | * @class 26 | * @memberOf corbel.Ec.OrderBuilder 27 | */ 28 | var OrderBuilder = corbel.Ec.OrderBuilder = corbel.Services.inherit({ 29 | constructor: function (id) { 30 | if (id) { 31 | this.id = id; 32 | } 33 | this.uri = 'order'; 34 | }, 35 | 36 | /** 37 | * Gets an order 38 | * @method 39 | * @memberOf corbel.Ec.OrderBuilder 40 | * 41 | * @return {Promise} Q promise that resolves to a Order {Object} or rejects with a {@link SilkRoadError} 42 | */ 43 | get: function () { 44 | console.log('ecInterface.order.get'); 45 | 46 | corbel.validate.value('id', this.id); 47 | return this.request({ 48 | url: this._buildUri(this.uri, this.id), 49 | method: corbel.request.method.GET 50 | }); 51 | }, 52 | 53 | /** 54 | * Updates the order 55 | * @method 56 | * @memberOf corbel.Ec.OrderBuilder 57 | * @param {Object} order Data of the order to update 58 | * @param {Array} order.items Array of products to purchase 59 | * @param {String} order.items.productId Product related with the item 60 | * @param {Integer} order.items.quantity Number of products 61 | * @param {Object} order.items.price Price of the product during the purchase 62 | * @param {String} order.items.price.concurrency Currency code for the price (ISO code) 63 | * @param {String} order.items.price.amount The amount of the price 64 | * @param {String} order.items.productPaymentPlan.duration Define the period of service has a validity in 65 | * ISO8601 period format 66 | * @param {String} order.items.productPaymentPlan.period The data to hire the service has a validity in 67 | * ISO8601 period format 68 | * @param {Object[]} order.items Array of products to purchase 69 | * @return {Promise} Q promise that resolves to undefined (void) or rejects 70 | * with a {@link SilkRoadError} 71 | */ 72 | update: function (order) { 73 | console.log('ecInterface.order.update'); 74 | 75 | corbel.validate.value('id', this.id); 76 | return this.request({ 77 | url: this._buildUri(this.uri, this.id), 78 | method: corbel.request.method.PUT, 79 | data: order 80 | }); 81 | }, 82 | 83 | /** 84 | * Deletes the Order 85 | * @method 86 | * @memberOf corbel.Ec.OrderBuilder 87 | * @return {Promise} Q promise that resolves to undefined (void) or rejects with a {@link SilkRoadError} 88 | */ 89 | delete: function () { 90 | console.log('ecInterface.order.delete'); 91 | 92 | corbel.validate.value('id', this.id); 93 | return this.request({ 94 | url: this._buildUri(this.uri, this.id), 95 | method: corbel.request.method.DELETE 96 | }); 97 | }, 98 | 99 | /** 100 | * Prepares the order, required to checkout 101 | * @method 102 | * @memberOf corbel.Ec.OrderBuilder 103 | * @param {string[]} couponIds Array of String with the coupons ids to prepare the order 104 | * @return {Promise} Q promise that resolves to undefined (void) or rejects with a 105 | * {@link SilkRoadError} 106 | */ 107 | prepare: function (couponIds) { 108 | console.log('ecInterface.order.prepare'); 109 | 110 | corbel.validate.value('id', this.id); 111 | return this.request({ 112 | url: this._buildUri(this.uri, this.id, '/prepare'), 113 | method: corbel.request.method.POST, 114 | data: couponIds 115 | }); 116 | }, 117 | 118 | /** 119 | * Checks out the Order 120 | * @method 121 | * @memberOf corbel.Ec.OrderBuilder 122 | * @param {Object} data Purchase information to do the checkout 123 | * @param {string[]} data.paymentMethodIds Array of String with the payment methods ids to checkout the order 124 | * @return {Promise} Promise that resolves in the new purchase id or rejects with a 125 | * {@link SilkRoadError} 126 | */ 127 | checkout: function (data) { 128 | console.log('ecInterface.order.checkout'); 129 | 130 | if (!data.paymentMethodIds) { 131 | return Promise.reject(new Error('paymentMethodIds lists needed')); 132 | } 133 | if (!data.paymentMethodIds.length) { 134 | return Promise.reject(new Error('One payment method is needed at least')); 135 | } 136 | corbel.validate.value('id', this.id); 137 | return this.request({ 138 | method: corbel.request.method.POST, 139 | url: this._buildUri(this.uri, this.id, '/checkout'), 140 | data: data 141 | }).then(function (res) { 142 | return corbel.Services.getLocationId(res); 143 | }); 144 | }, 145 | 146 | /** 147 | * Internal module uri builder 148 | * @method 149 | * @memberOf corbel.Ec.OrderBuilder 150 | * @return {string} 151 | */ 152 | _buildUri: corbel.Ec._buildUri 153 | 154 | }); 155 | 156 | })(); 157 | -------------------------------------------------------------------------------- /src/ec/paymentBuilder.js: -------------------------------------------------------------------------------- 1 | //@exclude 2 | 'use strict'; 3 | //@endexclude 4 | 5 | (function () { 6 | 7 | /** 8 | * Create a PaymentBuilder for payment managing requests. 9 | * 10 | * @return {corbel.Ec.PaymentBuilder} 11 | */ 12 | corbel.Ec.prototype.payment = function () { 13 | var payment = new PaymentBuilder(); 14 | payment.driver = this.driver; 15 | return payment; 16 | }; 17 | 18 | /** 19 | * A builder for payment requests. 20 | * 21 | * @class 22 | * @memberOf corbel.Ec.PaymentBuilder 23 | */ 24 | var PaymentBuilder = corbel.Ec.PaymentBuilder = corbel.Services.inherit({ 25 | constructor: function () { 26 | this.uri = 'payment'; 27 | }, 28 | 29 | /** 30 | * Gets all payments for the logged user. 31 | * 32 | * @method 33 | * @memberOf corbel.Ec.PaymentBuilder 34 | * @param {Object} params The params filter 35 | * @param {Integer} params.api:pageSize Number of result returned in the page (>0 , default: 10) 36 | * @param {String} params.api:query A search query expressed in silkroad query language 37 | * @param {Integer} params.api:page The page to be returned. Pages are zero-indexed (>0, default:0) 38 | * @param {String} params.api:sort Results orders. JSON with field to order and direction, asc or desc 39 | * 40 | * @return {Promise} Q promise that resolves to a Payment {Object} or rejects with a 41 | * {@link SilkRoadError} 42 | */ 43 | get: function (params, userId) { 44 | console.log('ecInterface.payment.get'); 45 | 46 | return this.request({ 47 | url: this._buildUri(this.uri, null, null, userId), 48 | method: corbel.request.method.GET, 49 | query: params ? corbel.utils.serializeParams(params) : null 50 | }); 51 | }, 52 | 53 | /** 54 | * Get payments paginated, this endpoint is only for admins. 55 | * 56 | * @method 57 | * @memberOf corbel.Ec.PaymentBuilder 58 | * @param {Object} params The params filter 59 | * @param {Integer} params.api:pageSize Number of result returned in the page (>0 , default: 10) 60 | * @param {String} params.api:query A search query expressed in silkroad query language 61 | * @param {Integer} params.api:page The page to be returned. Pages are zero-indexed (>0, default:0) 62 | * @param {String} params.api:sort Results orders. JSON with field to order and direction, asc or desc 63 | * 64 | * @return {Promise} Q promise that resolves to a Payment {Object} or rejects with a {@link SilkRoadError} 65 | */ 66 | getAll: function (params) { 67 | console.log('ecInterface.payment.getAll'); 68 | 69 | return this.request({ 70 | url: this._buildUri(this.uri, 'all'), 71 | method: corbel.request.method.GET, 72 | query: params ? corbel.utils.serializeParams(params) : null 73 | }); 74 | }, 75 | 76 | /** 77 | * Internal module uri builder 78 | * @method 79 | * @memberOf corbel.Ec.PaymentBuilder 80 | * @return {string} 81 | */ 82 | _buildUri: corbel.Ec._buildUri 83 | 84 | }); 85 | 86 | })(); 87 | -------------------------------------------------------------------------------- /src/ec/paymentMethodsBuilder.js: -------------------------------------------------------------------------------- 1 | //@exclude 2 | 'use strict'; 3 | //@endexclude 4 | 5 | (function () { 6 | 7 | /** 8 | * Create a PaymentMethodsBuilder for payment managing requests. 9 | * 10 | * @return {corbel.Ec.PaymentMethodBuilder} 11 | */ 12 | corbel.Ec.prototype.paymentMethod = function () { 13 | var paymentMethod = new PaymentMethodBuilder(); 14 | paymentMethod.driver = this.driver; 15 | return paymentMethod; 16 | }; 17 | 18 | /** 19 | * A builder for payment methods requests. 20 | * 21 | * @class 22 | * @memberOf corbel.Ec.PaymentMethodsBuilder 23 | */ 24 | var PaymentMethodBuilder = corbel.Ec.PaymentMethodBuilder = corbel.Services.inherit({ 25 | constructor: function () { 26 | this.uri = 'paymentmethod'; 27 | }, 28 | 29 | /** 30 | * Get the payment method registered for a user. 31 | * 32 | * @method 33 | * @memberOf corbel.Ec.PaymentMethodBuilder 34 | * 35 | * @return {Promise} Q promise that resolves to a Payment {Object} or rejects with a 36 | * {@link SilkRoadError} 37 | */ 38 | get: function (userId) { 39 | console.log('ecInterface.paymentmethod.get'); 40 | 41 | return this.request({ 42 | url: this._buildUri(this.uri, null, null, userId), 43 | method: corbel.request.method.GET 44 | }); 45 | }, 46 | 47 | /** 48 | * Add a new payment method for the logged user. 49 | * 50 | * @method 51 | * @memberOf corbel.Ec.PaymentMethodBuilder 52 | * 53 | * @param {Object} params The params filter 54 | * @param {String} params.data The card data encrypted 55 | * (@see https://github.com/adyenpayments/client-side-encryption) 56 | * @param {String} params.name User identifier related with de payment method 57 | * 58 | * @return {Promise} Q promise that resolves to a Payment {Object} or rejects with a 59 | * {@link SilkRoadError} 60 | */ 61 | add: function (params, userId) { 62 | console.log('ecInterface.paymentmethod.add'); 63 | 64 | return this.request({ 65 | url: this._buildUri(this.uri, null, null, userId), 66 | method: corbel.request.method.POST, 67 | data: params 68 | }) 69 | .then(function (res) { 70 | return corbel.Services.getLocationId(res); 71 | }); 72 | }, 73 | 74 | /** 75 | * Updates a current payment method for the logged user. 76 | * 77 | * @method 78 | * @memberOf corbel.Ec.PaymentMethodBuilder 79 | * 80 | * @param {Object} params The params filter 81 | * @param {String} params.data The card data encrypted 82 | * (@see https://github.com/adyenpayments/client-side-encryption) 83 | * @param {String} params.name User identifier related with de payment method 84 | * 85 | * @return {Promise} Q promise that resolves to a Payment {Object} or rejects with a 86 | * {@link SilkRoadError} 87 | */ 88 | update: function (params) { 89 | console.log('ecInterface.paymentmethod.update'); 90 | 91 | return this.request({ 92 | url: this._buildUri(this.uri), 93 | method: corbel.request.method.PUT, 94 | data: params 95 | }) 96 | .then(function (res) { 97 | return corbel.Services.getLocationId(res); 98 | }); 99 | }, 100 | 101 | 102 | /** 103 | * Get details of a single payment method by its id. 104 | * 105 | * @method 106 | * @memberOf corbel.Ec.PaymentMethodBuilder 107 | * 108 | * @param {String} id Payment method identifier 109 | * 110 | * @return {Promise} Q promise that resolves to a Payment {Object} or rejects with a 111 | * {@link SilkRoadError} 112 | */ 113 | getById: function (id) { 114 | console.log('ecInterface.paymentmethod.get'); 115 | 116 | corbel.validate.value('id', id); 117 | return this.request({ 118 | url: this._buildUri(this.uri, id), 119 | method: corbel.request.method.GET 120 | }); 121 | }, 122 | 123 | /** 124 | * Deletes a payment method. 125 | * 126 | * @method 127 | * @memberOf corbel.Ec.PaymentMethodBuilder 128 | * 129 | * @param {String} id Payment method identifier 130 | * 131 | * @return {Promise} Q promise that resolves to a Payment {Object} or rejects with a 132 | * {@link SilkRoadError} 133 | */ 134 | delete: function (id, userId) { 135 | console.log('ecInterface.paymentmethod.delete'); 136 | 137 | corbel.validate.value('id', id); 138 | return this.request({ 139 | url: this._buildUri(this.uri, id, null, userId), 140 | method: corbel.request.method.DELETE 141 | }); 142 | }, 143 | 144 | /** 145 | * Internal module uri builder 146 | * @method 147 | * @memberOf corbel.Ec.PaymentBuilder 148 | * @return {string} 149 | */ 150 | _buildUri: corbel.Ec._buildUri 151 | 152 | }); 153 | 154 | })(); 155 | -------------------------------------------------------------------------------- /src/ec/paymentPlanBuilder.js: -------------------------------------------------------------------------------- 1 | //@exclude 2 | 'use strict'; 3 | //@endexclude 4 | 5 | (function () { 6 | 7 | /** 8 | * Create a PaymentPlanBuilder for payment managing requests. 9 | * 10 | * @param {String} id payment plan id 11 | * 12 | * @return {corbel.Ec.PaymentPlanBuilder} 13 | */ 14 | corbel.Ec.prototype.paymentPlan = function (id) { 15 | var paymentPlan = new PaymentPlanBuilder(id); 16 | paymentPlan.driver = this.driver; 17 | return paymentPlan; 18 | }; 19 | 20 | /** 21 | * A builder for payment requests. 22 | * 23 | * @class 24 | * @memberOf corbel.Ec.PaymentPlanBuilder 25 | */ 26 | var PaymentPlanBuilder = corbel.Ec.PaymentPlanBuilder = corbel.Services.inherit({ 27 | constructor: function (id) { 28 | this.id = id; 29 | this.uri = 'paymentplan'; 30 | }, 31 | 32 | /** 33 | * Gets the payment plans of the logged user 34 | * 35 | * @method 36 | * @memberOf corbel.Ec.PaymentPlanBuilder 37 | */ 38 | get: function (userId) { 39 | console.log('ecInterface.paymentplan.get'); 40 | 41 | return this.request({ 42 | url: this._buildUri(this.uri, this.id, null, userId), 43 | method: corbel.request.method.GET, 44 | }); 45 | }, 46 | 47 | /** 48 | * Deletes a payment plan. 49 | * 50 | * @method 51 | * @memberOf corbel.Ec.PaymentPlanBuilder 52 | * 53 | * @param {String} id Payment method identifier 54 | * 55 | * @return {Promise} Q promise that resolves to a Payment {Object} or rejects with a 56 | * {@link SilkRoadError} 57 | */ 58 | delete: function (id) { 59 | console.log('ecInterface.paymentplan.delete'); 60 | 61 | corbel.validate.value('id', id); 62 | return this.request({ 63 | url: this._buildUri(this.uri, id), 64 | method: corbel.request.method.DELETE 65 | }); 66 | }, 67 | 68 | /** 69 | * Change the payment plan status from terminated to open (reactivated the payment plan) 70 | * 71 | * @method 72 | * @memberOf corbel.Ec.PaymentPlanBuilder 73 | * 74 | * @param {String} id Payment method identifier 75 | * 76 | */ 77 | rescue: function(id){ 78 | console.log('ecInterface.paymentplan.rescue'); 79 | 80 | corbel.validate.value('id', id); 81 | return this.request({ 82 | url: this._buildUri(this.uri, id,'/rescue'), 83 | method: corbel.request.method.PUT 84 | }); 85 | }, 86 | 87 | /** 88 | * Updates the payment plan price 89 | * 90 | * @method 91 | * @memberOf corbel.Ec.PaymentPlanBuilder 92 | * 93 | * @param {String} id Payment method identifier 94 | * 95 | */ 96 | updatePrice: function(params){ 97 | console.log('ecInterface.paymentplan.updatePrice'); 98 | 99 | corbel.validate.value('id', this.id); 100 | return this.request({ 101 | url: this._buildUri(this.uri, this.id, '/price'), 102 | method: corbel.request.method.PUT, 103 | data: params 104 | }); 105 | }, 106 | 107 | /** 108 | * Change the payment method of a payment plan 109 | * 110 | * @method 111 | * @memberOf corbel.Ec.PaymentPlanBuilder 112 | * 113 | * @param {Object} params The update params, they include payment Method id 114 | * 115 | */ 116 | updatePaymentMethod: function(params, userId){ 117 | console.log('ecInterface.paymentplan.updatePaymentMethod'); 118 | 119 | corbel.validate.value('id', this.id); 120 | 121 | return this.request({ 122 | url: this._buildUri(this.uri, this.id, '/paymentmethod', userId), 123 | method: corbel.request.method.PUT, 124 | data: params 125 | }); 126 | }, 127 | 128 | /** 129 | * Gets payment plans paginated, this endpoint is only for admins 130 | * 131 | * @method 132 | * @memberOf corbel.Ec.PaymentPlanBuilder 133 | * @param {Object} params The params filter 134 | * @param {Integer} params.api:pageSize Number of result returned in the page (>0 , default: 10) 135 | * @param {String} params.api:query A search query expressed in silkroad query language 136 | * @param {Integer} params.api:page The page to be returned. Pages are zero-indexed (>0, default:0) 137 | * @param {String} params.api:sort Results orders. JSON with field to order and direction, asc or desc 138 | * 139 | * @return {Promise} Q promise that resolves to a Payment {Object} or rejects with a {@link SilkRoadError} 140 | */ 141 | getAll: function (params) { 142 | console.log('ecInterface.paymentplan.getAll'); 143 | 144 | return this.request({ 145 | url: this._buildUri(this.uri, 'all'), 146 | method: corbel.request.method.GET, 147 | query: params ? corbel.utils.serializeParams(params) : null 148 | }); 149 | }, 150 | 151 | /** 152 | * Internal module uri builder 153 | * @method 154 | * @memberOf corbel.Ec.PaymentBuilder 155 | * @return {string} 156 | */ 157 | _buildUri: corbel.Ec._buildUri 158 | 159 | }); 160 | 161 | })(); -------------------------------------------------------------------------------- /src/ec/purchaseBuilder.js: -------------------------------------------------------------------------------- 1 | //@exclude 2 | 'use strict'; 3 | //@endexclude 4 | 5 | (function () { 6 | 7 | /** 8 | * Create a PurchaseBuilder for purchase managing requests. 9 | * 10 | * @return {corbel.Ec.PurchaseBuilder} 11 | */ 12 | corbel.Ec.prototype.purchase = function () { 13 | var purchase = new PurchaseBuilder(); 14 | purchase.driver = this.driver; 15 | return purchase; 16 | }; 17 | 18 | /** 19 | * A builder for purchase requests. 20 | * 21 | * @class 22 | * @memberOf corbel.Ec.PurchaseBuilder 23 | */ 24 | var PurchaseBuilder = corbel.Ec.PurchaseBuilder = corbel.Services.inherit({ 25 | constructor: function () { 26 | this.uri = 'purchase'; 27 | }, 28 | 29 | /** 30 | * Gets a purchase 31 | * 32 | * @method 33 | * @memberOf corbel.Ec.PurchaseBuilder 34 | * 35 | * @param id Purchase Identifier 36 | * @return {Promise} Q promise that resolves to a Purchase {Object} or rejects with a 37 | * {@link SilkRoadError} 38 | */ 39 | get: function (id) { 40 | console.log('ecInterface.purchase.get'); 41 | 42 | corbel.validate.value('id', id); 43 | return this.request({ 44 | url: this._buildUri(this.uri, id), 45 | method: corbel.request.method.GET 46 | }); 47 | }, 48 | 49 | /** 50 | * Gets all purchases for the logged user. 51 | * @method 52 | * @memberOf corbel.Ec.PurchaseBuilder 53 | * 54 | * @param {Object} params The params filter 55 | * @param {Integer} params.api:pageSize Number of result returned in the page (>0 , default: 10) 56 | * @param {String} params.api:query A search query expressed in silkroad query language 57 | * @param {Integer} params.api:page The page to be returned. Pages are zero-indexed (>0, default:0) 58 | * @param {String} params.api:sort Results orders. JSON with field to order and direction, asc or desc 59 | * 60 | * @return {Promise} Q promise that resolves to a Purchase {Object} or rejects with a {@link SilkRoadError} 61 | */ 62 | getAll: function (params, userId) { 63 | console.log('ecInterface.purchase.getAll'); 64 | 65 | return this.request({ 66 | url: this._buildUri(this.uri, null, null, userId), 67 | method: corbel.request.method.GET, 68 | query: params ? corbel.utils.serializeParams(params) : null 69 | }); 70 | }, 71 | 72 | /** 73 | * Internal module uri builder 74 | * @method 75 | * @memberOf corbel.Ec.PurchaseBuilder 76 | * @return {string} 77 | */ 78 | _buildUri: corbel.Ec._buildUri 79 | 80 | }); 81 | 82 | })(); 83 | -------------------------------------------------------------------------------- /src/evci/evci.js: -------------------------------------------------------------------------------- 1 | (function() { 2 | //@exclude 3 | 'use strict'; 4 | /*globals corbel */ 5 | //@endexclude 6 | 7 | corbel.Evci = corbel.Object.inherit({ 8 | 9 | /** 10 | * Create a new EventBuilder 11 | * @param {String} type String 12 | * @return {Events} 13 | */ 14 | constructor: function(driver) { 15 | this.driver = driver; 16 | }, 17 | 18 | event: function(type) { 19 | return new corbel.Evci.EventBuilder(type, this.driver); 20 | } 21 | 22 | }, { 23 | 24 | moduleName: 'evci', 25 | defaultPort: 8086, 26 | 27 | create: function(driver) { 28 | return new corbel.Evci(driver); 29 | } 30 | 31 | }); 32 | 33 | return corbel.Evci; 34 | 35 | })(); 36 | -------------------------------------------------------------------------------- /src/evci/eventBuilder.js: -------------------------------------------------------------------------------- 1 | //@exclude 2 | 'use strict'; 3 | //@endexclude 4 | 5 | (function() { 6 | 7 | var EventBuilder = corbel.Evci.EventBuilder = corbel.Services.inherit({ 8 | /** 9 | * Creates a new EventBuilder 10 | * @param {String} type 11 | * @return {Events} 12 | */ 13 | constructor: function(type, driver) { 14 | this.uri = 'event'; 15 | this.eventType = type; 16 | this.driver = driver; 17 | }, 18 | 19 | /** 20 | * Publish a new event. 21 | * 22 | * @method 23 | * @memberOf corbel.Evci.EventBuilder 24 | * 25 | * @param {Object} eventData The data of the event. 26 | * 27 | * @return {Promise} A promise with the id of the created scope or fails 28 | * with a {@link corbelError}. 29 | */ 30 | publish: function(eventData) { 31 | if (!eventData) { 32 | throw new Error('Send event require data'); 33 | } 34 | console.log('evciInterface.publish', eventData); 35 | corbel.validate.value('eventType', this.eventType); 36 | return this.request({ 37 | url: this._buildUri(this.uri,this.eventType), 38 | method: corbel.request.method.POST, 39 | data: eventData 40 | }).then(function(res) { 41 | return res; 42 | }); 43 | }, 44 | 45 | _buildUri: function(path,eventType) { 46 | var uri = ''; 47 | var urlBase = this.driver.config.getCurrentEndpoint(corbel.Evci.moduleName, this._buildPort(this.driver.config)); 48 | 49 | uri = urlBase + path; 50 | if (eventType) { 51 | uri += '/' + eventType; 52 | } 53 | return uri; 54 | }, 55 | 56 | _buildPort: function(config) { 57 | return config.get('evciPort', null) || corbel.Evci.defaultPort; 58 | } 59 | 60 | }, { 61 | 62 | moduleName: 'evci', 63 | 64 | create: function(driver) { 65 | return new corbel.EventBuilder(driver); 66 | } 67 | 68 | }); 69 | 70 | return EventBuilder; 71 | })(); 72 | -------------------------------------------------------------------------------- /src/iam/clientBuilder.js: -------------------------------------------------------------------------------- 1 | //@exclude 2 | 'use strict'; 3 | //@endexclude 4 | 5 | (function() { 6 | 7 | /** 8 | * Creates a ClientBuilder for client managing requests. 9 | * 10 | * @param {String} clientId Client id (optional). 11 | * 12 | * @return {corbel.Iam.ClientBuilder} 13 | */ 14 | corbel.Iam.prototype.client = function(clientId) { 15 | var client = new ClientBuilder(clientId); 16 | client.driver = this.driver; 17 | return client; 18 | }; 19 | 20 | /** 21 | * A builder for client management requests. 22 | * 23 | * @param {String} clientId Client id. 24 | * 25 | * @class 26 | * @memberOf iam 27 | */ 28 | var ClientBuilder = corbel.Iam.ClientBuilder = corbel.Services.inherit({ 29 | 30 | constructor: function(clientId) { 31 | this.clientId = clientId; 32 | this.uri = 'client'; 33 | }, 34 | 35 | /** 36 | * Adds a new client. 37 | * 38 | * @method 39 | * @memberOf corbel.Iam.ClientBuilder 40 | * 41 | * @param {Object} client The client data. 42 | * @param {String} client.id Client id. 43 | * @param {String} client.name Client domain (obligatory). 44 | * @param {String} client.key Client key (obligatory). 45 | * @param {String} client.version Client version. 46 | * @param {String} client.signatureAlghorithm Signature alghorithm. 47 | * @param {Object} client.scopes Scopes of the client. 48 | * @param {String} client.clientSideAuthentication Option for client side authentication. 49 | * @param {String} client.resetUrl Reset password url. 50 | * @param {String} client.resetNotificationId Reset password notification id. 51 | * 52 | * @return {Promise} A promise with the id of the created client or fails 53 | * with a {@link corbelError}. 54 | */ 55 | create: function(client) { 56 | console.log('iamInterface.client.create', client); 57 | return this.request({ 58 | url: this._buildUriWithDomain(this.uri), 59 | method: corbel.request.method.POST, 60 | data: client 61 | }).then(function(res) { 62 | return corbel.Services.getLocationId(res); 63 | }); 64 | }, 65 | 66 | /** 67 | * Gets a client. 68 | * 69 | * @method 70 | * @memberOf corbel.Iam.ClientBuilder 71 | * 72 | * @param {String} clientId Client id. 73 | * 74 | * @return {Promise} A promise with the client or fails with a {@link corbelError}. 75 | */ 76 | get: function() { 77 | console.log('iamInterface.client.get', this.clientId); 78 | corbel.validate.value('clientId', this.clientId); 79 | return this.request({ 80 | url: this._buildUriWithDomain(this.uri, this.clientId), 81 | method: corbel.request.method.GET 82 | }); 83 | }, 84 | 85 | /** 86 | * Gets all clients by domain. 87 | * 88 | * @method 89 | * @memberOf corbel.Iam.ClientBuilder 90 | * @param {object} options Get options for the request 91 | * @return {Promise} A promise with the domain or fails with a {@link corbelError}. 92 | * @see {@link corbel.util.serializeParams} to see a example of the params 93 | */ 94 | getAll: function(params) { 95 | corbel.validate.failIfIsDefined(this.clientId, 'This function not allowed client identifier'); 96 | console.log('iamInterface.client.getAll'); 97 | return this.request({ 98 | url: this._buildUriWithDomain(this.uri), 99 | method: corbel.request.method.GET, 100 | query: params ? corbel.utils.serializeParams(params) : null 101 | }); 102 | }, 103 | 104 | /** 105 | * Updates a client. 106 | * 107 | * @method 108 | * @memberOf corbel.Iam.ClientBuilder 109 | * 110 | * @param {Object} client The client data. 111 | * @param {String} client.name Client domain (obligatory). 112 | * @param {String} client.key Client key (obligatory). 113 | * @param {String} client.version Client version. 114 | * @param {String} client.signatureAlghorithm Signature alghorithm. 115 | * @param {Object} client.scopes Scopes of the client. 116 | * @param {String} client.clientSideAuthentication Option for client side authentication. 117 | * @param {String} client.resetUrl Reset password url. 118 | * @param {String} client.resetNotificationId Reset password notification id. 119 | * 120 | * @return {Promise} A promise or fails with a {@link corbelError}. 121 | */ 122 | update: function(client) { 123 | console.log('iamInterface.client.update', client); 124 | corbel.validate.value('clientId', this.clientId); 125 | return this.request({ 126 | url: this._buildUriWithDomain(this.uri + '/' + this.clientId), 127 | method: corbel.request.method.PUT, 128 | data: client 129 | }); 130 | }, 131 | 132 | /** 133 | * Removes a client. 134 | * 135 | * @method 136 | * @memberOf corbel.Iam.ClientBuilder 137 | * 138 | * @param {String} clientId The client id. 139 | * 140 | * @return {Promise} A promise or fails with a {@link corbelError}. 141 | */ 142 | remove: function() { 143 | console.log('iamInterface.client.remove', this.clientId); 144 | corbel.validate.value('clientId', this.clientId); 145 | 146 | return this.request({ 147 | url: this._buildUriWithDomain(this.uri + '/' + this.clientId), 148 | method: corbel.request.method.DELETE 149 | }); 150 | }, 151 | 152 | _buildUriWithDomain: corbel.Iam._buildUriWithDomain 153 | 154 | }); 155 | 156 | })(); 157 | -------------------------------------------------------------------------------- /src/iam/domainBuilder.js: -------------------------------------------------------------------------------- 1 | //@exclude 2 | 'use strict'; 3 | //@endexclude 4 | 5 | (function() { 6 | 7 | /** 8 | * Creates a DomainBuilder for domain managing requests. 9 | * 10 | * @return {corbel.Iam.DomainBuilder} 11 | */ 12 | corbel.Iam.prototype.domain = function() { 13 | var domain = new DomainBuilder(); 14 | domain.driver = this.driver; 15 | return domain; 16 | }; 17 | 18 | /** 19 | * A builder for domain management requests. 20 | * 21 | * @class 22 | * @memberOf iam 23 | */ 24 | var DomainBuilder = corbel.Iam.DomainBuilder = corbel.Services.inherit({ 25 | 26 | constructor: function() { 27 | this.uri = 'domain'; 28 | }, 29 | 30 | /** 31 | * Creates a new domain. 32 | * 33 | * @method 34 | * @memberOf corbel.Iam.DomainBuilder 35 | * 36 | * @param {Object} domain The domain data. 37 | * @param {String} domain.description Description of the domain. 38 | * @param {String} domain.authUrl Authentication url. 39 | * @param {String} domain.allowedDomains Allowed domains. 40 | * @param {String} domain.scopes Scopes of the domain. 41 | * @param {String} domain.defaultScopes Default copes of the domain. 42 | * @param {Object} domain.authConfigurations Authentication configuration. 43 | * @param {Object} domain.userProfileFields User profile fields. 44 | * 45 | * @return {Promise} A promise with the id of the created domain or fails 46 | * with a {@link corbelError}. 47 | */ 48 | create: function(domain) { 49 | console.log('iamInterface.domain.create', domain); 50 | return this.request({ 51 | url: this._buildUriWithDomain(this.uri), 52 | method: corbel.request.method.POST, 53 | data: domain 54 | }).then(function(res) { 55 | return corbel.Services.getLocationId(res); 56 | }); 57 | }, 58 | 59 | /** 60 | * Gets a domain. 61 | * 62 | * @method 63 | * @memberOf corbel.Iam.DomainBuilder 64 | * 65 | * @return {Promise} A promise with the domain or fails with a {@link corbelError}. 66 | */ 67 | get: function() { 68 | console.log('iamInterface.domain.get'); 69 | return this.request({ 70 | url: this._buildUriWithDomain(this.uri), 71 | method: corbel.request.method.GET 72 | }); 73 | }, 74 | 75 | /** 76 | * Gets all domains. 77 | * 78 | * @method 79 | * @memberOf corbel.Iam.DomainBuilder 80 | * @param {object} params Get options for the request 81 | * @return {Promise} A promise with the domain or fails with a {@link corbelError}. 82 | * @see {@link corbel.util.serializeParams} to see a example of the params 83 | */ 84 | getAll: function(params) { 85 | console.log('iamInterface.domain.getAll'); 86 | return this.request({ 87 | url: this._buildUriWithDomain(this.uri + '/all'), 88 | method: corbel.request.method.GET, 89 | query: params ? corbel.utils.serializeParams(params) : null 90 | }); 91 | }, 92 | 93 | /** 94 | * Updates a domain. 95 | * 96 | * @method 97 | * @memberOf corbel.Iam.DomainBuilder 98 | * 99 | * @param {Object} domain The domain data. 100 | * @param {String} domain.description Description of the domain. 101 | * @param {String} domain.authUrl Authentication url. 102 | * @param {String} domain.allowedDomains Allowed domains. 103 | * @param {String} domain.scopes Scopes of the domain. 104 | * @param {String} domain.defaultScopes Default copes of the domain. 105 | * @param {Object} domain.authConfigurations Authentication configuration. 106 | * @param {Object} domain.userProfileFields User profile fields. 107 | * 108 | * @return {Promise} A promise or fails with a {@link corbelError}. 109 | */ 110 | update: function(domain) { 111 | console.log('iamInterface.domain.update', domain); 112 | return this.request({ 113 | url: this._buildUriWithDomain(this.uri), 114 | method: corbel.request.method.PUT, 115 | data: domain 116 | }); 117 | }, 118 | 119 | /** 120 | * Removes a domain. 121 | * 122 | * @method 123 | * @memberOf corbel.Iam.DomainBuilder 124 | * 125 | * 126 | * @return {Promise} A promise or fails with a {@link corbelError}. 127 | */ 128 | remove: function() { 129 | console.log('iamInterface.domain.delete'); 130 | return this.request({ 131 | url: this._buildUriWithDomain(this.uri), 132 | method: corbel.request.method.DELETE 133 | }); 134 | }, 135 | 136 | _buildUriWithDomain: corbel.Iam._buildUriWithDomain 137 | 138 | }); 139 | 140 | })(); 141 | -------------------------------------------------------------------------------- /src/iam/emailBuilder.js: -------------------------------------------------------------------------------- 1 | //@exclude 2 | 'use strict'; 3 | //@endexclude 4 | 5 | (function() { 6 | 7 | /** 8 | * Creates a EmailBuilder for email requests 9 | * @return {corbel.Iam.EmailBuilder} 10 | */ 11 | corbel.Iam.prototype.email = function() { 12 | var builder; 13 | builder = new EmailBuilder(); 14 | builder.driver = this.driver; 15 | return builder; 16 | }; 17 | 18 | /** 19 | * Builder for creating requests of email 20 | * @class 21 | * @memberOf iam 22 | */ 23 | var EmailBuilder = corbel.Iam.EmailBuilder = corbel.Services.inherit({ 24 | 25 | constructor: function() { 26 | this.uri = 'email'; 27 | }, 28 | 29 | /** 30 | * Gets a UserId. 31 | * 32 | * @method 33 | * @memberOf corbel.Iam.EmailBuilder 34 | * 35 | * @param {String} email The email. 36 | * 37 | * @return {Promise} A promise with the user or fails with a {@link corbelError}. 38 | */ 39 | getUserId: function(email) { 40 | console.log('iamInterface.email.getUserId', email); 41 | corbel.validate.value('email', email); 42 | 43 | return this.request({ 44 | url: this._buildUriWithDomain(this.uri, email), 45 | method: corbel.request.method.GET 46 | }); 47 | }, 48 | 49 | /** 50 | * Return availability endpoint. 51 | * @method 52 | * @memberOf corbel.Iam.EmailBuilder 53 | * @param {String} email The email. 54 | * @return {Promise} A promise which resolves into email availability boolean state. 55 | */ 56 | availability: function(email) { 57 | console.log('iamInterface.email.availability', email); 58 | corbel.validate.value('email', email); 59 | 60 | return this.request({ 61 | url: this._buildUriWithDomain(this.uri, email), 62 | method: corbel.request.method.HEAD 63 | }).then( 64 | function() { 65 | return false; 66 | }, 67 | function(response) { 68 | if (response.status === 404) { 69 | return true; 70 | } else { 71 | return Promise.reject(response); 72 | } 73 | } 74 | ); 75 | }, 76 | 77 | _buildUriWithDomain: corbel.Iam._buildUriWithDomain 78 | 79 | }); 80 | })(); 81 | -------------------------------------------------------------------------------- /src/iam/groupsBuilder.js: -------------------------------------------------------------------------------- 1 | //@exclude 2 | 'use strict'; 3 | //@endexclude 4 | 5 | (function() { 6 | 7 | /** 8 | * Creates a GroupBuilder for group requests 9 | * 10 | * @return {iam.GroupBuilder | iam.GroupsBuilder} 11 | */ 12 | corbel.Iam.prototype.group = function(id) { 13 | var builder; 14 | 15 | if (id) { 16 | builder = new GroupBuilder(id); 17 | } else { 18 | builder = new GroupsBuilder(); 19 | } 20 | 21 | builder.driver = this.driver; 22 | return builder; 23 | }; 24 | 25 | /** 26 | * A builder for group requests without id (getAll and creation). 27 | * 28 | * @class 29 | * @memberOf iam 30 | */ 31 | var GroupsBuilder = corbel.Iam.GroupsBuilder = corbel.Services.inherit({ 32 | 33 | constructor: function() { 34 | this.uri = 'group'; 35 | }, 36 | 37 | /** 38 | * Get all groups. 39 | * 40 | * @method 41 | * @memberOf iam.GroupBuilder 42 | * 43 | * @param {Object} params Query parameters. 44 | * 45 | * @return {Promise} Q promise that resolves to an array of groups. 46 | */ 47 | getAll: function(params) { 48 | console.log('iamInterface.groups.getAll'); 49 | return this.request({ 50 | url: this._buildUriWithDomain(this.uri), 51 | method: corbel.request.method.GET, 52 | query: params ? corbel.utils.serializeParams(params) : null, 53 | withAuth: true 54 | }); 55 | }, 56 | 57 | /** 58 | * Create a group. 59 | * 60 | * @method 61 | * @memberOf iam.GroupBuilder 62 | * 63 | * @param {Object} data The group to create. 64 | * @param {String} data.name Group name. 65 | * @param {String} data.domain Group domain. 66 | * @param {Array} data.scopes Group scopes. 67 | * 68 | * @return {Promise} A promise which resolves into the ID of the created group or fails with a {@link SilkRoadError}. 69 | */ 70 | create: function(data) { 71 | console.log('iamInterface.groups.create', data); 72 | return this.request({ 73 | url: this._buildUriWithDomain(this.uri), 74 | method: corbel.request.method.POST, 75 | data: data, 76 | withAuth: true 77 | }).then(function(res) { 78 | return corbel.Services.getLocationId(res); 79 | }); 80 | }, 81 | 82 | _buildUriWithDomain: corbel.Iam._buildUriWithDomain 83 | 84 | }); 85 | 86 | /** 87 | * A builder for group requests. 88 | * 89 | * @class 90 | * @memberOf iam 91 | * @param {String} id The id of the group. 92 | */ 93 | var GroupBuilder = corbel.Iam.GroupBuilder = corbel.Services.inherit({ 94 | 95 | constructor: function(id) { 96 | this.uri = 'group'; 97 | this.id = id; 98 | }, 99 | 100 | /** 101 | * Get a group. 102 | * 103 | * @method 104 | * @memberOf corbel.Iam.GroupBuilder 105 | * @return {Promise} Q promise that resolves to a group or rejects with a {@link SilkRoadError}. 106 | */ 107 | get: function() { 108 | console.log('iamInterface.group.get'); 109 | corbel.validate.value('id', this.id); 110 | return this.request({ 111 | url: this._buildUriWithDomain(this.uri, this.id), 112 | method: corbel.request.method.GET, 113 | withAuth: true 114 | }); 115 | }, 116 | 117 | /** 118 | * Add scopes to a group. 119 | * 120 | * @method 121 | * @memberOf corbel.Iam.GroupBuilder 122 | * 123 | * @param {Array} scopes Group scopes to add. 124 | * 125 | * @return {Promise} A promise which resolves to undefined(void) or fails with a {@link SilkRoadError}. 126 | */ 127 | addScopes: function(scopes) { 128 | console.log('iamInterface.group.addScopes', scopes); 129 | corbel.validate.value('id', this.id); 130 | return this.request({ 131 | url: this._buildUriWithDomain(this.uri, this.id) + '/scope', 132 | method: corbel.request.method.PUT, 133 | data: scopes, 134 | withAuth: true 135 | }); 136 | }, 137 | 138 | /** 139 | * Remove a scope from a group. 140 | * 141 | * @method 142 | * @memberOf iam.GroupBuilder 143 | * 144 | * @param {String} scope Group scope. 145 | * 146 | * @return {Promise} A promise which resolves to undefined(void) or fails with a {@link SilkRoadError}. 147 | */ 148 | removeScope: function(scope) { 149 | console.log('iamInterface.group.removeScope', scope); 150 | corbel.validate.value('id', this.id); 151 | return this.request({ 152 | url: this._buildUriWithDomain(this.uri, this.id) + '/scope/' + scope, 153 | method: corbel.request.method.DELETE, 154 | withAuth: true 155 | }); 156 | }, 157 | 158 | /** 159 | * Delete a group. 160 | * 161 | * @method 162 | * @memberOf iam.GroupBuilder 163 | * @return {Promise} A promise which resolves to undefined(void) or fails with a {@link SilkRoadError}. 164 | */ 165 | delete: function() { 166 | console.log('iamInterface.group.delete'); 167 | corbel.validate.value('id', this.id); 168 | return this.request({ 169 | url: this._buildUriWithDomain(this.uri, this.id), 170 | method: corbel.request.method.DELETE, 171 | withAuth: true 172 | }); 173 | }, 174 | 175 | _buildUriWithDomain: corbel.Iam._buildUriWithDomain 176 | 177 | }); 178 | })(); 179 | -------------------------------------------------------------------------------- /src/iam/iam.js: -------------------------------------------------------------------------------- 1 | //@exclude 2 | 'use strict'; 3 | //@endexclude 4 | 5 | (function() { 6 | 7 | /** 8 | * A module to make iam requests. 9 | * @exports iam 10 | * @namespace 11 | * @memberof app.corbel 12 | */ 13 | 14 | var Iam = corbel.Iam = function(driver) { 15 | this.driver = driver; 16 | }; 17 | 18 | Iam.moduleName = 'iam'; 19 | Iam.defaultPort = 8082; 20 | 21 | Iam.create = function(driver) { 22 | return new Iam(driver); 23 | }; 24 | 25 | Iam.GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:jwt-bearer'; 26 | Iam.AUD = 'http://iam.bqws.io'; 27 | Iam.IAM_TOKEN = 'iamToken'; 28 | Iam.IAM_TOKEN_SCOPES = 'iamScopes'; 29 | Iam.IAM_DOMAIN = 'domain'; 30 | 31 | /** 32 | * COMMON MIXINS 33 | */ 34 | 35 | /** 36 | * Private method to build a string uri 37 | * @private 38 | * @param {String} uri 39 | * @param {String|Number} id 40 | * @return {String} 41 | */ 42 | Iam._buildUri = function(uri, id) { 43 | if (id) { 44 | uri += '/' + id; 45 | } 46 | 47 | var urlBase = this.driver.config.getCurrentEndpoint(Iam.moduleName, corbel.Iam._buildPort(this.driver.config)); 48 | 49 | return urlBase + uri; 50 | }; 51 | 52 | /** 53 | * Private method to build a string uri with domain 54 | * @private 55 | * @param {String} uri 56 | * @param {String|Number} id 57 | * @return {String} 58 | */ 59 | Iam._buildUriWithDomain = function(uri, id) { 60 | 61 | var urlBase = this.driver.config.getCurrentEndpoint(Iam.moduleName, corbel.Iam._buildPort(this.driver.config)); 62 | 63 | var domain = this.driver.config.get(corbel.Iam.IAM_DOMAIN, 'unauthenticated'); 64 | var customDomain = this.driver.config.get(corbel.Domain.CUSTOM_DOMAIN, domain); 65 | 66 | this.driver.config.set(corbel.Domain.CUSTOM_DOMAIN, undefined); 67 | 68 | var uriWithDomain = urlBase + customDomain + '/' + uri; 69 | 70 | if (id) { 71 | uriWithDomain += '/' + id; 72 | } 73 | 74 | return uriWithDomain; 75 | }; 76 | 77 | Iam._buildPort = function(config) { 78 | return config.get('iamPort', null) || corbel.Iam.defaultPort; 79 | }; 80 | 81 | })(); 82 | -------------------------------------------------------------------------------- /src/iam/scopeBuilder.js: -------------------------------------------------------------------------------- 1 | //@exclude 2 | 'use strict'; 3 | //@endexclude 4 | 5 | (function() { 6 | 7 | /** 8 | * Creates a ScopeBuilder for scope managing requests. 9 | * @param {String} id Scope id. 10 | * @return {corbel.Iam.ScopeBuilder} 11 | */ 12 | corbel.Iam.prototype.scope = function(id) { 13 | var scope = new ScopeBuilder(id); 14 | scope.driver = this.driver; 15 | return scope; 16 | }; 17 | 18 | /** 19 | * A builder for scope management requests. 20 | * 21 | * @param {String} id Scope id. 22 | * 23 | * @class 24 | * @memberOf iam 25 | */ 26 | var ScopeBuilder = corbel.Iam.ScopeBuilder = corbel.Services.inherit({ 27 | 28 | constructor: function(id) { 29 | this.id = id; 30 | this.uri = 'scope'; 31 | }, 32 | 33 | /** 34 | * Creates a new scope. 35 | * 36 | * @method 37 | * @memberOf corbel.Iam.ScopeBuilder 38 | * 39 | * @param {Object} scope The scope. 40 | * @param {Object} scope.rules Scope rules. 41 | * @param {String} scope.type Scope type. 42 | * @param {Object} scope.scopes Scopes for a composite scope. 43 | * 44 | * @return {Promise} A promise with the id of the created scope or fails 45 | * with a {@link corbelError}. 46 | */ 47 | create: function(scope) { 48 | corbel.validate.failIfIsDefined(this.id, 'This function not allowed scope identifier'); 49 | console.log('iamInterface.scope.create', scope); 50 | return this.request({ 51 | url: this._buildUriWithDomain(this.uri), 52 | method: corbel.request.method.POST, 53 | data: scope 54 | }).then(function(res) { 55 | return corbel.Services.getLocationId(res); 56 | }); 57 | }, 58 | 59 | /** 60 | * Gets a scope. 61 | * 62 | * @method 63 | * @memberOf corbel.Iam.ScopeBuilder 64 | * 65 | * @return {Promise} A promise with the scope or fails with a {@link corbelError}. 66 | */ 67 | get: function() { 68 | console.log('iamInterface.scope.get', this.id); 69 | corbel.validate.value('id', this.id); 70 | return this.request({ 71 | url: this._buildUriWithDomain(this.uri + '/' + this.id), 72 | method: corbel.request.method.GET 73 | }); 74 | }, 75 | 76 | /** 77 | * Removes a scope. 78 | * 79 | * @method 80 | * @memberOf corbel.Iam.ScopeBuilder 81 | * @return {Promise} A promise user or fails with a {@link corbelError}. 82 | */ 83 | remove: function() { 84 | console.log('iamInterface.scope.remove', this.id); 85 | corbel.validate.value('id', this.id); 86 | return this.request({ 87 | url: this._buildUriWithDomain(this.uri + '/' + this.id), 88 | method: corbel.request.method.DELETE 89 | }); 90 | }, 91 | 92 | _buildUriWithDomain: corbel.Iam._buildUriWithDomain 93 | 94 | }); 95 | })(); 96 | -------------------------------------------------------------------------------- /src/iam/usernameBuilder.js: -------------------------------------------------------------------------------- 1 | //@exclude 2 | 'use strict'; 3 | //@endexclude 4 | 5 | (function() { 6 | 7 | /** 8 | * Starts a username request 9 | * @return {corbel.Iam.UsernameBuilder} The builder to create the request 10 | */ 11 | corbel.Iam.prototype.username = function() { 12 | var username = new UsernameBuilder(); 13 | username.driver = this.driver; 14 | return username; 15 | }; 16 | 17 | /** 18 | * Builder for creating requests of users name 19 | * @class 20 | * @memberOf iam 21 | */ 22 | var UsernameBuilder = corbel.Iam.UsernameBuilder = corbel.Services.inherit({ 23 | 24 | constructor: function() { 25 | this.uri = 'username'; 26 | }, 27 | 28 | /** 29 | * Return availability endpoint. 30 | * @method 31 | * @memberOf corbel.Iam.UsernameBuilder 32 | * @param {String} username The username. 33 | * @return {Promise} A promise which resolves into usename availability boolean state. 34 | */ 35 | availability: function(username) { 36 | console.log('iamInterface.username.availability', username); 37 | corbel.validate.value('username', username); 38 | return this.request({ 39 | url: this._buildUriWithDomain(this.uri, username), 40 | method: corbel.request.method.HEAD 41 | }).then(function() { 42 | return false; 43 | }).catch(function(response) { 44 | if (response.status === 404) { 45 | return true; 46 | } else { 47 | return Promise.reject(response); 48 | } 49 | }); 50 | }, 51 | 52 | /** 53 | * Gets a UserId. 54 | * 55 | * @method 56 | * @memberOf corbel.Iam.UsernameBuilder 57 | * 58 | * @param {String} username The username. 59 | * 60 | * @return {Promise} A promise with the user or fails with a {@link corbelError}. 61 | */ 62 | getUserId: function(username) { 63 | console.log('iamInterface.username.getUserId', username); 64 | corbel.validate.value('username', username); 65 | return this.request({ 66 | url: this._buildUriWithDomain(this.uri, username), 67 | method: corbel.request.method.GET 68 | }); 69 | }, 70 | 71 | _buildUriWithDomain: corbel.Iam._buildUriWithDomain 72 | 73 | }); 74 | })(); 75 | -------------------------------------------------------------------------------- /src/jwt.js: -------------------------------------------------------------------------------- 1 | /* jshint camelcase:false */ 2 | //@exclude 3 | 'use strict'; 4 | //@endexclude 5 | 6 | (function() { 7 | 8 | var jwt = corbel.jwt = { 9 | 10 | EXPIRATION: 3500, 11 | ALGORITHM: 'HS256', 12 | TYP: 'JWT', 13 | VERSION: '1.0.0', 14 | 15 | /** 16 | * JWT-HmacSHA256 generator 17 | * http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html 18 | * @param {Object} claims Specific claims to include in the JWT (iss, aud, exp, scope, ...) 19 | * @param {String} secret String with the client assigned secret 20 | * @param {Object} [alg='corbel.jwt.ALGORITHM'] Object with the algorithm type 21 | * @return {String} jwt JWT string 22 | */ 23 | generate: function(claims, secret, alg) { 24 | claims = claims || {}; 25 | claims.exp = claims.exp || jwt._generateExp(); 26 | 27 | if (!claims.iss) { 28 | throw new Error('jwt:undefined:iss'); 29 | } 30 | if (!claims.aud) { 31 | throw new Error('jwt:undefined:aud'); 32 | } 33 | 34 | return jwt._generate(claims, secret, alg); 35 | }, 36 | 37 | _generate: function(claims, secret, alg){ 38 | alg = alg || jwt.ALGORITHM; 39 | 40 | // Ensure claims specific order 41 | var claimsKeys = [ 42 | 'iss', 43 | 'aud', 44 | 'exp', 45 | 'scope', 46 | 'prn', 47 | 'version', 48 | 'refresh_token', 49 | 'request_domain', 50 | 51 | 'basic_auth.username', 52 | 'basic_auth.password', 53 | 54 | 'device_id' 55 | ]; 56 | 57 | var finalClaims = {}; 58 | claimsKeys.forEach(function(key) { 59 | if (claims[key]) { 60 | finalClaims[key] = claims[key]; 61 | } 62 | }); 63 | 64 | corbel.utils.extend(finalClaims, claims); 65 | 66 | if (Array.isArray(finalClaims.scope)) { 67 | finalClaims.scope = finalClaims.scope.join(' '); 68 | } 69 | 70 | var bAlg = corbel.cryptography.rstr2b64(corbel.cryptography.str2rstr_utf8(JSON.stringify({ 71 | typ: jwt.TYP, 72 | alg: alg 73 | }))), 74 | bClaims = corbel.cryptography.rstr2b64(corbel.cryptography.str2rstr_utf8(JSON.stringify(finalClaims))), 75 | segment = bAlg + '.' + bClaims, 76 | assertion = corbel.cryptography.b64tob64u(corbel.cryptography.b64_hmac_sha256(secret, segment)); 77 | 78 | return segment + '.' + assertion; 79 | }, 80 | 81 | _generateExp: function() { 82 | return Math.round((new Date().getTime() / 1000)) + jwt.EXPIRATION; 83 | }, 84 | 85 | decode: function(assertion) { 86 | var serialize; 87 | if (corbel.Config.isNode || !root.atob) { 88 | // node environment 89 | serialize = require('base-64').decode; 90 | } else { 91 | serialize = root.atob; 92 | } 93 | var decoded = assertion.split('.'); 94 | 95 | try { 96 | decoded[0] = JSON.parse(serialize(decoded[0])); 97 | } catch (e) { 98 | decoded[0] = false; 99 | } 100 | 101 | try { 102 | decoded[1] = JSON.parse(serialize(decoded[1])); 103 | } catch (e) { 104 | decoded[1] = false; 105 | } 106 | 107 | if (!decoded[0] && !decoded[1]) { 108 | throw new Error('corbel:jwt:decode:invalid_assertion'); 109 | } 110 | 111 | decoded[0] = decoded[0] || {}; 112 | decoded[1] = decoded[1] || {}; 113 | 114 | Object.keys(decoded[1]).forEach(function(key) { 115 | decoded[0][key] = decoded[1][key]; 116 | }); 117 | 118 | return decoded[0]; 119 | } 120 | 121 | }; 122 | 123 | return jwt; 124 | 125 | })(); 126 | -------------------------------------------------------------------------------- /src/notifications/base-notifications.js: -------------------------------------------------------------------------------- 1 | (function() { 2 | //@exclude 3 | 'use strict'; 4 | //@endexclude 5 | 6 | corbel.Notifications.BaseNotifications = corbel.Services.inherit({ 7 | 8 | /** 9 | * Helper function to build the request uri 10 | * @param {String} srcType Type of the resource 11 | * @param {String} srcId Id of the resource 12 | * @param {String} relType Type of the relationed resource 13 | * @param {String} destId Information of the relationed resource 14 | * @return {String} Uri to perform the request 15 | */ 16 | buildUri: function(uri, id) { 17 | var urlBase = this.driver.config.getCurrentEndpoint(corbel.Notifications.moduleName, this._buildPort(this.driver.config)); 18 | 19 | var domain = this.driver.config.get(corbel.Iam.IAM_DOMAIN, 'unauthenticated'); 20 | var customDomain = this.driver.config.get(corbel.Domain.CUSTOM_DOMAIN, domain); 21 | 22 | this.driver.config.set(corbel.Domain.CUSTOM_DOMAIN, undefined); 23 | 24 | var uriWithDomain = urlBase + customDomain + '/' + uri; 25 | 26 | if (id) { 27 | uriWithDomain += '/' + id; 28 | } 29 | 30 | return uriWithDomain; 31 | }, 32 | 33 | _buildPort: function(config) { 34 | return config.get('notificationsPort', null) || corbel.Notifications.defaultPort; 35 | } 36 | 37 | }); 38 | 39 | 40 | return corbel.Notifications.BaseNotifications; 41 | 42 | })(); 43 | -------------------------------------------------------------------------------- /src/notifications/notifications.js: -------------------------------------------------------------------------------- 1 | (function() { 2 | //@exclude 3 | 'use strict'; 4 | /*globals corbel */ 5 | //@endexclude 6 | 7 | corbel.Notifications = corbel.Object.inherit({ 8 | 9 | constructor: function(driver) { 10 | this.driver = driver; 11 | }, 12 | 13 | template: function(id) { 14 | return new corbel.Notifications.NotificationsTemplateBuilder(this.driver, id); 15 | }, 16 | 17 | domain: function() { 18 | return new corbel.Notifications.NotificationsDomainBuilder(this.driver); 19 | }, 20 | 21 | notification: function() { 22 | return new corbel.Notifications.NotificationsBuilder(this.driver); 23 | } 24 | 25 | }, { 26 | 27 | moduleName: 'notifications', 28 | defaultPort: 8094, 29 | 30 | create: function(driver) { 31 | return new corbel.Notifications(driver); 32 | } 33 | 34 | }); 35 | 36 | 37 | return corbel.Notifications; 38 | 39 | })(); 40 | -------------------------------------------------------------------------------- /src/notifications/notificationsBuilder.js: -------------------------------------------------------------------------------- 1 | //@exclude 2 | 'use strict'; 3 | //@endexclude 4 | 5 | (function() { 6 | 7 | var NotificationsBuilder = corbel.Notifications.NotificationsBuilder = corbel.Notifications.BaseNotifications.inherit({ 8 | 9 | /** 10 | * Creates a new NotificationsBuilder 11 | * @return {corbel.Notification.NotificationBuilder} 12 | */ 13 | constructor: function(driver) { 14 | this.driver = driver; 15 | this.uri = 'notification'; 16 | }, 17 | 18 | /** 19 | * Send a notification 20 | * @method 21 | * @memberOf Corbel.Notifications.NotificationsBuilder 22 | * @param {Object} notification Notification 23 | * @param {String} notification.notificationId Notification id (mail, sms...) 24 | * @param {String} notification.recipient Notification recipient 25 | * @param {Object} notification.propierties Notification propierties 26 | * @return {Promise} Promise that resolves to undefined (void) or rejects with a {@link CorbelError} 27 | */ 28 | send: function(notification) { 29 | console.log('notificationsInterface.notification.sendNotification', notification); 30 | this.uri += '/send'; 31 | return this.request({ 32 | url: this.buildUri(this.uri), 33 | method: corbel.request.method.POST, 34 | data: notification 35 | }); 36 | } 37 | 38 | }, { 39 | 40 | moduleName: 'notifications', 41 | 42 | create: function(driver) { 43 | return new corbel.NotificationsBuilder(driver); 44 | } 45 | 46 | }); 47 | 48 | return NotificationsBuilder; 49 | 50 | })(); 51 | -------------------------------------------------------------------------------- /src/notifications/notificationsDomainBuilder.js: -------------------------------------------------------------------------------- 1 | //@exclude 2 | 'use strict'; 3 | //@endexclude 4 | 5 | (function() { 6 | 7 | var NotificationsDomainBuilder = corbel.Notifications.NotificationsDomainBuilder = corbel.Notifications.BaseNotifications.inherit({ 8 | 9 | /** 10 | * Creates a new NotificationsDomainBuilder 11 | * @return {corbel.Notification.NotificationDomainBuilder} 12 | */ 13 | constructor: function(driver) { 14 | this.driver = driver; 15 | this.uri = 'domain'; 16 | }, 17 | /* 18 | * Creates a new notification domain 19 | * @method 20 | * @memberOf Corbel.Notifications.NotificationsDomainBuilder 21 | * @param {Object} notification Contains the data of the new notification 22 | * @param {String} notification.properties Notification domain properties 23 | * @param {String} notification.templates Notification templates 24 | * 25 | * @return {Promise} Promise that resolves in the new notification domain id or rejects with a {@link CorbelError} 26 | */ 27 | create: function(domain) { 28 | console.log('notificationsInterface.domain.create', domain); 29 | return this.request({ 30 | url: this.buildUri(this.uri), 31 | method: corbel.request.method.POST, 32 | data: domain 33 | }). 34 | then(function(res) { 35 | return corbel.Services.getLocationId(res); 36 | }); 37 | }, 38 | /** 39 | * Gets a notification domain 40 | * @method 41 | * @memberOf Corbel.Notifications.NotificationsDomainBuilder 42 | * @return {Promise} Promise that resolves to a Notification {Object} or rejects with a {@link CorbelError} 43 | */ 44 | get: function() { 45 | console.log('notificationsInterface.domain.get'); 46 | return this.request({ 47 | url: this.buildUri(this.uri), 48 | method: corbel.request.method.GET 49 | }); 50 | }, 51 | /** 52 | * Updates a notification domain 53 | * @method 54 | * @memberOf Corbel.Notifications.NotificationsDomainBuilder 55 | * @param {Object} data Data to be updated 56 | * 57 | * @return {Promise} Promise that resolves to undefined (void) or rejects with a {@link CorbelError} 58 | */ 59 | update: function(data) { 60 | console.log('notificationsInterface.domain.update', data); 61 | return this.request({ 62 | url: this.buildUri(this.uri), 63 | method: corbel.request.method.PUT, 64 | data: data 65 | }); 66 | }, 67 | /** 68 | * Deletes a notification domain 69 | * @method 70 | * @memberOf Corbel.Notifications.NotificationsDomainBuilder 71 | * @return {Promise} Promise that resolves to undefined (void) or rejects with a {@link CorbelError} 72 | */ 73 | delete: function() { 74 | console.log('notificationsInterface.domain.delete'); 75 | return this.request({ 76 | url: this.buildUri(this.uri), 77 | method: corbel.request.method.DELETE 78 | }); 79 | } 80 | 81 | }, { 82 | 83 | moduleName: 'notifications', 84 | 85 | create: function(driver) { 86 | return new corbel.NotificationsDomainBuilder(driver); 87 | } 88 | 89 | }); 90 | 91 | return NotificationsDomainBuilder; 92 | 93 | })(); 94 | -------------------------------------------------------------------------------- /src/notifications/notificationsTemplateBuilder.js: -------------------------------------------------------------------------------- 1 | (function() { 2 | //@exclude 3 | 'use strict'; 4 | //@endexclude 5 | 6 | corbel.Notifications.NotificationsTemplateBuilder = corbel.Notifications.BaseNotifications.inherit({ 7 | 8 | /** 9 | * Creates a new NotificationsTemplateBuilder 10 | * @param {String} id of the notification template 11 | * @return {corbel.Notification.NotificationTemplateBuilder} 12 | */ 13 | constructor: function(driver, id) { 14 | this.driver = driver; 15 | this.uri = 'notification'; 16 | this.id = id; 17 | }, 18 | /* 19 | * Creates a new notification template 20 | * @method 21 | * @memberOf Corbel.Notifications.NotificationsTemplateBuilder 22 | * @param {Object} notification Contains the data of the new notification 23 | * @param {String} notification.type Notification type (mail, sms...) 24 | * @param {String} notification.text Notification content 25 | * @param {String} notification.sender Notification sender 26 | * @param {String} [notification.title] Notification title 27 | * 28 | * @return {Promise} Promise that resolves in the new notification id or rejects with a {@link CorbelError} 29 | */ 30 | create: function(notification) { 31 | console.log('notificationsInterface.template.create', notification); 32 | return this.request({ 33 | url: this.buildUri(this.uri), 34 | method: corbel.request.method.POST, 35 | data: notification 36 | }). 37 | then(function(res) { 38 | return corbel.Services.getLocationId(res); 39 | }); 40 | }, 41 | /** 42 | * Gets a notification template 43 | * @method 44 | * @memberOf Corbel.Notifications.NotificationsTemplateBuilder 45 | * @param {Object} [params] Params of the corbel request 46 | * @return {Promise} Promise that resolves to a Notification {Object} or rejects with a {@link CorbelError} 47 | */ 48 | get: function(params) { 49 | console.log('notificationsInterface.template.get', params); 50 | return this.request({ 51 | url: this.buildUri(this.uri, this.id), 52 | method: corbel.request.method.GET, 53 | query: params ? corbel.utils.serializeParams(params) : null 54 | }); 55 | }, 56 | /** 57 | * Updates a notification template 58 | * @method 59 | * @memberOf Corbel.Notifications.NotificationsTemplateBuilder 60 | * @param {Object} data Data to be updated 61 | * 62 | * @return {Promise} Promise that resolves to undefined (void) or rejects with a {@link CorbelError} 63 | */ 64 | update: function(data) { 65 | console.log('notificationsInterface.template.update', data); 66 | corbel.validate.value('id', this.id); 67 | return this.request({ 68 | url: this.buildUri(this.uri, this.id), 69 | method: corbel.request.method.PUT, 70 | data: data 71 | }); 72 | }, 73 | /** 74 | * Deletes a notification template 75 | * @method 76 | * @memberOf Corbel.Notifications.NotificationsTemplateBuilder 77 | * @return {Promise} Promise that resolves to undefined (void) or rejects with a {@link CorbelError} 78 | */ 79 | delete: function() { 80 | console.log('notificationsInterface.template.delete'); 81 | corbel.validate.value('id', this.id); 82 | return this.request({ 83 | url: this.buildUri(this.uri, this.id), 84 | method: corbel.request.method.DELETE 85 | }); 86 | } 87 | 88 | }, { 89 | 90 | moduleName: 'notifications', 91 | 92 | create: function(driver) { 93 | return new corbel.NotificationsTemplateBuilder(driver); 94 | } 95 | 96 | }); 97 | 98 | return corbel.Notifications.NotificationsTemplateBuilder; 99 | 100 | })(); 101 | -------------------------------------------------------------------------------- /src/oauth/oauth.js: -------------------------------------------------------------------------------- 1 | //@exclude 2 | 'use strict'; 3 | //@endexclude 4 | 5 | (function () { 6 | 7 | /** 8 | * A module to make Oauth requests. 9 | * @exports Oauth 10 | * @namespace 11 | * @memberof app.corbel 12 | */ 13 | 14 | var Oauth = corbel.Oauth = function (driver) { 15 | this.driver = driver; 16 | }; 17 | 18 | Oauth.moduleName = 'oauth'; 19 | Oauth.defaultPort = 8084; 20 | 21 | Oauth.create = function (driver) { 22 | return new Oauth(driver); 23 | }; 24 | /** 25 | * Private method to build a string uri 26 | * @private 27 | * @param {String} uri 28 | * @return {String} 29 | */ 30 | Oauth._buildUri = function (uri) { 31 | 32 | var urlBase = this.driver.config.getCurrentEndpoint(Oauth.moduleName, corbel.Oauth._buildPort(this.driver.config)); 33 | 34 | return urlBase + uri; 35 | }; 36 | 37 | Oauth._buildPort = function (config) { 38 | return config.get('oauthPort', null) || corbel.Oauth.defaultPort; 39 | }; 40 | 41 | /** 42 | * Default encoding 43 | * @type {String} 44 | * @default application/x-www-form-urlencoded; charset=UTF-8 45 | */ 46 | Oauth._URL_ENCODED = 'application/x-www-form-urlencoded; charset=UTF-8'; 47 | 48 | Oauth._checkProp = function (dict, keys, excep) { 49 | var error = excep ? excep : 'Error validating arguments'; 50 | if (!dict) { 51 | throw new Error(error); 52 | } 53 | for (var i in keys) { 54 | if (!(keys[i] in dict)) { 55 | throw new Error(error); 56 | } 57 | } 58 | }; 59 | 60 | Oauth._validateResponseType = function (responseType) { 61 | if (['code', 'token'].indexOf(responseType) < 0) { 62 | throw new Error('Only "code" or "token" response type allowed'); 63 | } 64 | }; 65 | 66 | Oauth._validateGrantType = function (grantType) { 67 | if (grantType !== 'authorization_code') { 68 | throw new Error('Only "authorization_code" grant type is allowed'); 69 | } 70 | }; 71 | 72 | Oauth._trasformParams = function (clientParams) { 73 | 74 | for (var key in clientParams) { 75 | var keyWithUnderscores = this._toUnderscore(key); 76 | if (key !== keyWithUnderscores) { 77 | clientParams[keyWithUnderscores] = clientParams[key]; 78 | delete clientParams[key]; 79 | } 80 | } 81 | return clientParams; 82 | }; 83 | 84 | Oauth._toUnderscore = function (string) { 85 | return string.replace(/([A-Z])/g, function ($1) { 86 | return '_' + $1.toLowerCase(); 87 | }); 88 | }; 89 | })(); 90 | -------------------------------------------------------------------------------- /src/oauth/tokenBuilder.js: -------------------------------------------------------------------------------- 1 | //@exclude 2 | 'use strict'; 3 | //@endexclude 4 | 5 | (function () { 6 | /** 7 | * Create a TokenBuilder for token managing requests. 8 | * Starts to build a token request 9 | * @method 10 | * @param {Object} clientParams 11 | * @param {String} [clientParams.clientId=corbel.Config.get('oauthClientId')] Client id 12 | * @param {String} [clientParams.clientSecret=corbel.Config.get('oauthSecret')] Client secret 13 | * @param {String} clientParams.grantType The grant type (only allowed 'authorization_code') 14 | * @return {corbel.Oauth.TokenBuilder} 15 | */ 16 | corbel.Oauth.prototype.token = function (clientParams) { 17 | console.log('oauthInterface.token'); 18 | 19 | corbel.Oauth._checkProp(clientParams, ['grantType'], 'Invalid client parameters'); 20 | corbel.Oauth._validateGrantType(clientParams.grantType); 21 | 22 | clientParams.clientId = clientParams.clientId || corbel.Config.get('OAUTH_DEFAULT.clientId'); 23 | clientParams.clientSecret = clientParams.clientSecret || corbel.Config.get('OAUTH_DEFAULT.clientSecret'); 24 | 25 | var params = { 26 | contentType: corbel.Oauth._URL_ENCODED, 27 | data: corbel.Oauth._trasformParams(clientParams) 28 | }; 29 | 30 | var token = new TokenBuilder(params); 31 | token.driver = this.driver; 32 | 33 | return token; 34 | }; 35 | /** 36 | * A builder for a token management requests. 37 | * @class 38 | * 39 | * @param {Object} params Initial params 40 | * 41 | * @memberOf corbel.Oauth.TokenBuilder 42 | */ 43 | var TokenBuilder = corbel.Oauth.TokenBuilder = corbel.Services.inherit({ 44 | 45 | constructor: function (params) { 46 | this.params = params; 47 | this.uri = 'oauth/token'; 48 | }, 49 | /** 50 | * Get an access token 51 | * @method 52 | * @memberOf corbel.Oauth.TokenBuilder 53 | * 54 | * @param {String} code The code to exchange for the token 55 | * 56 | * @return {Promise} promise that resolves to an access token {Object} or rejects with a {@link CorbelError} 57 | */ 58 | get: function (code) { 59 | console.log('oauthInterface.token.get'); 60 | this.params.data.code = code; 61 | 62 | return this.request({ 63 | url: this._buildUri(this.uri), 64 | method: corbel.request.method.POST, 65 | contentType: 'application/x-www-form-urlencoded; charset=UTF-8', 66 | data: this.params.data 67 | }); 68 | }, 69 | 70 | _buildUri: corbel.Oauth._buildUri 71 | }); 72 | })(); 73 | -------------------------------------------------------------------------------- /src/object.js: -------------------------------------------------------------------------------- 1 | //@exclude 2 | 'use strict'; 3 | //@endexclude 4 | 5 | (function() { 6 | 7 | /** 8 | * Base object with 9 | * @class 10 | * @exports Object 11 | * @namespace 12 | * @memberof corbel 13 | */ 14 | corbel.Object = function() { 15 | return this; 16 | }; 17 | 18 | /** 19 | * Gets my user assets 20 | * @memberof corbel.Object 21 | * @see corbel.utils.inherit 22 | * @return {Object} 23 | */ 24 | corbel.Object.inherit = corbel.utils.inherit; 25 | 26 | return corbel.Object; 27 | 28 | })(); -------------------------------------------------------------------------------- /src/request-params/aggregation-builder.js: -------------------------------------------------------------------------------- 1 | //@exclude 2 | 'use strict'; 3 | /* jshint unused:false */ 4 | //@endexclude 5 | 6 | 7 | var aggregationBuilder = (function() { 8 | 9 | var aggregationBuilder = {}; 10 | 11 | /** 12 | * Adds a count operation to aggregation 13 | * @param {String} field Name of the field to aggregate or * to aggregate all 14 | * @return {RequestParamsBuilder} RequestParamsBuilder 15 | */ 16 | aggregationBuilder.count = function(field) { 17 | this.params.aggregation = this.params.aggregation || {}; 18 | this.params.aggregation.$count = field; 19 | return this; 20 | }; 21 | 22 | return aggregationBuilder; 23 | 24 | })(); -------------------------------------------------------------------------------- /src/request-params/page-builder.js: -------------------------------------------------------------------------------- 1 | //@exclude 2 | 'use strict'; 3 | /* jshint unused:false */ 4 | //@endexclude 5 | 6 | 7 | var pageBuilder = (function() { 8 | 9 | var pageBuilder = {}; 10 | 11 | /** 12 | * Sets the page number of the page param 13 | * @param {int} page 14 | * @return {RequestParamsBuilder} RequestParamsBuilder 15 | */ 16 | pageBuilder.page = function(page) { 17 | this.params.pagination = this.params.pagination || {}; 18 | this.params.pagination.page = page; 19 | return this; 20 | }; 21 | 22 | /** 23 | * Sets the page size of the page param 24 | * @param {int} size 25 | * @return {RequestParamsBuilder} RequestParamsBuilder 26 | */ 27 | pageBuilder.pageSize = function(pageSize) { 28 | this.params.pagination = this.params.pagination || {}; 29 | this.params.pagination.pageSize = pageSize; 30 | return this; 31 | }; 32 | 33 | /** 34 | * Sets the page number and page size of the page param 35 | * @param {int} size 36 | * @return {RequestParamsBuilder} RequestParamsBuilder 37 | */ 38 | pageBuilder.pageParam = function(page, pageSize) { 39 | this.params.pagination = this.params.pagination || {}; 40 | this.params.pagination.page = page; 41 | this.params.pagination.pageSize = pageSize; 42 | return this; 43 | }; 44 | 45 | return pageBuilder; 46 | 47 | 48 | })(); 49 | -------------------------------------------------------------------------------- /src/request-params/query-builder.js: -------------------------------------------------------------------------------- 1 | //@exclude 2 | 'use strict'; 3 | /* jshint unused:false */ 4 | //@endexclude 5 | 6 | 7 | var queryBuilder = (function() { 8 | 9 | var queryBuilder = {}; 10 | 11 | /** 12 | * Adds an Equal criteria to query 13 | * @param {String} field 14 | * @param {String | Number | Date} value 15 | * @return {RequestParamsBuilder} RequestParamsBuilder 16 | */ 17 | queryBuilder.eq = function(field, value) { 18 | this.addCriteria('$eq', field, value); 19 | return this; 20 | }; 21 | 22 | /** 23 | * Adds a Greater Than criteria to query 24 | * @param {String} field 25 | * @param {String | Number | Date} value 26 | * @return {RequestParamsBuilder} RequestParamsBuilder 27 | */ 28 | queryBuilder.gt = function(field, value) { 29 | this.addCriteria('$gt', field, value); 30 | return this; 31 | }; 32 | 33 | /** 34 | * Adds a Greater Than Or Equal criteria to query 35 | * @param {String} field 36 | * @param {String | Number | Date} value 37 | * @return {RequestParamsBuilder} RequestParamsBuilder 38 | */ 39 | queryBuilder.gte = function(field, value) { 40 | this.addCriteria('$gte', field, value); 41 | return this; 42 | }; 43 | 44 | /** 45 | * Adds a Less Than criteria to query 46 | * @param {String} field 47 | * @param {String | Number | Date} value 48 | * @return {RequestParamsBuilder} RequestParamsBuilder 49 | */ 50 | queryBuilder.lt = function(field, value) { 51 | this.addCriteria('$lt', field, value); 52 | return this; 53 | }; 54 | 55 | /** 56 | * Adds a Less Than Or Equal criteria to query 57 | * @param {String} field 58 | * @param {String | Number | Date} value 59 | * @return {RequestParamsBuilder} RequestParamsBuilder 60 | */ 61 | queryBuilder.lte = function(field, value) { 62 | this.addCriteria('$lte', field, value); 63 | return this; 64 | }; 65 | 66 | /** 67 | * Adds a Not Equal criteria to query 68 | * @param {String} field 69 | * @param {String | Number | Date} value 70 | * @return {RequestParamsBuilder} RequestParamsBuilder 71 | */ 72 | queryBuilder.ne = function(field, value) { 73 | this.addCriteria('$ne', field, value); 74 | return this; 75 | }; 76 | 77 | /** 78 | * Adds a Like criteria to query 79 | * @param {String} field 80 | * @param {String | Number | Date} value 81 | * @return {RequestParamsBuilder} RequestParamsBuilder 82 | */ 83 | queryBuilder.like = function(field, value) { 84 | this.addCriteria('$like', field, value); 85 | return this; 86 | }; 87 | 88 | /** 89 | * Adds an In criteria to query 90 | * @param {String} field 91 | * @param {String[]|Number[]|Date[]} values 92 | * @return {RequestParamsBuilder} RequestParamsBuilder 93 | */ 94 | queryBuilder.in = function(field, values) { 95 | this.addCriteria('$in', field, values); 96 | return this; 97 | }; 98 | 99 | /** 100 | * Adds an All criteria to query 101 | * @param {String} field 102 | * @param {String[]|Number[]|Date[]} values 103 | * @return {RequestParamsBuilder} RequestParamsBuilder 104 | */ 105 | queryBuilder.all = function(field, values) { 106 | this.addCriteria('$all', field, values); 107 | return this; 108 | }; 109 | 110 | /** 111 | * Adds an Element Match criteria to query 112 | * @param {String} field 113 | * @param {JSON} value Query for the matching 114 | * @return {RequestParamsBuilder} RequestParamsBuilder 115 | */ 116 | queryBuilder.elemMatch = function(field, query) { 117 | this.addCriteria('$elem_match', field, query); 118 | return this; 119 | }; 120 | 121 | /** 122 | * Sets an specific queryDomain, by default 'api'. 123 | * @param {String} queryDomain query domain name, 'api' and '7digital' supported 124 | */ 125 | queryBuilder.setQueryDomain = function(queryDomain) { 126 | this.params.queryDomain = queryDomain; 127 | return this; 128 | }; 129 | 130 | queryBuilder.addCriteria = function(operator, field, value) { 131 | var criteria = {}; 132 | criteria[operator] = {}; 133 | criteria[operator][field] = value; 134 | this.params.query = this.params.query || []; 135 | this.params.query.push(criteria); 136 | return this; 137 | }; 138 | 139 | return queryBuilder; 140 | 141 | })(); -------------------------------------------------------------------------------- /src/request-params/request-params-builder.js: -------------------------------------------------------------------------------- 1 | //@exclude 2 | 'use strict'; 3 | /* global corbel, aggregationBuilder, queryBuilder, sortBuilder, pageBuilder */ 4 | //@endexclude 5 | 6 | 7 | (function(aggregationBuilder, queryBuilder, sortBuilder, pageBuilder) { 8 | 9 | 10 | 11 | /** 12 | * A module to build Request Params 13 | * @exports requestParamsBuilder 14 | * @namespace 15 | * @memberof app.silkroad 16 | */ 17 | corbel.requestParamsBuilder = corbel.Object.inherit({ 18 | constructor: function() { 19 | this.params = {}; 20 | }, 21 | /** 22 | * Returns the JSON representation of the params 23 | * @return {JSON} representation of the params 24 | */ 25 | build: function() { 26 | return this.params; 27 | } 28 | }); 29 | 30 | 31 | corbel.utils.extend(corbel.requestParamsBuilder.prototype, queryBuilder, sortBuilder, aggregationBuilder, pageBuilder); 32 | 33 | return corbel.requestParamsBuilder; 34 | 35 | })(aggregationBuilder, queryBuilder, sortBuilder, pageBuilder); -------------------------------------------------------------------------------- /src/request-params/sort-builder.js: -------------------------------------------------------------------------------- 1 | //@exclude 2 | 'use strict'; 3 | /* jshint unused:false */ 4 | //@endexclude 5 | 6 | 7 | var sortBuilder = (function() { 8 | 9 | var sortBuilder = {}; 10 | 11 | /** 12 | * Sets ascending direction to sort param 13 | * @return {RequestParamsBuilder} RequestParamsBuilder 14 | */ 15 | sortBuilder.asc = function(field) { 16 | this.params.sort = this.params.sort || {}; 17 | this.params.sort[field] = corbel.Resources.sort.ASC; 18 | return this; 19 | }; 20 | 21 | /** 22 | * Sets descending direction to sort param 23 | * @return {RequestParamsBuilder} RequestParamsBuilder 24 | */ 25 | sortBuilder.desc = function(field) { 26 | this.params.sort = this.params.sort || {}; 27 | this.params.sort[field] = corbel.Resources.sort.DESC; 28 | return this; 29 | }; 30 | 31 | return sortBuilder; 32 | })(); -------------------------------------------------------------------------------- /src/resources/base-resource.js: -------------------------------------------------------------------------------- 1 | (function() { 2 | //@exclude 3 | 'use strict'; 4 | //@endexclude 5 | 6 | corbel.Resources.BaseResource = corbel.Services.inherit({ 7 | 8 | /** 9 | * Helper function to build the request uri 10 | * @param {String} srcType Type of the resource 11 | * @param {String} srcId Id of the resource 12 | * @param {String} relType Type of the relationed resource 13 | * @param {String} destId Information of the relationed resource 14 | * @return {String} Uri to perform the request 15 | */ 16 | buildUri: function(srcType, srcId, destType, destId) { 17 | 18 | var urlBase = this.driver.config.getCurrentEndpoint(corbel.Resources.moduleName, this._buildPort(this.driver.config)); 19 | 20 | var domain = this.driver.config.get(corbel.Iam.IAM_DOMAIN, 'unauthenticated'); 21 | var customDomain = this.driver.config.get(corbel.Domain.CUSTOM_DOMAIN, domain); 22 | 23 | this.driver.config.set(corbel.Domain.CUSTOM_DOMAIN, undefined); 24 | 25 | var uri = urlBase + customDomain +'/resource/' + srcType; 26 | 27 | if (srcId) { 28 | uri += '/' + srcId; 29 | if (destType) { 30 | uri += '/' + destType; 31 | if (destId) { 32 | uri += ';r=' + destType + '/' + destId; 33 | } 34 | } 35 | } 36 | 37 | return uri; 38 | }, 39 | 40 | _buildPort: function(config) { 41 | return config.get('resourcesPort', null) || corbel.Resources.defaultPort; 42 | }, 43 | 44 | request: function(args) { 45 | var params = corbel.utils.extend(this.params, args); 46 | 47 | this.params = {}; //reset instance params 48 | 49 | args.query = corbel.utils.serializeParams(params); 50 | 51 | //call service request implementation 52 | return corbel.Services.prototype.request.apply(this, [args].concat(Array.prototype.slice.call(arguments, 1))); 53 | }, 54 | 55 | getURL: function(params) { 56 | return this.buildUri(this.type, this.srcId, this.destType) + (params ? '?' + corbel.utils.serializeParams(params) : ''); 57 | }, 58 | 59 | getDefaultOptions: function(options) { 60 | var defaultOptions = options ? corbel.utils.clone(options) : {}; 61 | 62 | return defaultOptions; 63 | } 64 | 65 | }); 66 | 67 | // extend for inherit requestParamsBuilder methods extensible for all Resources object 68 | corbel.utils.extend(corbel.Resources.BaseResource.prototype, corbel.requestParamsBuilder.prototype); 69 | 70 | return corbel.Resources.BaseResource; 71 | 72 | })(); 73 | -------------------------------------------------------------------------------- /src/resources/collection.js: -------------------------------------------------------------------------------- 1 | (function() { 2 | 3 | //@exclude 4 | 'use strict'; 5 | /*globals corbel */ 6 | //@endexclude 7 | 8 | /** 9 | * Collection requests 10 | * @class 11 | * @memberOf Resources 12 | * @param {String} type The collection type 13 | * @param {CorbelDriver} corbel instance 14 | */ 15 | corbel.Resources.Collection = corbel.Resources.BaseResource.inherit({ 16 | 17 | constructor: function(type, driver, params) { 18 | this.type = type; 19 | corbel.validate.value('type', this.type); 20 | this.driver = driver; 21 | this.params = params || {}; 22 | }, 23 | 24 | /** 25 | * Gets a collection of elements, filtered, paginated or sorted 26 | * @method 27 | * @memberOf Resources.CollectionBuilder 28 | * @param {object} options Get options for the request 29 | * @return {Promise} ES6 promise that resolves to an {Array} of Resources or rejects with a {@link CorbelError} 30 | * @see {@link corbel.util.serializeParams} to see a example of the params 31 | */ 32 | get: function(options) { 33 | options = this.getDefaultOptions(options); 34 | 35 | var args = corbel.utils.extend(options, { 36 | url: this.buildUri(this.type), 37 | method: corbel.request.method.GET, 38 | Accept: options.dataType 39 | }); 40 | 41 | return this.request(args); 42 | }, 43 | 44 | /** 45 | * Adds a new element to a collection 46 | * @method 47 | * @memberOf Resources.CollectionBuilder 48 | * @param {object} data Data array added to the collection 49 | * @param {object} options Options object with dataType request option 50 | * @return {Promise} ES6 promise that resolves to the new resource id or rejects with a {@link CorbelError} 51 | */ 52 | add: function(data, options) { 53 | options = this.getDefaultOptions(options); 54 | 55 | var args = corbel.utils.extend(options, { 56 | url: this.buildUri(this.type), 57 | method: corbel.request.method.POST, 58 | contentType: options.dataType, 59 | Accept: options.dataType, 60 | data: data 61 | }); 62 | 63 | return this.request(args).then(function(res) { 64 | return corbel.Services.getLocationId(res); 65 | }); 66 | }, 67 | 68 | /** 69 | * Update every element in a collection, accepts query params 70 | * @method 71 | * @memberOf resources.CollectionBuilder 72 | * @param {Object} data The element to be updated 73 | * @param {Object} options/query Options object with dataType request option 74 | * @return {Promise} ES6 promise that resolves to an {Array} of resources or rejects with a {@link CorbelError} 75 | */ 76 | update: function(data, options) { 77 | options = this.getDefaultOptions(options); 78 | 79 | var args = corbel.utils.extend(options, { 80 | url: this.buildUri(this.type), 81 | method: corbel.request.method.PUT, 82 | contentType: options.dataType, 83 | Accept: options.dataType, 84 | data: data 85 | }); 86 | 87 | return this.request(args); 88 | }, 89 | 90 | /** 91 | * Delete a collection 92 | * @method 93 | * @memberOf Resources.CollectionBuilder 94 | * @param {object} options Options object with dataType request option 95 | * @return {Promise} ES6 promise that resolves to the new resource id or rejects with a {@link CorbelError} 96 | */ 97 | delete: function(options) { 98 | options = this.getDefaultOptions(options); 99 | 100 | var args = corbel.utils.extend(options, { 101 | url: this.buildUri(this.type), 102 | method: corbel.request.method.DELETE, 103 | contentType: options.dataType, 104 | Accept: options.dataType 105 | }); 106 | 107 | return this.request(args); 108 | } 109 | 110 | }); 111 | 112 | return corbel.Resources.Collection; 113 | 114 | })(); 115 | -------------------------------------------------------------------------------- /src/resources/relation.js: -------------------------------------------------------------------------------- 1 | (function() { 2 | //@exclude 3 | 'use strict'; 4 | /*globals corbel */ 5 | //@endexclude 6 | 7 | /** 8 | * Relation 9 | * @class 10 | * @memberOf Resources 11 | * @param {String} srcType The source resource type 12 | * @param {String} srcId The source resource id 13 | * @param {String} destType The destination resource type 14 | */ 15 | corbel.Resources.Relation = corbel.Resources.BaseResource.inherit({ 16 | 17 | constructor: function(srcType, srcId, destType, driver, params) { 18 | this.type = srcType; 19 | this.srcId = srcId; 20 | this.destType = destType; 21 | corbel.validate.values(['type', 'srcId', 'destType'],this); 22 | this.driver = driver; 23 | this.params = params || {}; 24 | }, 25 | 26 | /** 27 | * Gets the resources of a relation 28 | * @method 29 | * @memberOf Resources.Relation 30 | * @param {String} dataType Mime type of the expected resource 31 | * @param {String} destId Relationed resource 32 | * @param {Object} params Params of the corbel request 33 | * @return {Promise} ES6 promise that resolves to a relation {Object} or rejects with a {@link CorbelError} 34 | * @see {@link corbel.util.serializeParams} to see a example of the params 35 | */ 36 | get: function(destId, options) { 37 | options = this.getDefaultOptions(options); 38 | var args = corbel.utils.extend(options, { 39 | url: this.buildUri(this.type, this.srcId, this.destType, destId), 40 | method: corbel.request.method.GET, 41 | Accept: options.dataType 42 | }); 43 | 44 | return this.request(args); 45 | }, 46 | 47 | /** 48 | * Adds a new relation between Resources 49 | * @method 50 | * @memberOf Resources.Relation 51 | * @param {String} destId Relationed resource 52 | * @param {Object} relationData Additional data to be added to the relation (in json) 53 | * @return {Promise} ES6 promise that resolves to undefined (void) or rejects with a {@link CorbelError} 54 | * @example uri = '555' 55 | */ 56 | add: function(destId, relationData, options) { 57 | options = this.getDefaultOptions(options); 58 | corbel.validate.value('destId', destId); 59 | 60 | var args = corbel.utils.extend(options, { 61 | url: this.buildUri(this.type, this.srcId, this.destType, destId), 62 | data: relationData, 63 | method: corbel.request.method.PUT, 64 | contentType: options.dataType, 65 | Accept: options.dataType 66 | }); 67 | 68 | return this.request(args); 69 | }, 70 | 71 | /** 72 | * Adds a new anonymous relation 73 | * @method 74 | * @memberOf Resources.Relation 75 | * @param {Object} relationData Additional data to be added to the relation (in json) 76 | * @return {Promise} ES6 promise that resolves to undefined (void) or rejects with a {@link CorbelError} 77 | * @example uri = '555' 78 | */ 79 | addAnonymous: function(relationData, options) { 80 | options = this.getDefaultOptions(options); 81 | 82 | var args = corbel.utils.extend(options, { 83 | url: this.buildUri(this.type, this.srcId, this.destType), 84 | data: relationData, 85 | method: corbel.request.method.POST, 86 | contentType: options.dataType, 87 | Accept: options.dataType 88 | }); 89 | 90 | return this.request(args); 91 | }, 92 | 93 | /** 94 | * Move a relation 95 | * @method 96 | * @memberOf Resources.Relation 97 | * @param {Integer} pos The new position 98 | * @return {Promise} ES6 promise that resolves to undefined (void) or rejects with a {@link CorbelError} 99 | */ 100 | move: function(destId, pos, options) { 101 | corbel.validate.value('destId', destId); 102 | var positionStartId = destId.indexOf('/'); 103 | if (positionStartId !== -1){ 104 | destId = destId.substring(positionStartId + 1); 105 | } 106 | 107 | options = this.getDefaultOptions(options); 108 | 109 | var args = corbel.utils.extend(options, { 110 | url: this.buildUri(this.type, this.srcId, this.destType, destId), 111 | contentType: 'application/json', 112 | data: { 113 | '_order': '$pos(' + pos + ')' 114 | }, 115 | method: corbel.request.method.PUT 116 | }); 117 | 118 | return this.request(args); 119 | }, 120 | 121 | /** 122 | * Deletes a relation between Resources 123 | * @method 124 | * @memberOf Resources.Relation 125 | * @param {String} destId Relationed resource 126 | * @return {Promise} ES6 promise that resolves to undefined (void) or rejects with a {@link CorbelError} 127 | * @example 128 | * destId = 'music:Track/555' 129 | */ 130 | delete: function(destId, options) { 131 | options = this.getDefaultOptions(options); 132 | 133 | var args = corbel.utils.extend(options, { 134 | url: this.buildUri(this.type, this.srcId, this.destType, destId), 135 | method: corbel.request.method.DELETE, 136 | Accept: options.dataType 137 | }); 138 | 139 | return this.request(args); 140 | } 141 | }); 142 | 143 | return corbel.Resources.Relation; 144 | 145 | })(); 146 | -------------------------------------------------------------------------------- /src/resources/resource.js: -------------------------------------------------------------------------------- 1 | (function() { 2 | //@exclude 3 | 'use strict'; 4 | /*globals corbel */ 5 | //@endexclude 6 | 7 | /** 8 | * Builder for resource requests 9 | * @class 10 | * @memberOf resources 11 | * @param {String} type The resource type 12 | * @param {String} id The resource id 13 | */ 14 | corbel.Resources.Resource = corbel.Resources.BaseResource.inherit({ 15 | 16 | constructor: function(type, id, driver, params) { 17 | this.type = type; 18 | this.id = id; 19 | corbel.validate.values(['type', 'id'], this); 20 | 21 | this.driver = driver; 22 | this.params = params || {}; 23 | }, 24 | 25 | /** 26 | * Gets a resource 27 | * @method 28 | * @memberOf resources.Resource 29 | * @param {Object} options 30 | * @param {String} [options.dataType] Mime type of the expected resource 31 | * @param {Object} [options.params] Additional request parameters 32 | * @return {Promise} ES6 promise that resolves to a Resource {Object} or rejects with a {@link CorbelError} 33 | * @see {@link services.request} to see a example of the params 34 | */ 35 | get: function(options) { 36 | options = this.getDefaultOptions(options); 37 | 38 | 39 | var args = corbel.utils.extend(options, { 40 | url: this.buildUri(this.type, this.id), 41 | method: corbel.request.method.GET, 42 | contentType: options.dataType, 43 | Accept: options.dataType 44 | }); 45 | 46 | return this.request(args); 47 | }, 48 | 49 | 50 | /** 51 | * Updates a resource 52 | * @method 53 | * @memberOf resources.Resource 54 | * @param {Object} data Data to be updated 55 | * @param {Object} options 56 | * @param {String} [options.dataType] Mime tipe of the sent data 57 | * @param {Object} [options.params] Additional request parameters 58 | * @return {Promise} ES6 promise that resolves to undefined (void) or rejects with a {@link CorbelError} 59 | * @see {@link services.request} to see a example of the params 60 | */ 61 | update: function(data, options) { 62 | options = this.getDefaultOptions(options); 63 | 64 | var args = corbel.utils.extend(options, { 65 | url: this.buildUri(this.type, this.id), 66 | method: corbel.request.method.PUT, 67 | data: data, 68 | contentType: options.dataType, 69 | Accept: options.dataType 70 | }); 71 | 72 | return this.request(args); 73 | }, 74 | 75 | 76 | /** 77 | * Updates the ACL of a resource 78 | * @method 79 | * @memberOf resources.Resource 80 | * @param {Object} acl Acl to be updated 81 | * @return {Promise} ES6 promise that resolves to undefined (void) or rejects with a {@link CorbelError} 82 | */ 83 | updateAcl: function(acl) { 84 | var args = { 85 | url: this.buildUri(this.type, this.id), 86 | method: corbel.request.method.PUT, 87 | data: acl, 88 | Accept: 'application/corbel.acl+json' 89 | }; 90 | 91 | return this.request(args); 92 | }, 93 | 94 | /** 95 | * Deletes a resource 96 | * @method 97 | * @memberOf resources.Resource 98 | * @param {Object} options 99 | * @param {Object} [options.dataType] Mime tipe of the delete data 100 | * @return {Promise} ES6 promise that resolves to undefined (void) or rejects with a {@link CorbelError} 101 | */ 102 | delete: function(options) { 103 | options = this.getDefaultOptions(options); 104 | 105 | var args = corbel.utils.extend(options, { 106 | url: this.buildUri(this.type, this.id), 107 | method: corbel.request.method.DELETE, 108 | contentType: options.dataType, 109 | Accept: options.dataType 110 | }); 111 | 112 | return this.request(args); 113 | } 114 | }); 115 | 116 | return corbel.Resources.Resource; 117 | 118 | })(); 119 | -------------------------------------------------------------------------------- /src/resources/resources.js: -------------------------------------------------------------------------------- 1 | (function() { 2 | //@exclude 3 | 'use strict'; 4 | /*globals corbel */ 5 | //@endexclude 6 | 7 | corbel.Resources = corbel.Object.inherit({ 8 | 9 | constructor: function(driver) { 10 | this.driver = driver; 11 | }, 12 | 13 | collection: function(type) { 14 | return new corbel.Resources.Collection(type, this.driver); 15 | }, 16 | 17 | resource: function(type, id) { 18 | return new corbel.Resources.Resource(type, id, this.driver); 19 | }, 20 | 21 | relation: function(srcType, srcId, destType) { 22 | return new corbel.Resources.Relation(srcType, srcId, destType, this.driver); 23 | } 24 | 25 | }, { 26 | 27 | moduleName: 'resources', 28 | defaultPort: 8080, 29 | 30 | sort: { 31 | 32 | /** 33 | * Ascending sort 34 | * @type {String} 35 | * @constant 36 | * @default 37 | */ 38 | ASC: 'asc', 39 | 40 | /** 41 | * Descending sort 42 | * @type {String} 43 | * @constant 44 | * @default 45 | */ 46 | DESC: 'desc' 47 | 48 | }, 49 | 50 | /** 51 | * constant for use to specify all resources wildcard 52 | * @namespace 53 | */ 54 | ALL: '_', 55 | 56 | create: function(driver) { 57 | return new corbel.Resources(driver); 58 | } 59 | 60 | }); 61 | 62 | return corbel.Resources; 63 | 64 | })(); 65 | -------------------------------------------------------------------------------- /src/scheduler/scheduler.js: -------------------------------------------------------------------------------- 1 | (function() { 2 | //@exclude 3 | 'use strict'; 4 | /*globals corbel */ 5 | //@endexclude 6 | 7 | corbel.Scheduler = corbel.Object.inherit({ 8 | 9 | /** 10 | * Create a new SchedulerBuilder 11 | * @param {String} type String 12 | * @return {Scheduler} 13 | */ 14 | constructor: function(driver) { 15 | this.driver = driver; 16 | }, 17 | 18 | task: function(id) { 19 | return new corbel.Scheduler.TaskBuilder(this.driver, id); 20 | } 21 | }, { 22 | 23 | moduleName: 'scheduler', 24 | defaultPort: 8098, 25 | 26 | create: function(driver) { 27 | return new corbel.Scheduler(driver); 28 | } 29 | }); 30 | 31 | return corbel.Scheduler; 32 | })(); 33 | -------------------------------------------------------------------------------- /src/scheduler/schedulerBuilder.js: -------------------------------------------------------------------------------- 1 | //@exclude 2 | 'use strict'; 3 | //@endexclude 4 | 5 | (function() { 6 | 7 | var TaskBuilder = corbel.Scheduler.TaskBuilder = corbel.Services.inherit({ 8 | 9 | constructor: function(driver, id) { 10 | this.uri = 'tasks'; 11 | this.driver = driver; 12 | this.id = id; 13 | }, 14 | 15 | create: function(task) { 16 | console.log('schedulerInterface.task.create', task); 17 | return this.request({ 18 | url: this._buildUri(this.uri), 19 | method: corbel.request.method.POST, 20 | data: task 21 | }). 22 | then(function(res) { 23 | return corbel.Services.getLocationId(res); 24 | }); 25 | }, 26 | 27 | get: function(params) { 28 | console.log('schedulerInterface.task.get', params); 29 | corbel.validate.value('id', this.id); 30 | return this.request({ 31 | url: this._buildUri(this.uri, this.id), 32 | method: corbel.request.method.GET, 33 | query: params ? corbel.utils.serializeParams(params) : null 34 | }); 35 | }, 36 | 37 | update: function(task) { 38 | console.log('schedulerInterface.task.update', task); 39 | corbel.validate.value('id', this.id); 40 | return this.request({ 41 | url: this._buildUri(this.uri, this.id), 42 | method: corbel.request.method.PUT, 43 | data: task 44 | }); 45 | }, 46 | 47 | delete: function() { 48 | console.log('schedulerInterface.task.delete'); 49 | corbel.validate.value('id', this.id); 50 | return this.request({ 51 | url: this._buildUri(this.uri, this.id), 52 | method: corbel.request.method.DELETE 53 | }); 54 | }, 55 | 56 | _buildUri: function(path, id) { 57 | var uri = ''; 58 | var urlBase = this.driver.config.getCurrentEndpoint(corbel.Scheduler.moduleName, this._buildPort(this.driver.config)); 59 | 60 | uri = urlBase + path; 61 | if (id) { 62 | uri += '/' + id; 63 | } 64 | return uri; 65 | }, 66 | 67 | _buildPort: function(config) { 68 | return config.get('schedulerPort', null) || corbel.Notifications.defaultPort; 69 | } 70 | 71 | }, { 72 | 73 | moduleName: 'tasks', 74 | 75 | create: function(driver) { 76 | return new corbel.TaskBuilder(driver); 77 | } 78 | 79 | }); 80 | 81 | return TaskBuilder; 82 | 83 | })(); 84 | -------------------------------------------------------------------------------- /src/validate.js: -------------------------------------------------------------------------------- 1 | //@exclude 2 | 'use strict'; 3 | //@endexclude 4 | 5 | (function() { 6 | 7 | 8 | 9 | /** 10 | * A module to make values validation. 11 | * @exports validate 12 | * @namespace 13 | * @memberof app 14 | */ 15 | corbel.validate = {}; 16 | 17 | corbel.validate.values = function(keys, obj){ 18 | var that = this; 19 | keys.forEach(function(key){ 20 | that.value(key, obj[key]); 21 | }); 22 | return true; 23 | }; 24 | 25 | corbel.validate.value = function(key, value){ 26 | return this.isDefined(value, key + ' value is mandatory and cannot be undefined'); 27 | }; 28 | 29 | 30 | /** 31 | * Checks if some value is not undefined 32 | * @param {Mixed} value 33 | * @param {String} [message] 34 | * @throws {Error} If return value is false and message are defined 35 | * @return {Boolean} 36 | */ 37 | corbel.validate.isDefined = function(value, message) { 38 | var isUndefined = value === undefined; 39 | 40 | if (isUndefined && message) { 41 | throw new Error(message); 42 | } 43 | return !isUndefined; 44 | }; 45 | 46 | /** 47 | * Checks if some value is defined and throw error 48 | * @param {Mixed} value 49 | * @param {String} [message] 50 | * @throws {Error} If return value is false and message are defined 51 | * @return {Boolean} 52 | */ 53 | 54 | corbel.validate.failIfIsDefined = function(value, message) { 55 | var isDefined = value !== undefined; 56 | 57 | if (isDefined && message) { 58 | throw new Error(message); 59 | } 60 | return !isDefined; 61 | }; 62 | 63 | /** 64 | * Checks whenever value are null or not 65 | * @param {Mixed} value 66 | * @param {String} [message] 67 | * @throws {Error} If return value is false and message are defined 68 | * @return {Boolean} 69 | */ 70 | corbel.validate.isNotNull = function(value, message) { 71 | var isNull = value === null; 72 | 73 | if (isNull && message) { 74 | throw new Error(message); 75 | } 76 | return !isNull; 77 | }; 78 | 79 | /** 80 | * Checks whenever a value is not null and not undefined 81 | * @param {Mixed} value 82 | * @param {String} [message] 83 | * @throws {Error} If return value is false and message are defined 84 | * @return {Boolean} 85 | */ 86 | corbel.validate.isValue = function(value, message) { 87 | return this.isDefined(value, message) && this.isNotNull(value, message); 88 | }; 89 | 90 | /** 91 | * Checks if a variable is a type of object 92 | * @param {object} test object 93 | * @return {Boolean} 94 | */ 95 | corbel.validate.isObject = function(obj) { 96 | return typeof obj === 'object'; 97 | }; 98 | 99 | /** 100 | * Checks whenever a value is greater than other 101 | * @param {Mixed} value 102 | * @param {Mixed} greaterThan 103 | * @param {String} [message] 104 | * @throws {Error} If return value is false and message are defined 105 | * @return {Boolean} 106 | */ 107 | corbel.validate.isGreaterThan = function(value, greaterThan, message) { 108 | var gt = this.isValue(value) && value > greaterThan; 109 | 110 | if (!gt && message) { 111 | throw new Error(message); 112 | } 113 | return gt; 114 | }; 115 | 116 | /** 117 | * Checks whenever a value is greater or equal than other 118 | * @param {Mixed} value 119 | * @param {Mixed} isGreaterThanOrEqual 120 | * @param {String} [message] 121 | * @throws {Error} If return value is false and message are defined 122 | * @return {Boolean} 123 | */ 124 | corbel.validate.isGreaterThanOrEqual = function(value, isGreaterThanOrEqual, message) { 125 | var gte = this.isValue(value) && value >= isGreaterThanOrEqual; 126 | 127 | if (!gte && message) { 128 | throw new Error(message); 129 | } 130 | return gte; 131 | }; 132 | 133 | })(); -------------------------------------------------------------------------------- /src/webfs/webfs.js: -------------------------------------------------------------------------------- 1 | (function() { 2 | //@exclude 3 | 'use strict'; 4 | //@endexclude 5 | 6 | /** 7 | * A webfs API factory 8 | * @exports corbel.Webfs 9 | * @namespace 10 | * @extends corbel.Object 11 | * @memberof corbel 12 | */ 13 | corbel.Webfs = corbel.Object.inherit({ 14 | 15 | /** 16 | * Creates a new WebfsBuilder 17 | * @memberof corbel.Webfs.prototype 18 | * @param {string} id String with the resource id 19 | * @return {corbel.Webfs.WebfsBuilder} 20 | */ 21 | constructor: function(driver) { 22 | this.driver = driver; 23 | }, 24 | 25 | webfs: function(id) { 26 | return new corbel.Webfs.WebfsBuilder(this.driver, id); 27 | } 28 | 29 | }, { 30 | 31 | /** 32 | * moduleName constant 33 | * @constant 34 | * @memberof corbel.Webfs 35 | * @type {string} 36 | * @default 37 | */ 38 | moduleName: 'webfs', 39 | 40 | /** 41 | * defaultPort constant 42 | * @constant 43 | * @memberof corbel.Webfs 44 | * @type {Number} 45 | * @default 46 | */ 47 | defaultPort: 8096, 48 | 49 | /** 50 | * defaultDomain constant 51 | * @constant 52 | * @memberof corbel.Webfs 53 | * @type {Number} 54 | * @default 55 | */ 56 | defaultDomain: 'unauthenticated', 57 | 58 | domain: 'domain', 59 | 60 | /** 61 | * AssetsBuilder factory 62 | * @memberof corbel.Webfs 63 | * @param {corbel} corbel instance driver 64 | * @return {corbel.Webfs.WebfsBuilder} 65 | */ 66 | create: function(driver) { 67 | return new corbel.Webfs(driver); 68 | } 69 | 70 | }); 71 | 72 | return corbel.Webfs; 73 | 74 | })(); 75 | -------------------------------------------------------------------------------- /src/webfs/webfsBuilder.js: -------------------------------------------------------------------------------- 1 | //@exclude 2 | 'use strict'; 3 | //@endexclude 4 | 5 | (function() { 6 | 7 | /** 8 | * Module for retrieve content of S3 9 | * @exports WebfsBuilder 10 | * @namespace 11 | * @extends corbel.Services 12 | * @memberof corbel.Webfs 13 | */ 14 | var WebfsBuilder = corbel.Webfs.WebfsBuilder = corbel.Services.inherit({ 15 | 16 | /** 17 | * Creates a new WebfsBuilder 18 | * @memberof corbel.Webfs.WebfsBuilder.prototype 19 | * @return {corbel.Webfs.WebfsBuilder} 20 | */ 21 | constructor: function(driver, id) { 22 | this.driver = driver; 23 | this.id = id; 24 | }, 25 | 26 | /** 27 | * Gets the content 28 | * @memberof corbel.Webfs.WebfsBuilder.prototype 29 | * @param {object} [params] Params of a {@link corbel.request} 30 | * @return {Promise} Promise that resolves with a resource or rejects with a {@link CorbelError} 31 | */ 32 | get: function(params) { 33 | 34 | corbel.validate.value('id', this.id); 35 | 36 | var options = params ? corbel.utils.clone(params) : {}; 37 | 38 | var args = corbel.utils.extend(options, { 39 | url: this._buildUriWithDomain(this.id), 40 | method: corbel.request.method.GET, 41 | query: params ? corbel.utils.serializeParams(params) : null 42 | }); 43 | 44 | return this.request(args); 45 | 46 | }, 47 | 48 | delete: function(){ 49 | 50 | corbel.validate.value('id', this.id); 51 | 52 | var args = { 53 | url: this._buildUriWithDomain(this.id), 54 | method: corbel.request.method.DELETE 55 | }; 56 | 57 | return this.request(args); 58 | }, 59 | 60 | _buildUri: function(id) { 61 | var urlBase = this.driver.config.getCurrentEndpoint(corbel.Webfs.moduleName, this._buildPort(this.driver.config)); 62 | 63 | return urlBase + id; 64 | }, 65 | 66 | _buildUriWithDomain: function(id) { 67 | 68 | var urlBase = this.driver.config.getCurrentEndpoint(corbel.Webfs.moduleName, this._buildPort(this.driver.config)); 69 | 70 | var domain = this.driver.config.get(corbel.Webfs.domain, corbel.Webfs.defaultDomain); 71 | var customDomain = this.driver.config.get(corbel.Domain.CUSTOM_DOMAIN, domain); 72 | 73 | this.driver.config.set(corbel.Domain.CUSTOM_DOMAIN, undefined); 74 | 75 | var uriWithDomain = urlBase + customDomain + '/path'; 76 | 77 | if (id) { 78 | uriWithDomain += '/' + id; 79 | } 80 | 81 | return uriWithDomain; 82 | }, 83 | 84 | _buildPort: function(config) { 85 | return config.get('webfsPort', null) || corbel.Webfs.defaultPort; 86 | } 87 | 88 | }, { 89 | 90 | /** 91 | * GET constant 92 | * @constant 93 | * @memberof corbel.Webfs.WebfsBuilder 94 | * @type {string} 95 | * @default 96 | */ 97 | moduleName: 'webfs', 98 | 99 | /** 100 | * Factory 101 | * @memberof corbel.Webfs.WebfsBuilder 102 | * @type {string} 103 | * @default 104 | */ 105 | create: function(driver) { 106 | return new corbel.Webfs.WebfsBuilder(driver); 107 | } 108 | 109 | }); 110 | 111 | return WebfsBuilder; 112 | 113 | })(); 114 | -------------------------------------------------------------------------------- /test/browser/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | corbel-js testing 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 |

corbelJS

18 |
19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 37 | 38 | 48 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /test/browser/test-suite.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | (function() { 4 | 5 | // @include ./unit/request.js 6 | // @include ./unit/resource-binary.js 7 | 8 | })(); -------------------------------------------------------------------------------- /test/browser/unit/resource-binary.js: -------------------------------------------------------------------------------- 1 | /*jshint newcap: false */ 2 | 'use strict'; 3 | 4 | var CONFIG = { 5 | clientId: 'clientId', 6 | clientSecret: 'clientSecret', 7 | scopes: 'scopes', 8 | 9 | domain: 'domain-example', 10 | 11 | urlBase: 'https://{{module}}-qa.bqws.io/v1.0/' 12 | }; 13 | var TEST_ENDPOINT = CONFIG.urlBase.replace('{{module}}', 'resources') + CONFIG.domain + '/'; 14 | 15 | describe('corbel resources module', function() { 16 | 17 | var sandbox = sinon.sandbox.create(), 18 | corbelDriver, 19 | resources; 20 | 21 | // crete test blob 22 | var canvas = document.createElement('canvas'); 23 | canvas.id = 'myCanvas'; 24 | canvas.width = '626'; 25 | canvas.height = '626'; 26 | 27 | var testElement =document.createElement('div'); 28 | testElement.setAttribute('id', 'test'); 29 | document.body.appendChild(testElement); 30 | 31 | document.getElementById('test').appendChild(canvas); 32 | var context = canvas.getContext('2d'); 33 | var imageObj = new Image(); 34 | 35 | context.drawImage(imageObj, 0, 0); 36 | var blob = corbel.utils.dataURItoBlob(canvas.toDataURL()); 37 | // phantom hack 38 | if(canvas.remove) { 39 | canvas.remove(); 40 | } 41 | 42 | before(function() { 43 | corbelDriver = corbel.getDriver(CONFIG); 44 | resources = corbelDriver.resources; 45 | }); 46 | 47 | after(function() {}); 48 | 49 | beforeEach(function() { 50 | sandbox.stub(corbel.request, 'send').returns(Promise.resolve()); 51 | }); 52 | 53 | afterEach(function() { 54 | sandbox.restore(); 55 | }); 56 | 57 | 58 | it('update/create a binary resource', function() { 59 | resources.resource('books:Book', '123').update(blob, { 60 | dataType: 'image/png' 61 | }); 62 | var callRequestParam = corbel.request.send.firstCall.args[0]; 63 | expect(callRequestParam.url).to.be.equal(TEST_ENDPOINT + 'resource/books:Book/123'); 64 | expect(callRequestParam.method).to.be.equal('PUT'); 65 | expect(callRequestParam.headers.Accept).to.be.equal('image/png'); 66 | expect(callRequestParam.data instanceof Blob).to.be.equal(true); 67 | }); 68 | 69 | it('delete a binary resource', function() { 70 | resources.resource('books:Book', '123').delete({ 71 | dataType: 'image/png' 72 | }); 73 | var callRequestParam = corbel.request.send.firstCall.args[0]; 74 | expect(callRequestParam.url).to.be.equal(TEST_ENDPOINT + 'resource/books:Book/123'); 75 | expect(callRequestParam.method).to.be.equal('DELETE'); 76 | expect(callRequestParam.headers.Accept).to.be.equal('image/png'); 77 | }); 78 | 79 | it('get a binary resource with mediaType and noContent', function() { 80 | resources.resource('books:Book', '123').get({ 81 | dataType: 'image/png', 82 | responseType: 'blob', 83 | noRedirect: true 84 | }); 85 | var callRequestParam = corbel.request.send.firstCall.args[0]; 86 | expect(callRequestParam.url).to.be.equal(TEST_ENDPOINT + 'resource/books:Book/123'); 87 | expect(callRequestParam.method).to.be.equal('GET'); 88 | expect(callRequestParam.headers.Accept).to.be.equal('image/png'); 89 | expect(callRequestParam.responseType).to.be.equal('blob'); 90 | expect(callRequestParam.headers['No-Redirect']).to.be.equal(true); 91 | }); 92 | 93 | }); 94 | -------------------------------------------------------------------------------- /test/karma.conf.js: -------------------------------------------------------------------------------- 1 | // Karma configuration 2 | // http://karma-runner.github.io/0.12/config/configuration-file.html 3 | // Generated on 2014-10-22 using 4 | // generator-karma 0.8.3 5 | 6 | module.exports = function(config) { 7 | 'use strict'; 8 | 9 | config.set({ 10 | // enable / disable watching file and executing tests whenever any file changes 11 | autoWatch: true, 12 | 13 | // base path, that will be used to resolve files and exclude 14 | basePath: '../', 15 | 16 | // testing framework to use (jasmine/mocha/qunit/...) 17 | frameworks: ['mocha-debug', 'mocha', 'chai', 'chai-as-promised', 'sinon'], 18 | 19 | // list of files / patterns to load in the browser 20 | files: [ 21 | 'dist/corbel.with-polyfills.js', 22 | '.tmp/test/browser/**/*.js', 23 | 'bower_components/', 24 | 'vendor/' 25 | ], 26 | 27 | // list of files / patterns to exclude 28 | exclude: ['express/server.js'], 29 | 30 | // web server port 31 | port: 8080, 32 | 33 | // Start these browsers, currently available: 34 | // - Chrome 35 | // - ChromeCanary 36 | // - Firefox 37 | // - Opera 38 | // - Safari (only Mac) 39 | // - PhantomJS 40 | // - IE (only Windows) 41 | browsers: [ 42 | 'PhantomJS' 43 | ], 44 | 45 | // Which plugins to enable 46 | plugins: [ 47 | 'karma-phantomjs-launcher', 48 | 'karma-chrome-launcher', 49 | 'karma-mocha', 50 | 'karma-mocha-debug', 51 | 'karma-mocha-reporter', 52 | 'karma-chai-plugins', 53 | 'karma-sinon', 54 | 'karma-tap-reporter' 55 | ], 56 | phantomjsLauncher: { 57 | flags: [ 58 | '--web-security=no', 59 | '--ignore-ssl-errors=no' 60 | ] 61 | }, 62 | 63 | // Continuous Integration mode 64 | // if true, it capture browsers, run tests and exit 65 | singleRun: false, 66 | 67 | colors: true, 68 | 69 | browserNoActivityTimeout: 95000, 70 | 71 | client: { 72 | mocha: { 73 | reporter: 'html' // change Karma's debug.html to the mocha web reporter 74 | } 75 | }, 76 | 77 | // test results reporter to use 78 | // possible values: 'dots', 'progress', 'junit', 'growl', 'coverage' 79 | reporters: ['tap', 'mocha'], 80 | 81 | tapReporter: { 82 | outputFile: '.report/report.tap' 83 | }, 84 | 85 | // level of logging 86 | // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG 87 | logLevel: config.LOG_INFO, 88 | 89 | // Uncomment the following lines if you are using grunt's server to run the tests 90 | // proxies: { 91 | // '/': 'http://localhost:9000/' 92 | // }, 93 | // URL root prevent conflicts with the site root 94 | // urlRoot: '_karma_' 95 | }); 96 | }; 97 | -------------------------------------------------------------------------------- /test/node/test-suite.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | global.Promise = require('es6-promise').Promise; 4 | 5 | var chai = require('chai'); 6 | var chaiAsPromised = require('chai-as-promised'); 7 | chai.use(chaiAsPromised); 8 | chai.should(); 9 | 10 | require('./unit/config.js'); 11 | require('./unit/baseUrlIntegrity.js'); 12 | require('./unit/corbel.js'); 13 | require('./unit/domain.js'); 14 | require('./unit/validate.js'); 15 | require('./unit/request.js'); 16 | require('./unit/jwt.js'); 17 | require('./unit/iam.js'); 18 | require('./unit/resources.js'); 19 | require('./unit/resources-request-params.js'); 20 | require('./unit/services.js'); 21 | require('./unit/assets.js'); 22 | require('./unit/oauth.js'); 23 | require('./unit/notifications.js'); 24 | require('./unit/ec.js'); 25 | require('./unit/evci.js'); 26 | require('./unit/scheduler.js'); 27 | require('./unit/borrow.js'); 28 | require('./unit/composr.js'); 29 | require('./unit/webfs.js'); 30 | require('./unit/utils.js'); 31 | -------------------------------------------------------------------------------- /test/node/unit/assets.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | /* jshint camelcase:false */ 3 | 4 | var corbel = require('../../../dist/corbel.js'), 5 | chai = require('chai'), 6 | sinon = require('sinon'), 7 | expect = chai.expect; 8 | 9 | describe('In Assets module we can', function() { 10 | 11 | var sandbox = sinon.sandbox.create(); 12 | var CONFIG = { 13 | 14 | clientId: 'clientId', 15 | clientSecret: 'clientSecret', 16 | 17 | scopes: ['silkroad-qa:client', 'resources:send_event_bus', 'resources:test:test_operations', 'resources:music:read_catalog', 'resources:music:streaming'], 18 | 19 | urlBase: 'https://{{module}}-corbel.io/' 20 | 21 | }; 22 | 23 | var ASSET_URL = CONFIG.urlBase.replace('{{module}}', 'assets') + 'asset'; 24 | 25 | var corbelDriver = corbel.getDriver(CONFIG); 26 | 27 | var corbelRequestStub; 28 | 29 | beforeEach(function() { 30 | corbelRequestStub = sandbox.stub(corbel.request, 'send'); 31 | }); 32 | 33 | afterEach(function() { 34 | sandbox.restore(); 35 | }); 36 | 37 | it('create one asset', function() { 38 | corbelRequestStub.returns(Promise.resolve()); 39 | var testData = '{\'test_object\':\'test\'}'; 40 | corbelDriver.assets.asset().create(testData); 41 | 42 | var callRequestParam = corbelRequestStub.getCall(0).args[0]; 43 | expect(callRequestParam.url).to.be.equal(ASSET_URL); 44 | expect(callRequestParam.method).to.be.equal('POST'); 45 | expect(callRequestParam.data).to.be.equal(testData); 46 | }); 47 | 48 | it('get my user assets', function() { 49 | corbelRequestStub.returns(Promise.resolve('OK')); 50 | 51 | corbelDriver.assets.asset().get(); 52 | 53 | var callRequestParam = corbelRequestStub.getCall(0).args[0]; 54 | expect(callRequestParam.url).to.be.equal(ASSET_URL); 55 | expect(callRequestParam.method).to.be.equal('GET'); 56 | }); 57 | 58 | it('get my user assets all with params', function() { 59 | corbelRequestStub.returns(Promise.resolve('OK')); 60 | var params = { 61 | query: [{ 62 | '$eq': { 63 | field: 'value' 64 | } 65 | }], 66 | pagination: { 67 | pageSize: 2, 68 | page: 3 69 | }, 70 | sort: { 71 | field: 'asc' 72 | } 73 | }; 74 | 75 | corbelDriver.assets.asset().get(params); 76 | 77 | var callRequestParam = corbelRequestStub.getCall(0).args[0]; 78 | 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'); 79 | expect(callRequestParam.query).to.be.equal(); 80 | expect(callRequestParam.method).to.be.equal('GET'); 81 | }); 82 | 83 | it('get all assets', function() { 84 | corbelRequestStub.returns(Promise.resolve('OK')); 85 | 86 | corbelDriver.assets.asset('all').get(); 87 | 88 | var callRequestParam = corbelRequestStub.getCall(0).args[0]; 89 | expect(callRequestParam.url).to.be.equal(ASSET_URL + '/all'); 90 | expect(callRequestParam.method).to.be.equal('GET'); 91 | }); 92 | 93 | it('get all with params', function() { 94 | corbelRequestStub.returns(Promise.resolve('OK')); 95 | var params = { 96 | query: [{ 97 | '$eq': { 98 | field: 'value' 99 | } 100 | }], 101 | pagination: { 102 | pageSize: 2, 103 | page: 3 104 | }, 105 | sort: { 106 | field: 'asc' 107 | } 108 | }; 109 | 110 | corbelDriver.assets.asset('all').get(params); 111 | 112 | var callRequestParam = corbelRequestStub.getCall(0).args[0]; 113 | 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'); 114 | expect(callRequestParam.method).to.be.equal('GET'); 115 | }); 116 | 117 | it('get aggregated count', function() { 118 | corbelRequestStub.returns(Promise.resolve('OK')); 119 | var params = { 120 | aggregation : { '$count' : '*'} 121 | }; 122 | 123 | corbelDriver.assets.asset('all').get(params); 124 | 125 | var callRequestParam = corbelRequestStub.getCall(0).args[0]; 126 | expect(callRequestParam.url).to.be.equal(ASSET_URL + '/all?' + 'api:aggregation=' + encodeURIComponent('{\"$count\":\"*\"}')); 127 | expect(callRequestParam.method).to.be.equal('GET'); 128 | }); 129 | 130 | it('delete an undefinded asset', function() { 131 | corbelRequestStub.returns(Promise.resolve('OK')); 132 | 133 | expect(function(){ 134 | corbelDriver.assets.asset().delete(); 135 | }).to.throw('id value is mandatory and cannot be undefined'); 136 | }); 137 | 138 | it('delete one asset', function() { 139 | corbelRequestStub.returns(Promise.resolve()); 140 | var assetId = 1; 141 | 142 | corbelDriver.assets.asset(assetId).delete(); 143 | 144 | var callRequestParam = corbelRequestStub.getCall(0).args[0]; 145 | expect(callRequestParam.url).to.be.equal(ASSET_URL + '/' + assetId); 146 | expect(callRequestParam.method).to.be.equal('DELETE'); 147 | }); 148 | 149 | it('get access', function() { 150 | corbelRequestStub.returns(Promise.resolve()); 151 | corbelDriver.assets.asset().access(); 152 | 153 | var callRequestParam = corbelRequestStub.getCall(0).args[0]; 154 | expect(callRequestParam.url).to.be.equal(ASSET_URL + '/access'); 155 | expect(callRequestParam.method).to.be.equal('GET'); 156 | expect(callRequestParam.headers['No-Redirect']).to.be.equal(true); 157 | }); 158 | 159 | }); 160 | -------------------------------------------------------------------------------- /test/node/unit/baseUrlIntegrity.js: -------------------------------------------------------------------------------- 1 | /*jshint newcap: false */ 2 | 'use strict'; 3 | 4 | var corbel = require('../../../dist/corbel.js'), 5 | chai = require('chai'), 6 | sinon = require('sinon'), 7 | expect = chai.expect; 8 | 9 | var TEST_ENDPOINT = 'https://resources-mycorbel.com/v1.0/domain-example/', 10 | 11 | URL_EXAMPLE_RESOURCES = TEST_ENDPOINT + 'resource/resource:entity?api:search=' + encodeURIComponent('{"text":"test"}'); 12 | 13 | var CONFIG = { 14 | clientId: 'clientId', 15 | clientSecret: 'clientSecret', 16 | scopes: 'scopes', 17 | domain: 'domain-example', 18 | urlBase: 'https://{{module}}-mycorbel.com/v1.0/' 19 | }; 20 | 21 | describe('corbel resources module', function() { 22 | 23 | var sandbox = sinon.sandbox.create(), 24 | corbelDriver, 25 | resources; 26 | 27 | before(function() { 28 | corbelDriver = corbel.getDriver(CONFIG); 29 | resources = corbelDriver.resources; 30 | }); 31 | 32 | after(function() {}); 33 | 34 | beforeEach(function() { 35 | sandbox.stub(corbel.request, 'send').returns(Promise.resolve()); 36 | }); 37 | 38 | afterEach(function() { 39 | sandbox.restore(); 40 | }); 41 | 42 | describe('url integrity', function() { 43 | this.timeout(10000); 44 | 45 | it('does not stack multiple api:definitions', function(done) { 46 | var params = { 47 | search : { 48 | text: 'test' 49 | } 50 | }; 51 | 52 | expect(resources.collection('resource:entity').getURL(params)).to.be.equal(URL_EXAMPLE_RESOURCES); 53 | 54 | //After N calls the params object does not get modified by reference. 55 | var promises = [resources.collection('resource:entity').get(params), resources.collection('resource:entity').get(params)]; 56 | 57 | Promise.all(promises) 58 | .then(function(){ 59 | expect(resources.collection('resource:entity').getURL(params)).to.be.equal(URL_EXAMPLE_RESOURCES); 60 | done(); 61 | }) 62 | .catch(function(err){ 63 | console.log(err); 64 | done(err); 65 | }); 66 | }); 67 | 68 | }); 69 | }); -------------------------------------------------------------------------------- /test/node/unit/domain.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | /* jshint camelcase:false */ 3 | 4 | var corbel = require('../../../dist/corbel.js'), 5 | chai = require('chai'), 6 | sinon = require('sinon'), 7 | expect = chai.expect; 8 | 9 | describe('With custom domain we can', function() { 10 | 11 | var sandbox = sinon.sandbox.create(); 12 | 13 | var CONFIG = { 14 | clientId: 'clientId', 15 | clientSecret: 'clientSecret', 16 | scopes: ['corbel-qa:client'], 17 | urlBase: 'https://{{module}}-corbel.io/' 18 | }; 19 | 20 | var RESOURCE_COLLECTION_URL = CONFIG.urlBase.replace('{{module}}', 'resources') + '{{domain}}/resource/{{resource}}' ; 21 | var WEBFS_URL = CONFIG.urlBase.replace('{{module}}', 'webfs') + '{{domain}}/{{resource}}' ; 22 | 23 | var corbelDriver, corbelRequestStub; 24 | 25 | beforeEach(function() { 26 | corbelDriver = corbel.getDriver(CONFIG); 27 | corbelRequestStub = sandbox.stub(corbel.request, 'send'); 28 | corbelRequestStub.returns(Promise.resolve()); 29 | }); 30 | 31 | afterEach(function() { 32 | sandbox.restore(); 33 | }); 34 | 35 | it('add a custom domain value', function() { 36 | var resource = 'resource:entity'; 37 | var customDomain = 'oneTestDomain'; 38 | 39 | var url = RESOURCE_COLLECTION_URL.replace('{{resource}}', resource).replace('{{domain}}', customDomain); 40 | expect(corbelDriver.domain(customDomain).resources.collection(resource).getURL()).to.be.equal(url); 41 | }); 42 | 43 | it('does not persist the value on resources configuration for consecutive calls', function(done){ 44 | var resource = 'resource:entity'; 45 | var customDomain = 'oneTestDomainTwo'; 46 | 47 | var urlWithDomain = RESOURCE_COLLECTION_URL.replace('{{resource}}', resource).replace('{{domain}}', customDomain); 48 | var urlWithoutDomain = RESOURCE_COLLECTION_URL.replace('{{resource}}', resource).replace('{{domain}}', 'unauthenticated'); 49 | 50 | expect(corbelDriver.domain(customDomain).resources.collection(resource).getURL()).to.be.equal(urlWithDomain); 51 | 52 | corbelDriver.domain(customDomain).resources.collection(resource) 53 | .get() 54 | .then(function(){ 55 | expect(corbelDriver.resources.collection(resource).getURL()).to.be.equal(urlWithoutDomain); 56 | }) 57 | .should.notify(done); 58 | }); 59 | 60 | it('does not persist the value on webfs configuration for consecutive calls', function(done){ 61 | var resource = 'index.html'; 62 | var customDomain = 'oneTestDomainTwo'; 63 | 64 | var urlWithDomain = WEBFS_URL.replace('{{resource}}', resource).replace('{{domain}}', customDomain + '/path'); 65 | var urlWithoutDomain = WEBFS_URL.replace('{{resource}}', resource).replace('{{domain}}', 'unauthenticated' + '/path'); 66 | 67 | expect(corbelDriver.domain(customDomain).webfs.webfs(resource)._buildUriWithDomain(resource)).to.be.equal(urlWithDomain); 68 | 69 | corbelDriver.domain(customDomain).webfs.webfs(resource).get() 70 | .then(function(){ 71 | expect(corbelDriver.webfs.webfs(resource)._buildUriWithDomain(resource)).to.be.equal(urlWithoutDomain); 72 | }) 73 | .should.notify(done); 74 | }); 75 | }); 76 | -------------------------------------------------------------------------------- /test/node/unit/evci.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | /* jshint camelcase:false */ 3 | 4 | var corbel = require('../../../dist/corbel.js'), 5 | chai = require('chai'), 6 | sinon = require('sinon'), 7 | expect = chai.expect; 8 | 9 | describe('In Evci module we can', function() { 10 | 11 | var sandbox = sinon.sandbox.create(); 12 | 13 | var CONFIG = { 14 | 15 | clientId: 'clientId', 16 | clientSecret: 'clientSecret', 17 | 18 | scopes: ['silkroad-qa:client', 'resources:send_event_bus', 'resources:test:test_operations'], 19 | 20 | urlBase: 'https://{{module}}-corbel.io/' 21 | 22 | }; 23 | 24 | var EVENT_TYPE = 'log:error'; 25 | 26 | var EVENT_DATA = '{\'test_object\':\'test\'}'; 27 | 28 | var EVCI_URL = CONFIG.urlBase.replace('{{module}}', corbel.Evci.moduleName) + 'event'; 29 | 30 | var corbelDriver = corbel.getDriver(CONFIG); 31 | 32 | var corbelRequestStub; 33 | 34 | beforeEach(function() { 35 | corbelRequestStub = sandbox.stub(corbel.request, 'send'); 36 | }); 37 | 38 | afterEach(function() { 39 | sandbox.restore(); 40 | }); 41 | 42 | it('generate evci query correctly', function() { 43 | corbelRequestStub.returns(Promise.resolve()); 44 | corbelDriver.evci.event(EVENT_TYPE).publish(EVENT_DATA); 45 | 46 | var callRequestParam = corbelRequestStub.getCall(0).args[0]; 47 | expect(callRequestParam.url).to.be.equal(EVCI_URL+'/'+EVENT_TYPE); 48 | expect(callRequestParam.method).to.be.equal('POST'); 49 | expect(callRequestParam.data).to.be.equal(EVENT_DATA); 50 | }); 51 | 52 | it('throw exception when create event without type', function() { 53 | corbelRequestStub.returns(Promise.resolve('OK')); 54 | expect(function(){ 55 | corbelDriver.evci.event().publish(EVENT_DATA); 56 | }).to.throw('eventType value is mandatory and cannot be undefined'); 57 | }); 58 | 59 | it('throw exception when publish event without data', function() { 60 | expect(corbelDriver.evci.event(EVENT_TYPE).publish).to.throw('Send event require data'); 61 | }); 62 | }); 63 | -------------------------------------------------------------------------------- /test/node/unit/jwt.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | var corbel = require('../../../dist/corbel.js'), 4 | chai = require('chai'), 5 | expect = chai.expect; 6 | 7 | describe('JWT module', function() { 8 | 9 | var CLIENT_ID = 'CLIENT_ID'; 10 | var SCOPES = 'scope1 scope2'; 11 | 12 | it('exists and is an object', function() { 13 | expect(corbel.jwt).to.be.an('object'); 14 | }); 15 | 16 | it('has all namespace properties', function() { 17 | expect(corbel.jwt).to.include.keys( 18 | 'generate' 19 | ); 20 | }); 21 | 22 | it('generates a valid JWT', function() { 23 | var secret = 'secret', 24 | claims = { 25 | 'iss': CLIENT_ID, 26 | 'aud': 'http://iam.bqws.io', 27 | 'exp': 1391535, 28 | 'scope': SCOPES, 29 | 'version': '1.0.0' 30 | }; 31 | var EXPECTED_ASSERTION = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJDTElFTlRfSUQiLCJhdWQiOiJodHRwOi8vaWFtLmJxd3MuaW8iLCJleHAiOjEzOTE1MzUsInNjb3BlIjoic2NvcGUxIHNjb3BlMiIsInZlcnNpb24iOiIxLjAuMCJ9._TCKYb3gbsuznfwA1gopY4mSYr7VHmvFQGxW1CJJjHQ'; 32 | 33 | // without alg 34 | var assertion = corbel.jwt.generate(claims, secret); 35 | expect(assertion).to.be.equal(EXPECTED_ASSERTION); 36 | 37 | // with alg 38 | assertion = corbel.jwt.generate(claims, secret, 'HS256'); 39 | expect(assertion).to.be.equal(EXPECTED_ASSERTION); 40 | 41 | // with array scopes 42 | claims.scope = ['scope1', 'scope2']; 43 | assertion = corbel.jwt.generate(claims, secret); 44 | expect(assertion).to.be.equal(EXPECTED_ASSERTION); 45 | }); 46 | 47 | it('decodes expected values', function() { 48 | var secret = 'secret', 49 | claims = { 50 | iss: 'clientId', 51 | aud: 'http://iam.bqws.io', 52 | exp: 12345, 53 | scope: 'scope:example1 scope:example2' 54 | }; 55 | 56 | var EXPECTED = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJjbGllbnRJZCIsImF1ZCI6Imh0dHA6Ly9pYW0uYnF3cy5pbyIsImV4cCI6MTIzNDUsInNjb3BlIjoic2NvcGU6ZXhhbXBsZTEgc2NvcGU6ZXhhbXBsZTIifQ.18g9YO_KgWtW1s7HSo87mIjG02u8Pe880tdLbg_JxC4'; 57 | 58 | var assertion = corbel.jwt.generate(claims, secret); 59 | expect(assertion).to.be.equal(EXPECTED); 60 | 61 | // with array scopes 62 | claims.scope = ['scope:example1', 'scope:example2']; 63 | assertion = corbel.jwt.generate(claims, secret); 64 | var jwtDecoded = corbel.jwt.decode(assertion); 65 | expect(jwtDecoded).to.be.an('object'); 66 | 67 | expect(jwtDecoded.typ).to.be.equal('JWT'); 68 | expect(jwtDecoded.alg).to.be.equal('HS256'); 69 | 70 | expect(jwtDecoded.iss).to.be.equal('clientId'); 71 | expect(jwtDecoded.aud).to.be.equal('http://iam.bqws.io'); 72 | expect(jwtDecoded.exp).to.be.equal(12345); 73 | expect(jwtDecoded.scope).to.be.equal('scope:example1 scope:example2'); 74 | }); 75 | 76 | it('throws exception with invalid assertion', function() { 77 | expect(function() { 78 | corbel.jwt.decode('invalid_assertion'); 79 | }).to.throw('corbel:jwt:decode:invalid_assertion'); 80 | }); 81 | 82 | describe('when generating claims', function() { 83 | 84 | it('iss are required', function() { 85 | 86 | expect(function() { 87 | corbel.jwt.generate(); 88 | }).to.throw('jwt:undefined:iss'); 89 | 90 | }); 91 | 92 | it('aud are required', function() { 93 | 94 | expect(function() { 95 | corbel.jwt.generate({ 96 | iss: 'myiss' 97 | }); 98 | }).to.throw('jwt:undefined:aud'); 99 | 100 | }); 101 | 102 | 103 | }); 104 | 105 | }); 106 | -------------------------------------------------------------------------------- /test/node/unit/scheduler.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | /* jshint camelcase:false */ 3 | 4 | var corbel = require('../../../dist/corbel.js'), 5 | chai = require('chai'), 6 | sinon = require('sinon'), 7 | expect = chai.expect; 8 | 9 | describe('In Scheduler module we can', function() { 10 | 11 | var sandbox = sinon.sandbox.create(); 12 | 13 | var CONFIG = { 14 | 15 | clientId: 'clientId', 16 | clientSecret: 'clientSecret', 17 | 18 | urlBase: 'https://{{module}}-corbel.io/' 19 | 20 | }; 21 | 22 | var TASK_ID = 'task:id'; 23 | 24 | var TASK_DATA = { 'data': 'data' }; 25 | 26 | var SCHEDULER_URL = CONFIG.urlBase.replace('{{module}}', corbel.Scheduler.moduleName) + 'tasks'; 27 | 28 | var corbelDriver = corbel.getDriver(CONFIG); 29 | 30 | var corbelRequestStub; 31 | 32 | beforeEach(function() { 33 | corbelRequestStub = sandbox.stub(corbel.request, 'send'); 34 | }); 35 | 36 | afterEach(function() { 37 | sandbox.restore(); 38 | }); 39 | 40 | it('generate a scheduler task correctly', function() { 41 | corbelRequestStub.returns(Promise.resolve()); 42 | corbelDriver.scheduler.task().create(TASK_DATA); 43 | 44 | var callRequestParam = corbelRequestStub.getCall(0).args[0]; 45 | expect(callRequestParam.url).to.be.equal(SCHEDULER_URL); 46 | expect(callRequestParam.method).to.be.equal('POST'); 47 | expect(callRequestParam.data).to.be.equal(TASK_DATA); 48 | }); 49 | 50 | it('task cannot be retrieved without an id', function() { 51 | corbelRequestStub.returns(Promise.resolve('OK')); 52 | expect(function(){ 53 | corbelDriver.scheduler.task().get(); 54 | }).to.throw('id value is mandatory and cannot be undefined'); 55 | }); 56 | 57 | it('retrieve a scheduler task correctly', function() { 58 | corbelRequestStub.returns(Promise.resolve()); 59 | corbelDriver.scheduler.task(TASK_ID).get(); 60 | 61 | var callRequestParam = corbelRequestStub.getCall(0).args[0]; 62 | expect(callRequestParam.url).to.be.equal(SCHEDULER_URL +'/'+ TASK_ID); 63 | expect(callRequestParam.method).to.be.equal('GET'); 64 | }); 65 | 66 | it('task cannot be updated without an id', function() { 67 | corbelRequestStub.returns(Promise.resolve('OK')); 68 | expect(function(){ 69 | corbelDriver.scheduler.task().update(); 70 | }).to.throw('id value is mandatory and cannot be undefined'); 71 | }); 72 | 73 | it('update a scheduler task correctly', function() { 74 | corbelRequestStub.returns(Promise.resolve()); 75 | corbelDriver.scheduler.task(TASK_ID).update(TASK_DATA); 76 | 77 | var callRequestParam = corbelRequestStub.getCall(0).args[0]; 78 | expect(callRequestParam.url).to.be.equal(SCHEDULER_URL +'/'+ TASK_ID); 79 | expect(callRequestParam.method).to.be.equal('PUT'); 80 | }); 81 | 82 | it('task cannot be delete without an id', function() { 83 | corbelRequestStub.returns(Promise.resolve('OK')); 84 | expect(function(){ 85 | corbelDriver.scheduler.task().delete(); 86 | }).to.throw('id value is mandatory and cannot be undefined'); 87 | }); 88 | 89 | it('delete a scheduler task correctly', function() { 90 | corbelRequestStub.returns(Promise.resolve()); 91 | corbelDriver.scheduler.task(TASK_ID).delete(); 92 | 93 | var callRequestParam = corbelRequestStub.getCall(0).args[0]; 94 | expect(callRequestParam.url).to.be.equal(SCHEDULER_URL +'/'+ TASK_ID); 95 | expect(callRequestParam.method).to.be.equal('DELETE'); 96 | }); 97 | }); 98 | -------------------------------------------------------------------------------- /test/node/unit/utils.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | /* jshint camelcase:false */ 3 | 4 | var corbel = require('../../../dist/corbel.js'), 5 | chai = require('chai'), 6 | expect = chai.expect; 7 | 8 | describe('In utils module', function() { 9 | 10 | it('an Array can be copied', function() { 11 | var arrayOrigin = [1, 2, 3]; 12 | 13 | var copiedArray = corbel.utils.copyArray(arrayOrigin); 14 | 15 | expect(copiedArray.length).to.equals(3); 16 | 17 | for(var i = 0; i < copiedArray.length; i++){ 18 | expect(copiedArray[i]).to.equals(arrayOrigin[i]); 19 | } 20 | }); 21 | 22 | it('array references are not maintained', function() { 23 | var arrayOrigin = [1, 2, 3]; 24 | 25 | var copiedArray = corbel.utils.copyArray(arrayOrigin); 26 | 27 | copiedArray.pop(); 28 | 29 | expect(arrayOrigin.length).to.equals(3); 30 | expect(copiedArray.length).to.equals(2); 31 | }); 32 | 33 | it('is JSON evaluation (true)', function() { 34 | var testJson = '{"a": 1, "b": 2}'; 35 | 36 | expect(corbel.utils.isJSON(testJson)).to.be.equal(true); 37 | }); 38 | 39 | it('is JSON evaluation (false)', function() { 40 | var notJson = 'notJson'; 41 | 42 | expect(corbel.utils.isJSON(notJson)).to.be.equal(false); 43 | }); 44 | 45 | it('is stream evaluation (true)', function() { 46 | var Stream = require('stream'); 47 | var stream = new Stream(); 48 | 49 | expect(corbel.utils.isStream(stream)).to.be.equal(true); 50 | }); 51 | 52 | it('is stream evaluation (false)', function() { 53 | var notStream = 'notStream'; 54 | 55 | expect(corbel.utils.isStream(notStream)).to.be.equal(false); 56 | }); 57 | 58 | it('an array is converted to object', function() { 59 | var arr = ['a', 'b']; 60 | var obj = {0: 'a', 1: 'b'}; 61 | 62 | expect(corbel.utils.arrayToObject(arr)).to.deep.equal(obj); 63 | }); 64 | 65 | it('keys are converted to lowercase', function() { 66 | var upperObj = {A: 'a', B: 'b'}; 67 | var lowerObj = {a: 'a', b: 'b'}; 68 | 69 | expect(corbel.utils.keysToLowerCase(upperObj)).to.deep.equal(lowerObj); 70 | }); 71 | 72 | it('a hash is properly encoded to url format', function() { 73 | var obj = { 74 | assertion:'abcd_134', 75 | grant_type:'urn:ietf:params:oauth:grant-type:jwt-bearer' 76 | }; 77 | 78 | var expectedResult = 'assertion=abcd_134&grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer'; 79 | 80 | expect(corbel.utils.toURLEncoded(obj)).to.be.equal(expectedResult); 81 | }); 82 | 83 | it('an array is properly encoded to url format', function() { 84 | var obj = [ 85 | { 86 | 'name':'api:query', 87 | 'value': 'abc' 88 | }, 89 | { 90 | 'name':'api:query', 91 | 'value': 'abc2' 92 | }, 93 | { 94 | 'name':'api:page', 95 | 'value': 5 96 | } 97 | ]; 98 | 99 | var expectedResult = 'api:query=abc&api:query=abc2&api:page=5'; 100 | 101 | expect(corbel.utils.toURLEncoded(obj)).to.be.equal(expectedResult); 102 | }); 103 | }); 104 | -------------------------------------------------------------------------------- /test/node/unit/webfs.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | /* jshint camelcase:false */ 3 | 4 | var corbel = require('../../../dist/corbel.js'), 5 | chai = require('chai'), 6 | sinon = require('sinon'), 7 | expect = chai.expect; 8 | 9 | describe('In Webfs module we can', function() { 10 | 11 | var sandbox = sinon.sandbox.create(); 12 | var CONFIG = { 13 | 14 | clientId: 'clientId', 15 | clientSecret: 'clientSecret', 16 | 17 | scopes: ['silkroad-qa:client', 'resources:send_event_bus', 'resources:test:test_operations', 'resources:music:read_catalog', 'resources:music:streaming'], 18 | 19 | domain: 'domain-example', 20 | 21 | urlBase: 'https://{{module}}-corbel.io/v1.0/' 22 | }; 23 | 24 | var WEBFS_URL = CONFIG.urlBase.replace('{{module}}', 'webfs') + CONFIG.domain + '/path/'; 25 | var RESOURCE_ID = 'index.html'; 26 | 27 | var corbelDriver = corbel.getDriver(CONFIG); 28 | 29 | var corbelRequestStub; 30 | 31 | beforeEach(function() { 32 | corbelRequestStub = sandbox.stub(corbel.request, 'send'); 33 | }); 34 | 35 | afterEach(function() { 36 | sandbox.restore(); 37 | }); 38 | 39 | it('retrieve a resource from S3', function() { 40 | corbelRequestStub.returns(Promise.resolve('OK')); 41 | 42 | corbelDriver.webfs.webfs(RESOURCE_ID).get(); 43 | 44 | var callRequestParam = corbelRequestStub.getCall(0).args[0]; 45 | expect(callRequestParam).to.have.property('url', WEBFS_URL + RESOURCE_ID); 46 | expect(callRequestParam).to.have.property('method', 'GET'); 47 | }); 48 | 49 | it('retrieve a resource from S3 with specific contentType', function() { 50 | corbelRequestStub.returns(Promise.resolve('OK')); 51 | 52 | corbelDriver.webfs.webfs(RESOURCE_ID).get({contentType: 'text/xml'}); 53 | 54 | var callRequestParam = corbelRequestStub.getCall(0).args[0]; 55 | expect(callRequestParam).to.have.property('url', WEBFS_URL + RESOURCE_ID); 56 | expect(callRequestParam).to.have.property('method', 'GET'); 57 | expect(callRequestParam).to.have.property('contentType', 'text/xml'); 58 | }); 59 | 60 | it('retrieve a resource from S3 with specific Accept header', function() { 61 | corbelRequestStub.returns(Promise.resolve('OK')); 62 | 63 | corbelDriver.webfs.webfs(RESOURCE_ID).get({Accept: 'text/xml'}); 64 | 65 | var callRequestParam = corbelRequestStub.getCall(0).args[0]; 66 | expect(callRequestParam).to.have.property('url', WEBFS_URL + RESOURCE_ID); 67 | expect(callRequestParam).to.have.property('method', 'GET'); 68 | expect(callRequestParam).to.have.deep.property('headers.Accept', 'text/xml'); 69 | }); 70 | 71 | it('an error is thrown if resourceId is undefined', function() { 72 | corbelRequestStub.returns(Promise.resolve('OK')); 73 | 74 | expect(function() { 75 | corbelDriver.webfs.webfs().get(); 76 | }).to.throw('id value is mandatory and cannot be undefined'); 77 | }); 78 | 79 | it('delete a folder from S3', function() { 80 | corbelRequestStub.returns(Promise.resolve('OK')); 81 | 82 | corbelDriver.webfs.webfs(RESOURCE_ID).delete(); 83 | 84 | var callRequestParam = corbelRequestStub.getCall(0).args[0]; 85 | expect(callRequestParam).to.have.property('url', WEBFS_URL + RESOURCE_ID); 86 | expect(callRequestParam).to.have.property('method', 'DELETE'); 87 | }); 88 | }); 89 | --------------------------------------------------------------------------------