├── .gitignore ├── .jshintrc ├── LICENSE.txt ├── OSSMETADATA ├── README.md ├── authors.txt ├── dist ├── XMLHttpSource.js └── XMLHttpSource.min.js ├── package.json ├── src ├── XMLHttpSource.js ├── buildQueryObject.js ├── getCORSRequest.js ├── getXMLHttpRequest.browser.js ├── getXMLHttpRequest.js └── request.js └── ts ├── falcor-browser.d.ts └── falcor-http-datasource.d.ts /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | *.iml 3 | node_modules -------------------------------------------------------------------------------- /.jshintrc: -------------------------------------------------------------------------------- 1 | { 2 | "curly": true, 3 | "eqeqeq": true, 4 | "immed": true, 5 | "latedef": false, 6 | "newcap": true, 7 | "noarg": true, 8 | "sub": true, 9 | "undef": true, 10 | "unused": false, 11 | "boss": true, 12 | "eqnull": true, 13 | "node": true, 14 | "globals": { 15 | "require": true, 16 | "document": false, 17 | "WebSocket": false, 18 | "global": false, 19 | "XMLHttpRequest": false 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2012 Netflix, Inc. 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /OSSMETADATA: -------------------------------------------------------------------------------- 1 | osslifecycle=active 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # HttpDataSource 2 | 3 | This is a Falcor DataSource which can be used to retrieve JSON Graph information from an HTTP server. 4 | 5 | ## Install 6 | ```bash 7 | npm install falcor-http-datasource 8 | ``` 9 | 10 | ## Usage 11 | 12 | Minimalistic ES6 example, a quick dirty setup 13 | 14 | ```es6 15 | import falcor from 'falcor'; 16 | import HttpDataSource from 'falcor-http-datasource'; 17 | 18 | var model = new falcor.Model({ 19 | source: new HttpDataSource('/model.json') 20 | }); 21 | ``` 22 | If you need some additional info for your global HTTP requests consider something like 23 | 24 | JWT 25 | ```javascript 26 | var source = new HttpDataSource('/model.json', { 27 | headers: { 28 | 'Authorization': `bearer ' + token` 29 | } 30 | }); 31 | ``` 32 | POST JSON 33 | ```javascript 34 | var source = new HttpDataSource('/model.json', { 35 | headers: { 36 | 'Content-Type': 'application/json' 37 | } 38 | }); 39 | ``` 40 | Cookies 41 | ```javascript 42 | var source = new HttpDataSource('/model.json', { 43 | withCredentials: true 44 | }); 45 | // server must include the header `Access-Control-Allow-Credentials: true` 46 | ``` 47 | CORS 48 | ```javascript 49 | var source = new HttpDataSource('/model.json', { 50 | crossDomain: true 51 | }); 52 | ``` 53 | or you might want to pass it to constructor as your global AppSource 54 | 55 | ```es6 56 | 57 | export class AppSource extends HttpDataSource { 58 | constructor(path, token) { 59 | super(path, { 60 | headers: { 61 | 'Authorization': `bearer ${ token }` 62 | } 63 | timeout: 20000 64 | }) 65 | } 66 | 67 | get(...args) { 68 | // returns an Observable if you wanted to map/filter/reduce/etc 69 | return super.get(...args) 70 | } 71 | set(...args) { 72 | // returns an Observable if you wanted to map/filter/reduce/etc 73 | return super.set(...args) 74 | } 75 | call(...args) { 76 | // returns an Observable if you wanted to map/filter/reduce/etc 77 | return super.call(...args) 78 | } 79 | 80 | onBeforeRequest(config) { 81 | // as of now you're able to mutate the config object before we create our xhr instance 82 | // you would attach any url params here 83 | // config.url = config.url + '&something=Value' 84 | console.log(config); 85 | } 86 | buildQueryObject(...args) { 87 | // helper method to build our url for advanced implementations 88 | return super.buildQueryObject(...args) 89 | } 90 | } 91 | 92 | export class FalcorModel extends falcor.Model { 93 | constructor(cache) { 94 | super({ 95 | cache: cache, 96 | source: new AppSource('/model.json', user.token) 97 | }); 98 | } 99 | } 100 | 101 | ``` 102 | -------------------------------------------------------------------------------- /authors.txt: -------------------------------------------------------------------------------- 1 | Jafar Husain 2 | Paul Taylor 3 | Michael Paulson 4 | Patrick Stapleton 5 | -------------------------------------------------------------------------------- /dist/XMLHttpSource.js: -------------------------------------------------------------------------------- 1 | (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o= 200 && status <= 399) { 380 | try { 381 | if (responseType !== 'json') { 382 | responseData = JSON.parse(responseData || ''); 383 | } 384 | if (typeof responseData === 'string') { 385 | responseData = JSON.parse(responseData || ''); 386 | } 387 | } catch (e) { 388 | _handleXhrError(observer, 'invalid json', e); 389 | } 390 | observer.onNext(responseData); 391 | observer.onCompleted(); 392 | return; 393 | 394 | } else if (status === 401 || status === 403 || status === 407) { 395 | 396 | return _handleXhrError(observer, responseData); 397 | 398 | } else if (status === 410) { 399 | // TODO: Retry ? 400 | return _handleXhrError(observer, responseData); 401 | 402 | } else if (status === 408 || status === 504) { 403 | // TODO: Retry ? 404 | return _handleXhrError(observer, responseData); 405 | 406 | } else { 407 | 408 | return _handleXhrError(observer, responseData || ('Response code ' + status)); 409 | 410 | }//if 411 | }//if 412 | }//onXhrLoad 413 | 414 | function onXhrError(observer, xhr, status, e) { 415 | _handleXhrError(observer, status || xhr.statusText || 'request error', e); 416 | } 417 | 418 | module.exports = request; 419 | 420 | },{"./getCORSRequest":3,"./getXMLHttpRequest":4}]},{},[1]); 421 | -------------------------------------------------------------------------------- /dist/XMLHttpSource.min.js: -------------------------------------------------------------------------------- 1 | (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o=200&&status<=399){try{if(responseType!=="json"){responseData=JSON.parse(responseData||"")}if(typeof responseData==="string"){responseData=JSON.parse(responseData||"")}}catch(e){_handleXhrError(observer,"invalid json",e)}observer.onNext(responseData);observer.onCompleted();return}else if(status===401||status===403||status===407){return _handleXhrError(observer,responseData)}else if(status===410){return _handleXhrError(observer,responseData)}else if(status===408||status===504){return _handleXhrError(observer,responseData)}else{return _handleXhrError(observer,responseData||"Response code "+status)}}}function onXhrError(observer,xhr,status,e){_handleXhrError(observer,status||xhr.statusText||"request error",e)}module.exports=request},{"./getCORSRequest":2,"./getXMLHttpRequest":3}],5:[function(require,module,exports){"use strict";var request=require("./request");var buildQueryObject=require("./buildQueryObject");var isArray=Array.isArray;function simpleExtend(obj,obj2){var prop;for(prop in obj2){obj[prop]=obj2[prop]}return obj}function XMLHttpSource(jsongUrl,config){this._jsongUrl=jsongUrl;if(typeof config==="number"){var newConfig={timeout:config};config=newConfig}this._config=simpleExtend({timeout:15e3,headers:{}},config||{})}XMLHttpSource.prototype={constructor:XMLHttpSource,buildQueryObject:buildQueryObject,get:function httpSourceGet(pathSet){var method="GET";var queryObject=this.buildQueryObject(this._jsongUrl,method,{paths:pathSet,method:"get"});var config=simpleExtend(queryObject,this._config);var context=this;return request(method,config,context)},set:function httpSourceSet(jsongEnv){var method="POST";var config,queryObject;if(!this._config.headers||!this._config.headers["Content-Type"]||!this._config.headers["Content-Type"].match(/application\/json/)){queryObject=this.buildQueryObject(this._jsongUrl,method,{jsonGraph:jsongEnv,method:"set"});config=simpleExtend(queryObject,this._config);config.headers["Content-Type"]="application/x-www-form-urlencoded"}else{config=simpleExtend({url:this._jsongUrl,data:JSON.stringify({jsonGraph:JSON.stringify(jsongEnv),method:"set"})},this._config)}var context=this;return request(method,config,context)},call:function httpSourceCall(callPath,args,pathSuffix,paths){args=args||[];pathSuffix=pathSuffix||[];paths=paths||[];var method="POST";var config,queryData=[],queryObject;if(!this._config.headers||!this._config.headers["Content-Type"]||!this._config.headers["Content-Type"].match(/application\/json/)){queryData.push("method=call");queryData.push("callPath="+encodeURIComponent(JSON.stringify(callPath)));queryData.push("arguments="+encodeURIComponent(JSON.stringify(args)));queryData.push("pathSuffixes="+encodeURIComponent(JSON.stringify(pathSuffix)));queryData.push("paths="+encodeURIComponent(JSON.stringify(paths)));queryObject=this.buildQueryObject(this._jsongUrl,method,queryData.join("&"));config=simpleExtend(queryObject,this._config);config.headers["Content-Type"]="application/x-www-form-urlencoded"}else{config=simpleExtend({url:this._jsongUrl,data:JSON.stringify({method:"call",callPath:JSON.stringify(callPath),arguments:JSON.stringify(args),pathSuffixes:JSON.stringify(pathSuffix),paths:JSON.stringify(paths)})},this._config)}var context=this;return request(method,config,context)}};XMLHttpSource.XMLHttpSource=XMLHttpSource;XMLHttpSource["default"]=XMLHttpSource;module.exports=XMLHttpSource},{"./buildQueryObject":1,"./request":4}]},{},[5]); -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "falcor-http-datasource", 3 | "version": "0.1.3", 4 | "description": "This package contains falcor components for use in browsers.", 5 | "main": "src/XMLHttpSource.js", 6 | "homepage": "https://github.com/Netflix/falcor-http-datasource", 7 | "browser": { 8 | "./src/getXMLHttpRequest.js": "./src/getXMLHttpRequest.browser.js" 9 | }, 10 | "author": { 11 | "name": "Netflix", 12 | "url": "https://github.com/Netflix/falcor/authors.txt" 13 | }, 14 | "repository": { 15 | "type": "git", 16 | "url": "git://github.com/Netflix/falcor-http-datasource.git" 17 | }, 18 | "licenses": [ 19 | { 20 | "type": "Apache License, Version 2.0", 21 | "url": "http://www.apache.org/licenses/LICENSE-2.0.html" 22 | } 23 | ], 24 | "scripts": { 25 | "build:pretty": "browserify ./src/XMLHttpSource.js > ./dist/XMLHttpSource.js", 26 | "build:min": "browserify . | uglifyjs > ./dist/XMLHttpSource.min.js", 27 | "build": "npm run build:min && npm run build:pretty", 28 | "test": "echo \"Error: no test specified\" && exit 1" 29 | }, 30 | "keywords": [ 31 | "Falcor", 32 | "Browser" 33 | ], 34 | "dependencies": { 35 | "xmlhttprequest": "^1.7.0" 36 | }, 37 | "license": "ALV2", 38 | "bugs": { 39 | "url": "https://github.com/Netflix/falcor-http-datasource/issues" 40 | }, 41 | "devDependencies": { 42 | "browserify": "^11.0.0", 43 | "uglifyjs": "^2.4.10" 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/XMLHttpSource.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | var request = require('./request'); 3 | var buildQueryObject = require('./buildQueryObject'); 4 | var isArray = Array.isArray; 5 | 6 | function simpleExtend(obj, obj2) { 7 | var prop; 8 | for (prop in obj2) { 9 | obj[prop] = obj2[prop]; 10 | } 11 | return obj; 12 | } 13 | 14 | function XMLHttpSource(jsongUrl, config) { 15 | this._jsongUrl = jsongUrl; 16 | if (typeof config === 'number') { 17 | var newConfig = { 18 | timeout: config 19 | }; 20 | config = newConfig; 21 | } 22 | this._config = simpleExtend({ 23 | timeout: 15000, 24 | headers: {} 25 | }, config || {}); 26 | } 27 | 28 | XMLHttpSource.prototype = { 29 | // because javascript 30 | constructor: XMLHttpSource, 31 | /** 32 | * buildQueryObject helper 33 | */ 34 | buildQueryObject: buildQueryObject, 35 | 36 | /** 37 | * @inheritDoc DataSource#get 38 | */ 39 | get: function httpSourceGet(pathSet) { 40 | var method = 'GET'; 41 | var queryObject = this.buildQueryObject(this._jsongUrl, method, { 42 | paths: pathSet, 43 | method: 'get' 44 | }); 45 | var config = simpleExtend(queryObject, this._config); 46 | // pass context for onBeforeRequest callback 47 | var context = this; 48 | return request(method, config, context); 49 | }, 50 | 51 | /** 52 | * @inheritDoc DataSource#set 53 | */ 54 | set: function httpSourceSet(jsongEnv) { 55 | var method = 'POST'; 56 | var config, queryObject; 57 | if (!this._config.headers || !this._config.headers["Content-Type"] || !this._config.headers["Content-Type"].match(/application\/json/)) { 58 | queryObject = this.buildQueryObject(this._jsongUrl, method, { 59 | jsonGraph: jsongEnv, 60 | method: 'set' 61 | }); 62 | config = simpleExtend(queryObject, this._config); 63 | config.headers["Content-Type"] = "application/x-www-form-urlencoded"; 64 | } else { 65 | config = simpleExtend({ 66 | url: this._jsongUrl, 67 | data: JSON.stringify({ 68 | jsonGraph: JSON.stringify(jsongEnv), 69 | method: 'set' 70 | }) 71 | }, this._config); 72 | } 73 | // pass context for onBeforeRequest callback 74 | var context = this; 75 | return request(method, config, context); 76 | 77 | }, 78 | 79 | /** 80 | * @inheritDoc DataSource#call 81 | */ 82 | call: function httpSourceCall(callPath, args, pathSuffix, paths) { 83 | // arguments defaults 84 | args = args || []; 85 | pathSuffix = pathSuffix || []; 86 | paths = paths || []; 87 | 88 | var method = 'POST'; 89 | var config, queryData = [], queryObject; 90 | if (!this._config.headers || !this._config.headers["Content-Type"] || !this._config.headers["Content-Type"].match(/application\/json/)) { 91 | queryData.push('method=call'); 92 | queryData.push('callPath=' + encodeURIComponent(JSON.stringify(callPath))); 93 | queryData.push('arguments=' + encodeURIComponent(JSON.stringify(args))); 94 | queryData.push('pathSuffixes=' + encodeURIComponent(JSON.stringify(pathSuffix))); 95 | queryData.push('paths=' + encodeURIComponent(JSON.stringify(paths))); 96 | 97 | queryObject = this.buildQueryObject(this._jsongUrl, method, queryData.join('&')); 98 | config = simpleExtend(queryObject, this._config); 99 | config.headers["Content-Type"] = "application/x-www-form-urlencoded"; 100 | } else { 101 | config = simpleExtend({ 102 | url: this._jsongUrl, 103 | data: JSON.stringify({ 104 | method: 'call', 105 | callPath: JSON.stringify(callPath), 106 | arguments: JSON.stringify(args), 107 | pathSuffixes: JSON.stringify(pathSuffix), 108 | paths: JSON.stringify(paths) 109 | }) 110 | }, this._config); 111 | } 112 | // pass context for onBeforeRequest callback 113 | var context = this; 114 | return request(method, config, context); 115 | } 116 | }; 117 | // ES6 modules 118 | XMLHttpSource.XMLHttpSource = XMLHttpSource; 119 | XMLHttpSource['default'] = XMLHttpSource; 120 | // commonjs 121 | module.exports = XMLHttpSource; 122 | -------------------------------------------------------------------------------- /src/buildQueryObject.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | module.exports = function buildQueryObject(url, method, queryData) { 3 | var qData = []; 4 | var keys; 5 | var data = {url: url}; 6 | var isQueryParamUrl = url.indexOf('?') !== -1; 7 | var startUrl = (isQueryParamUrl) ? '&' : '?'; 8 | 9 | if (typeof queryData === 'string') { 10 | qData.push(queryData); 11 | } else { 12 | 13 | keys = Object.keys(queryData); 14 | keys.forEach(function (k) { 15 | var value = (typeof queryData[k] === 'object') ? JSON.stringify(queryData[k]) : queryData[k]; 16 | qData.push(k + '=' + encodeURIComponent(value)); 17 | }); 18 | } 19 | 20 | if (method === 'GET') { 21 | data.url += startUrl + qData.join('&'); 22 | } else { 23 | data.data = qData.join('&'); 24 | } 25 | 26 | return data; 27 | }; 28 | -------------------------------------------------------------------------------- /src/getCORSRequest.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | // Get CORS support even for older IE 3 | module.exports = function getCORSRequest() { 4 | var xhr = new global.XMLHttpRequest(); 5 | if ('withCredentials' in xhr) { 6 | return xhr; 7 | } else if (!!global.XDomainRequest) { 8 | return new XDomainRequest(); 9 | } else { 10 | throw new Error('CORS is not supported by your browser'); 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /src/getXMLHttpRequest.browser.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | module.exports = function getXMLHttpRequest() { 3 | var progId, 4 | progIds, 5 | i; 6 | if (global.XMLHttpRequest) { 7 | return new global.XMLHttpRequest(); 8 | } else { 9 | try { 10 | progIds = ['Msxml2.XMLHTTP', 'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.4.0']; 11 | for (i = 0; i < 3; i++) { 12 | try { 13 | progId = progIds[i]; 14 | if (new global.ActiveXObject(progId)) { 15 | break; 16 | } 17 | } catch(e) { } 18 | } 19 | return new global.ActiveXObject(progId); 20 | } catch (e) { 21 | throw new Error('XMLHttpRequest is not supported by your browser'); 22 | } 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /src/getXMLHttpRequest.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | var xhr = require('xmlhttprequest'); 3 | module.exports = function getXMLHttpRequest() { 4 | var request = new xhr.XMLHttpRequest(); 5 | request.setDisableHeaderCheck(true); 6 | return request; 7 | }; 8 | -------------------------------------------------------------------------------- /src/request.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | var getXMLHttpRequest = require('./getXMLHttpRequest'); 3 | var getCORSRequest = require('./getCORSRequest'); 4 | var hasOwnProp = Object.prototype.hasOwnProperty; 5 | 6 | var noop = function() {}; 7 | 8 | function Observable() {} 9 | 10 | Observable.create = function(subscribe) { 11 | var o = new Observable(); 12 | 13 | o.subscribe = function(onNext, onError, onCompleted) { 14 | 15 | var observer; 16 | var disposable; 17 | 18 | if (typeof onNext === 'function') { 19 | observer = { 20 | onNext: onNext, 21 | onError: (onError || noop), 22 | onCompleted: (onCompleted || noop) 23 | }; 24 | } else { 25 | observer = onNext; 26 | } 27 | 28 | disposable = subscribe(observer); 29 | 30 | if (typeof disposable === 'function') { 31 | return { 32 | dispose: disposable 33 | }; 34 | } else { 35 | return disposable; 36 | } 37 | }; 38 | 39 | return o; 40 | }; 41 | 42 | function request(method, options, context) { 43 | return Observable.create(function requestObserver(observer) { 44 | 45 | var config = { 46 | method: method || 'GET', 47 | crossDomain: false, 48 | async: true, 49 | headers: {}, 50 | responseType: 'json' 51 | }; 52 | 53 | var xhr, 54 | isDone, 55 | headers, 56 | header, 57 | prop; 58 | 59 | for (prop in options) { 60 | if (hasOwnProp.call(options, prop)) { 61 | config[prop] = options[prop]; 62 | } 63 | } 64 | 65 | // Add request with Headers 66 | if (!config.crossDomain && !config.headers['X-Requested-With']) { 67 | config.headers['X-Requested-With'] = 'XMLHttpRequest'; 68 | } 69 | 70 | // allow the user to mutate the config open 71 | if (context.onBeforeRequest != null) { 72 | context.onBeforeRequest(config); 73 | } 74 | 75 | // create xhr 76 | try { 77 | xhr = config.crossDomain ? getCORSRequest() : getXMLHttpRequest(); 78 | } catch (err) { 79 | observer.onError(err); 80 | } 81 | try { 82 | // Takes the url and opens the connection 83 | if (config.user) { 84 | xhr.open(config.method, config.url, config.async, config.user, config.password); 85 | } else { 86 | xhr.open(config.method, config.url, config.async); 87 | } 88 | 89 | // Sets timeout information 90 | xhr.timeout = config.timeout; 91 | 92 | // Anything but explicit false results in true. 93 | xhr.withCredentials = config.withCredentials !== false; 94 | 95 | // Fills the request headers 96 | headers = config.headers; 97 | for (header in headers) { 98 | if (hasOwnProp.call(headers, header)) { 99 | xhr.setRequestHeader(header, headers[header]); 100 | } 101 | } 102 | 103 | if (config.responseType) { 104 | try { 105 | xhr.responseType = config.responseType; 106 | } catch (e) { 107 | // WebKit added support for the json responseType value on 09/03/2013 108 | // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are 109 | // known to throw when setting the value "json" as the response type. Other older 110 | // browsers implementing the responseType 111 | // 112 | // The json response type can be ignored if not supported, because JSON payloads are 113 | // parsed on the client-side regardless. 114 | if (config.responseType !== 'json') { 115 | throw e; 116 | } 117 | } 118 | } 119 | 120 | xhr.onreadystatechange = function onreadystatechange(e) { 121 | // Complete 122 | if (xhr.readyState === 4) { 123 | if (!isDone) { 124 | isDone = true; 125 | onXhrLoad(observer, xhr, e); 126 | } 127 | } 128 | }; 129 | 130 | // Timeout 131 | xhr.ontimeout = function ontimeout(e) { 132 | if (!isDone) { 133 | isDone = true; 134 | onXhrError(observer, xhr, 'timeout error', e); 135 | } 136 | }; 137 | 138 | // Send Request 139 | xhr.send(config.data); 140 | 141 | } catch (e) { 142 | observer.onError(e); 143 | } 144 | // Dispose 145 | return function dispose() { 146 | // Doesn't work in IE9 147 | if (!isDone && xhr.readyState !== 4) { 148 | isDone = true; 149 | xhr.abort(); 150 | } 151 | };//Dispose 152 | }); 153 | } 154 | 155 | /* 156 | * General handling of ultimate failure (after appropriate retries) 157 | */ 158 | function _handleXhrError(observer, textStatus, errorThrown) { 159 | // IE9: cross-domain request may be considered errors 160 | if (!errorThrown) { 161 | errorThrown = new Error(textStatus); 162 | } 163 | 164 | observer.onError(errorThrown); 165 | } 166 | 167 | function onXhrLoad(observer, xhr, e) { 168 | var responseData, 169 | responseObject, 170 | responseType; 171 | 172 | // If there's no observer, the request has been (or is being) cancelled. 173 | if (xhr && observer) { 174 | responseType = xhr.responseType; 175 | // responseText is the old-school way of retrieving response (supported by IE8 & 9) 176 | // response/responseType properties were introduced in XHR Level2 spec (supported by IE10) 177 | responseData = ('response' in xhr) ? xhr.response : xhr.responseText; 178 | 179 | // normalize IE9 bug (http://bugs.jquery.com/ticket/1450) 180 | var status = (xhr.status === 1223) ? 204 : xhr.status; 181 | 182 | if (status >= 200 && status <= 399) { 183 | try { 184 | if (responseType !== 'json') { 185 | responseData = JSON.parse(responseData || ''); 186 | } 187 | if (typeof responseData === 'string') { 188 | responseData = JSON.parse(responseData || ''); 189 | } 190 | } catch (e) { 191 | _handleXhrError(observer, 'invalid json', e); 192 | } 193 | observer.onNext(responseData); 194 | observer.onCompleted(); 195 | return; 196 | 197 | } else if (status === 401 || status === 403 || status === 407) { 198 | 199 | return _handleXhrError(observer, responseData); 200 | 201 | } else if (status === 410) { 202 | // TODO: Retry ? 203 | return _handleXhrError(observer, responseData); 204 | 205 | } else if (status === 408 || status === 504) { 206 | // TODO: Retry ? 207 | return _handleXhrError(observer, responseData); 208 | 209 | } else { 210 | 211 | return _handleXhrError(observer, responseData || ('Response code ' + status)); 212 | 213 | }//if 214 | }//if 215 | }//onXhrLoad 216 | 217 | function onXhrError(observer, xhr, status, e) { 218 | _handleXhrError(observer, status || xhr.statusText || 'request error', e); 219 | } 220 | 221 | module.exports = request; 222 | -------------------------------------------------------------------------------- /ts/falcor-browser.d.ts: -------------------------------------------------------------------------------- 1 | declare module "falcor-browser" { 2 | function get(pathSet: any): any; 3 | function set(jsongEnv): any; 4 | function call(callPath: any, args?: any, pathSuffix?: any, paths?: any): any; 5 | 6 | interface IXMLHttpSource { 7 | get(pathSet: any): any; 8 | set(jsongEnv): any; 9 | call(callPath: any, args?: any, pathSuffix?: any, paths?: any): any; 10 | } 11 | export class XMLHttpSource implements IXMLHttpSource { 12 | constructor(...args); 13 | get(pathSet: any): any; 14 | set(jsongEnv): any; 15 | call(callPath: any, args?: any, pathSuffix?: any, paths?: any): any; 16 | } 17 | export default XMLHttpSource 18 | } 19 | -------------------------------------------------------------------------------- /ts/falcor-http-datasource.d.ts: -------------------------------------------------------------------------------- 1 | declare module "falcor-http-datasource" { 2 | function get(pathSet: any): any; 3 | function set(jsongEnv): any; 4 | function call(callPath: any, args?: any, pathSuffix?: any, paths?: any): any; 5 | 6 | interface IXMLHttpSource { 7 | get(pathSet: any): any; 8 | set(jsongEnv): any; 9 | call(callPath: any, args?: any, pathSuffix?: any, paths?: any): any; 10 | } 11 | export class XMLHttpSource implements IXMLHttpSource { 12 | constructor(...args); 13 | get(pathSet: any): any; 14 | set(jsongEnv): any; 15 | call(callPath: any, args?: any, pathSuffix?: any, paths?: any): any; 16 | } 17 | export default XMLHttpSource 18 | } 19 | --------------------------------------------------------------------------------