UNPKG

8.78 kBJavaScriptView Raw
1import { createToken, createPlugin } from 'fusion-core';
2import { UniversalEventsToken } from 'fusion-plugin-universal-events';
3import { FetchToken } from 'fusion-tokens';
4import mapObject from 'just-map-object';
5import isEqual from 'just-compare';
6
7/** Copyright (c) 2018 Uber Technologies, Inc.
8 *
9 * This source code is licensed under the MIT license found in the
10 * LICENSE file in the root directory of this source tree.
11 *
12 *
13 */
14var RPCToken = createToken('RPCToken');
15var RPCHandlersToken = createToken('RPCHandlersToken');
16var BodyParserOptionsToken = createToken('BodyParserOptionsToken');
17var RPCHandlersConfigToken = createToken('RPCHandlersConfigToken');
18
19var formatApiPath = function formatApiPath(apiPath) {
20 return ("/" + apiPath + "/").replace(/\/{2,}/g, '/');
21};
22
23function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }
24
25function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
26
27/** Copyright (c) 2018 Uber Technologies, Inc.
28 *
29 * This source code is licensed under the MIT license found in the
30 * LICENSE file in the root directory of this source tree.
31 *
32 *
33 */
34
35/* eslint-env browser */
36var statKey = 'rpc:method-client';
37
38var RPC =
39/*#__PURE__*/
40function () {
41 function RPC(_ref) {
42 var fetch = _ref.fetch,
43 emitter = _ref.emitter,
44 rpcConfig = _ref.rpcConfig;
45 this.fetch = fetch;
46 this.config = rpcConfig || {};
47 this.emitter = emitter;
48 this.apiPath = formatApiPath(rpcConfig && rpcConfig.apiPath ? rpcConfig.apiPath : 'api');
49 }
50
51 var _proto = RPC.prototype;
52
53 _proto.request = function request(rpcId, args, headers) {
54 if (!this.fetch) {
55 throw new Error('fusion-plugin-rpc requires `fetch`');
56 }
57
58 if (!this.emitter) {
59 throw new Error('Missing emitter registered to UniversalEventsToken');
60 }
61
62 var fetch = this.fetch;
63 var emitter = this.emitter;
64 var apiPath = this.apiPath;
65 var startTime = Date.now(); // TODO(#3) handle args instanceof FormData
66
67 return fetch("" + apiPath + rpcId, {
68 method: 'POST',
69 headers: _objectSpread({
70 'Content-Type': 'application/json'
71 }, headers || {}),
72 body: JSON.stringify(args || {})
73 }).then(function (r) {
74 return r.json();
75 }).then(function (args) {
76 var status = args.status,
77 data = args.data;
78
79 if (status === 'success') {
80 emitter.emit(statKey, {
81 method: rpcId,
82 status: 'success',
83 timing: Date.now() - startTime
84 });
85 return data;
86 } else {
87 emitter.emit(statKey, {
88 method: rpcId,
89 error: data,
90 status: 'failure',
91 timing: Date.now() - startTime
92 });
93 return Promise.reject(data);
94 }
95 });
96 };
97
98 return RPC;
99}();
100
101var pluginFactory = function pluginFactory() {
102 return createPlugin({
103 deps: {
104 fetch: FetchToken,
105 emitter: UniversalEventsToken,
106 rpcConfig: RPCHandlersConfigToken.optional
107 },
108 provides: function provides(deps) {
109 var _deps$fetch = deps.fetch,
110 fetch = _deps$fetch === void 0 ? window.fetch : _deps$fetch,
111 emitter = deps.emitter,
112 rpcConfig = deps.rpcConfig;
113 return {
114 from: function from() {
115 return new RPC({
116 fetch: fetch,
117 emitter: emitter,
118 rpcConfig: rpcConfig
119 });
120 }
121 };
122 }
123 });
124};
125
126var browserDataFetching = true && pluginFactory();
127
128function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
129
130/** Copyright (c) 2018 Uber Technologies, Inc.
131 *
132 * This source code is licensed under the MIT license found in the
133 * LICENSE file in the root directory of this source tree.
134 *
135 *
136 */
137var MissingHandlerError =
138/*#__PURE__*/
139function (_Error) {
140 _inheritsLoose(MissingHandlerError, _Error);
141
142 function MissingHandlerError(method) {
143 var _this;
144
145 _this = _Error.call(this, "Missing RPC handler for " + method) || this;
146 _this.code = 'ERR_MISSING_HANDLER';
147 Error.captureStackTrace(_this, MissingHandlerError);
148 return _this;
149 }
150
151 return MissingHandlerError;
152}(Error);
153
154function _inheritsLoose$1(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
155
156/** Copyright (c) 2018 Uber Technologies, Inc.
157 *
158 * This source code is licensed under the MIT license found in the
159 * LICENSE file in the root directory of this source tree.
160 *
161 *
162 */
163var ResponseError =
164/*#__PURE__*/
165function (_Error) {
166 _inheritsLoose$1(ResponseError, _Error);
167
168 function ResponseError(message) {
169 var _this;
170
171 _this = _Error.call(this, message) || this;
172 _this.code = null;
173 _this.meta = null;
174 Error.captureStackTrace(_this, ResponseError);
175 return _this;
176 }
177
178 return ResponseError;
179}(Error);
180
181/** Copyright (c) 2018 Uber Technologies, Inc.
182 *
183 * This source code is licensed under the MIT license found in the
184 * LICENSE file in the root directory of this source tree.
185 *
186 *
187 */
188
189/* eslint-env node */
190
191/** Copyright (c) 2018 Uber Technologies, Inc.
192 *
193 * This source code is licensed under the MIT license found in the
194 * LICENSE file in the root directory of this source tree.
195 *
196 *
197 */
198var RPC$2 =
199/*#__PURE__*/
200function () {
201 function RPC(handlers) {
202 this.handlers = handlers;
203 }
204
205 var _proto = RPC.prototype;
206
207 _proto.request = function request(method, args) {
208 return new Promise(function ($return, $error) {
209 if (!this.handlers) {
210 return $error(new Error('fusion-plugin-rpc requires `handlers`'));
211 }
212
213 if (!this.handlers[method]) {
214 return $error(new MissingHandlerError(method));
215 }
216
217 return $return(this.handlers[method](args));
218 }.bind(this));
219 };
220
221 return RPC;
222}();
223
224var plugin = createPlugin({
225 deps: {
226 handlers: RPCHandlersToken,
227 emitter: UniversalEventsToken
228 },
229 provides: function provides(_temp) {
230 var _ref = _temp === void 0 ? {} : _temp,
231 handlers = _ref.handlers;
232
233 return {
234 from: function from() {
235 return new RPC$2(handlers);
236 }
237 };
238 }
239});
240
241function _objectSpread$1(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty$1(target, key, source[key]); }); } return target; }
242
243function _defineProperty$1(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
244
245var getMockRpcHandlers = function getMockRpcHandlers(fixtures, onMockRpc) {
246 return fixtures.reduce(function (rpcHandlers, fixture) {
247 return _objectSpread$1({}, rpcHandlers, mapObject(fixture, function (rpcId, responseDetails) {
248 return function () {
249 var $args = arguments;
250 return new Promise(function ($return, $error) {
251 for (var _len = $args.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
252 args[_key] = $args[_key];
253 }
254
255 var response = Array.isArray(responseDetails) ? responseDetails.filter(function (item) {
256 return isEqual(item.args, args);
257 })[0].response : responseDetails;
258 onMockRpc && onMockRpc(rpcId, args, response);
259
260 if (response instanceof Error) {
261 return $error(response);
262 }
263
264 return $return(response);
265 });
266 };
267 }));
268 }, {});
269};
270
271/** Copyright (c) 2018 Uber Technologies, Inc.
272 *
273 * This source code is licensed under the MIT license found in the
274 * LICENSE file in the root directory of this source tree.
275 *
276 *
277 */
278var index = browserDataFetching;
279
280export default index;
281export { plugin as mock, ResponseError, BodyParserOptionsToken, RPCToken, RPCHandlersToken, RPCHandlersConfigToken, getMockRpcHandlers };