UNPKG

9.67 kBJavaScriptView Raw
1'use strict';
2
3Object.defineProperty(exports, '__esModule', { value: true });
4
5function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
6
7var fusionCore = require('fusion-core');
8var fusionPluginUniversalEvents = require('fusion-plugin-universal-events');
9var bodyparser = _interopDefault(require('koa-bodyparser'));
10var mapObject = _interopDefault(require('just-map-object'));
11var isEqual = _interopDefault(require('just-compare'));
12
13/** Copyright (c) 2018 Uber Technologies, Inc.
14 *
15 * This source code is licensed under the MIT license found in the
16 * LICENSE file in the root directory of this source tree.
17 *
18 *
19 */
20const RPCToken = fusionCore.createToken('RPCToken');
21const RPCHandlersToken = fusionCore.createToken('RPCHandlersToken');
22const BodyParserOptionsToken = fusionCore.createToken('BodyParserOptionsToken');
23const RPCHandlersConfigToken = fusionCore.createToken('RPCHandlersConfigToken');
24
25const formatApiPath = apiPath => `/${apiPath}/`.replace(/\/{2,}/g, '/');
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 */
36
37/** Copyright (c) 2018 Uber Technologies, Inc.
38 *
39 * This source code is licensed under the MIT license found in the
40 * LICENSE file in the root directory of this source tree.
41 *
42 *
43 */
44class MissingHandlerError extends Error {
45 constructor(method) {
46 super(`Missing RPC handler for ${method}`);
47 this.code = 'ERR_MISSING_HANDLER';
48 Error.captureStackTrace(this, MissingHandlerError);
49 }
50
51}
52
53/** Copyright (c) 2018 Uber Technologies, Inc.
54 *
55 * This source code is licensed under the MIT license found in the
56 * LICENSE file in the root directory of this source tree.
57 *
58 *
59 */
60class ResponseError extends Error {
61 constructor(message) {
62 super(message);
63 this.code = null;
64 this.meta = null;
65 Error.captureStackTrace(this, ResponseError);
66 }
67
68}
69
70/** Copyright (c) 2018 Uber Technologies, Inc.
71 *
72 * This source code is licensed under the MIT license found in the
73 * LICENSE file in the root directory of this source tree.
74 *
75 *
76 */
77
78/* eslint-env node */
79const statKey$1 = 'rpc:method';
80/* Helper function */
81
82function hasHandler(handlers, method) {
83 return handlers.hasOwnProperty(method);
84}
85
86class RPC$1 {
87 constructor(emitter, handlers, ctx) {
88 if (!ctx || !ctx.headers) {
89 throw new Error('fusion-plugin-rpc requires `ctx`');
90 }
91
92 this.ctx = ctx;
93 this.emitter = emitter;
94 this.handlers = handlers;
95 return this;
96 }
97
98 async request(method, args) {
99 const startTime = ms();
100
101 if (!this.ctx) {
102 throw new Error('fusion-plugin-rpc requires `ctx`');
103 }
104
105 if (!this.emitter) {
106 throw new Error('fusion-plugin-rpc requires `emitter`');
107 }
108
109 const scopedEmitter = this.emitter.from(this.ctx);
110
111 if (!this.handlers) {
112 throw new Error('fusion-plugin-rpc requires `handlers`');
113 }
114
115 if (!hasHandler(this.handlers, method)) {
116 const e = new MissingHandlerError(method);
117
118 if (scopedEmitter) {
119 scopedEmitter.emit('rpc:error', {
120 method,
121 origin: 'server',
122 error: e
123 });
124 }
125
126 throw e;
127 }
128
129 try {
130 const result = await this.handlers[method](args, this.ctx);
131
132 if (scopedEmitter) {
133 scopedEmitter.emit(statKey$1, {
134 method,
135 status: 'success',
136 origin: 'server',
137 timing: ms() - startTime
138 });
139 }
140
141 return result;
142 } catch (e) {
143 if (scopedEmitter) {
144 scopedEmitter.emit(statKey$1, {
145 method,
146 error: e,
147 status: 'failure',
148 origin: 'server',
149 timing: ms() - startTime
150 });
151 }
152
153 throw e;
154 }
155 }
156
157}
158
159const pluginFactory$1 = () => fusionCore.createPlugin({
160 deps: {
161 emitter: fusionPluginUniversalEvents.UniversalEventsToken,
162 handlers: RPCHandlersToken,
163 bodyParserOptions: BodyParserOptionsToken.optional,
164 rpcConfig: RPCHandlersConfigToken.optional
165 },
166 provides: deps => {
167 const {
168 emitter,
169 handlers
170 } = deps;
171 const service = {
172 from: fusionCore.memoize(ctx => new RPC$1(emitter, handlers, ctx))
173 };
174 return service;
175 },
176 middleware: deps => {
177 const {
178 emitter,
179 handlers,
180 bodyParserOptions,
181 rpcConfig
182 } = deps;
183 if (!handlers) throw new Error('Missing handlers registered to RPCHandlersToken');
184 if (!emitter) throw new Error('Missing emitter registered to UniversalEventsToken');
185 const parseBody = bodyparser(bodyParserOptions);
186 const apiPath = formatApiPath(rpcConfig && rpcConfig.apiPath ? rpcConfig.apiPath : 'api');
187 return async (ctx, next) => {
188 await next();
189 const scopedEmitter = emitter.from(ctx);
190
191 if (ctx.method === 'POST' && ctx.path.startsWith(apiPath)) {
192 const startTime = ms(); // eslint-disable-next-line no-useless-escape
193
194 const pathMatch = new RegExp(`${apiPath}([^/]+)`, 'i');
195 const [, method] = ctx.path.match(pathMatch) || [];
196
197 if (hasHandler(handlers, method)) {
198 await parseBody(ctx, () => Promise.resolve());
199
200 try {
201 const result = await handlers[method](ctx.request.body, ctx);
202 ctx.body = {
203 status: 'success',
204 data: result
205 };
206
207 if (scopedEmitter) {
208 scopedEmitter.emit(statKey$1, {
209 method,
210 status: 'success',
211 origin: 'browser',
212 timing: ms() - startTime
213 });
214 }
215 } catch (e) {
216 const error = e instanceof ResponseError ? e : new Error('UnknownError - Use ResponseError from fusion-plugin-rpc (or fusion-plugin-rpc-redux-react if you are using React) package for more detailed error messages');
217 ctx.body = {
218 status: 'failure',
219 data: {
220 message: error.message,
221 // $FlowFixMe
222 code: error.code,
223 // $FlowFixMe
224 meta: error.meta
225 }
226 };
227
228 if (scopedEmitter) {
229 scopedEmitter.emit(statKey$1, {
230 method,
231 error: e,
232 status: 'failure',
233 origin: 'browser',
234 timing: ms() - startTime
235 });
236 }
237 }
238 } else {
239 const e = new MissingHandlerError(method);
240 ctx.body = {
241 status: 'failure',
242 data: {
243 message: e.message,
244 code: e.code
245 }
246 };
247 ctx.status = 404;
248
249 if (scopedEmitter) {
250 scopedEmitter.emit('rpc:error', {
251 origin: 'browser',
252 method,
253 error: e
254 });
255 }
256 }
257 }
258 };
259 }
260});
261/* Helper functions */
262
263
264function ms() {
265 const [seconds, ns] = process.hrtime();
266 return Math.round(seconds * 1000 + ns / 1e6);
267}
268
269var serverDataFetching = true && pluginFactory$1();
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 */
278class RPC$2 {
279 constructor(handlers) {
280 this.handlers = handlers;
281 }
282
283 async request(method, args) {
284 if (!this.handlers) {
285 throw new Error('fusion-plugin-rpc requires `handlers`');
286 }
287
288 if (!this.handlers[method]) {
289 throw new MissingHandlerError(method);
290 }
291
292 return this.handlers[method](args);
293 }
294
295}
296
297const plugin = fusionCore.createPlugin({
298 deps: {
299 handlers: RPCHandlersToken,
300 emitter: fusionPluginUniversalEvents.UniversalEventsToken
301 },
302 provides: ({
303 handlers
304 } = {}) => {
305 return {
306 from: () => new RPC$2(handlers)
307 };
308 }
309});
310
311function _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; }
312
313function _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; }
314
315const getMockRpcHandlers = (fixtures, onMockRpc) => fixtures.reduce((rpcHandlers, fixture) => _objectSpread$1({}, rpcHandlers, mapObject(fixture, (rpcId, responseDetails) => async (...args) => {
316 const response = Array.isArray(responseDetails) ? responseDetails.filter(item => isEqual(item.args, args))[0].response : responseDetails;
317 onMockRpc && onMockRpc(rpcId, args, response);
318
319 if (response instanceof Error) {
320 throw response;
321 }
322
323 return response;
324})), {});
325
326/** Copyright (c) 2018 Uber Technologies, Inc.
327 *
328 * This source code is licensed under the MIT license found in the
329 * LICENSE file in the root directory of this source tree.
330 *
331 *
332 */
333var index = serverDataFetching;
334
335exports.default = index;
336exports.mock = plugin;
337exports.ResponseError = ResponseError;
338exports.BodyParserOptionsToken = BodyParserOptionsToken;
339exports.RPCToken = RPCToken;
340exports.RPCHandlersToken = RPCHandlersToken;
341exports.RPCHandlersConfigToken = RPCHandlersConfigToken;
342exports.getMockRpcHandlers = getMockRpcHandlers;