@webiny/handler 0.0.0-mt-3 → 0.0.0-unstable.8c4d9f045a

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/Context.d.ts ADDED
@@ -0,0 +1,13 @@
1
+ import { Context as BaseContext, ContextParams as BaseContextParams } from "@webiny/api";
2
+ import { Context as BaseContextType } from "./types";
3
+ export interface ContextParams extends BaseContextParams {
4
+ server: BaseContextType["server"];
5
+ routes: BaseContextType["routes"];
6
+ }
7
+ export declare class Context extends BaseContext implements BaseContextType {
8
+ readonly server: BaseContextType["server"];
9
+ readonly routes: BaseContextType["routes"];
10
+ handlerClient: BaseContextType["handlerClient"];
11
+ request: BaseContextType["request"];
12
+ constructor(params: ContextParams);
13
+ }
package/Context.js ADDED
@@ -0,0 +1,29 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+
5
+ Object.defineProperty(exports, "__esModule", {
6
+ value: true
7
+ });
8
+ exports.Context = void 0;
9
+
10
+ var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
11
+
12
+ var _api = require("@webiny/api");
13
+
14
+ class Context extends _api.Context {
15
+ // @ts-ignore
16
+ // @ts-ignore
17
+ constructor(params) {
18
+ super(params);
19
+ (0, _defineProperty2.default)(this, "server", void 0);
20
+ (0, _defineProperty2.default)(this, "routes", void 0);
21
+ (0, _defineProperty2.default)(this, "handlerClient", void 0);
22
+ (0, _defineProperty2.default)(this, "request", void 0);
23
+ this.server = params.server;
24
+ this.routes = params.routes;
25
+ }
26
+
27
+ }
28
+
29
+ exports.Context = Context;
package/Context.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"names":["Context","BaseContext","constructor","params","server","routes"],"sources":["Context.ts"],"sourcesContent":["import { Context as BaseContext, ContextParams as BaseContextParams } from \"@webiny/api\";\nimport { Context as BaseContextType } from \"~/types\";\n\nexport interface ContextParams extends BaseContextParams {\n server: BaseContextType[\"server\"];\n routes: BaseContextType[\"routes\"];\n}\n\nexport class Context extends BaseContext implements BaseContextType {\n public readonly server: BaseContextType[\"server\"];\n public readonly routes: BaseContextType[\"routes\"];\n // @ts-ignore\n public handlerClient: BaseContextType[\"handlerClient\"];\n // @ts-ignore\n public request: BaseContextType[\"request\"];\n\n public constructor(params: ContextParams) {\n super(params);\n this.server = params.server;\n this.routes = params.routes;\n }\n}\n"],"mappings":";;;;;;;;;;;AAAA;;AAQO,MAAMA,OAAN,SAAsBC,YAAtB,CAA6D;EAGhE;EAEA;EAGOC,WAAW,CAACC,MAAD,EAAwB;IACtC,MAAMA,MAAN;IADsC;IAAA;IAAA;IAAA;IAEtC,KAAKC,MAAL,GAAcD,MAAM,CAACC,MAArB;IACA,KAAKC,MAAL,GAAcF,MAAM,CAACE,MAArB;EACH;;AAZ+D"}
package/README.md CHANGED
@@ -4,6 +4,12 @@
4
4
  [![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat-square)](https://github.com/prettier/prettier)
5
5
  [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](http://makeapullrequest.com)
6
6
 
7
- A tiny, universal, and plugin-based framework for creating (serverless) handlers, used within services like AWS Lambda, Azure Serverless Functions, and others.
7
+ ## Install
8
+ ```
9
+ npm install --save @webiny/handler
10
+ ```
8
11
 
9
- A handler can be anything from a simple event-handler, to a fully-fledged GraphQL server. It all depends on the additional plugins that are passed upon the creating the handler.
12
+ Or if you prefer yarn:
13
+ ```
14
+ yarn add @webiny/handler
15
+ ```
package/fastify.d.ts ADDED
@@ -0,0 +1,8 @@
1
+ /// <reference types="node" />
2
+ import { PluginCollection } from "@webiny/plugins/types";
3
+ import { FastifyServerOptions as ServerOptions } from "fastify";
4
+ export interface CreateHandlerParams {
5
+ plugins: PluginCollection;
6
+ options?: ServerOptions;
7
+ }
8
+ export declare const createHandler: (params: CreateHandlerParams) => import("fastify").FastifyInstance<import("http").Server, import("http").IncomingMessage, import("http").ServerResponse, import("fastify").FastifyLoggerInstance, import("fastify").FastifyTypeProviderDefault> & PromiseLike<import("fastify").FastifyInstance<import("http").Server, import("http").IncomingMessage, import("http").ServerResponse, import("fastify").FastifyLoggerInstance, import("fastify").FastifyTypeProviderDefault>>;
package/fastify.js ADDED
@@ -0,0 +1,315 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+
5
+ Object.defineProperty(exports, "__esModule", {
6
+ value: true
7
+ });
8
+ exports.createHandler = void 0;
9
+
10
+ var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
11
+
12
+ var _fastify = _interopRequireDefault(require("fastify"));
13
+
14
+ var _utils = require("@webiny/utils");
15
+
16
+ var _Context = require("./Context");
17
+
18
+ var _error = _interopRequireDefault(require("@webiny/error"));
19
+
20
+ var _RoutePlugin = require("./plugins/RoutePlugin");
21
+
22
+ var _handlerClient = require("@webiny/handler-client");
23
+
24
+ var _cookie = _interopRequireDefault(require("@fastify/cookie"));
25
+
26
+ var _middleware = require("./middleware");
27
+
28
+ var _api = require("@webiny/api");
29
+
30
+ var _BeforeHandlerPlugin = require("./plugins/BeforeHandlerPlugin");
31
+
32
+ var _HandlerResultPlugin = require("./plugins/HandlerResultPlugin");
33
+
34
+ var _HandlerErrorPlugin = require("./plugins/HandlerErrorPlugin");
35
+
36
+ function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
37
+
38
+ function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { (0, _defineProperty2.default)(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
39
+
40
+ const DEFAULT_HEADERS = _objectSpread({
41
+ "Cache-Control": "no-store",
42
+ "Content-Type": "application/json; charset=utf-8",
43
+ "Access-Control-Allow-Origin": "*",
44
+ "Access-Control-Allow-Headers": "*",
45
+ "Access-Control-Allow-Methods": "OPTIONS,POST,GET,DELETE,PUT,PATCH"
46
+ }, (0, _utils.getWebinyVersionHeaders)());
47
+
48
+ const getDefaultHeaders = routes => {
49
+ /**
50
+ * If we are accepting all headers, just output that one.
51
+ */
52
+ const keys = Object.keys(routes);
53
+ const all = keys.every(key => routes[key].length > 0);
54
+
55
+ if (all) {
56
+ return _objectSpread(_objectSpread({}, DEFAULT_HEADERS), {}, {
57
+ "Access-Control-Allow-Methods": "*"
58
+ });
59
+ }
60
+
61
+ return _objectSpread(_objectSpread({}, DEFAULT_HEADERS), {}, {
62
+ "Access-Control-Allow-Methods": keys.filter(key => {
63
+ const type = key;
64
+
65
+ if (!routes[type] || Array.isArray(routes[type]) === false) {
66
+ return false;
67
+ }
68
+
69
+ return routes[type].length > 0;
70
+ }).sort().join(",")
71
+ });
72
+ };
73
+
74
+ const OPTIONS_HEADERS = {
75
+ "Access-Control-Max-Age": "86400",
76
+ "Cache-Control": "public, max-age=86400"
77
+ };
78
+
79
+ const createHandler = params => {
80
+ const definedRoutes = {
81
+ POST: [],
82
+ GET: [],
83
+ OPTIONS: [],
84
+ DELETE: [],
85
+ PATCH: [],
86
+ PUT: [],
87
+ HEAD: []
88
+ };
89
+
90
+ const throwOnDefinedRoute = (type, path, options) => {
91
+ if (type === "ALL") {
92
+ const all = Object.keys(definedRoutes).some(key => {
93
+ const routes = definedRoutes[key];
94
+ return routes.includes(path);
95
+ });
96
+
97
+ if (!all) {
98
+ return;
99
+ }
100
+
101
+ throw new _error.default(`You cannot override a route with onAll() method, please remove unnecessary route from the system.`, "OVERRIDE_ROUTE_ERROR", {
102
+ type,
103
+ path
104
+ });
105
+ } else if (definedRoutes[type].includes(path) === false) {
106
+ return;
107
+ } else if ((options === null || options === void 0 ? void 0 : options.override) === true) {
108
+ return;
109
+ }
110
+
111
+ throw new _error.default(`When you are trying to override existing route, you must send "override" parameter when adding that route.`, "OVERRIDE_ROUTE_ERROR", {
112
+ type,
113
+ path
114
+ });
115
+ };
116
+
117
+ const addDefinedRoute = (inputType, path) => {
118
+ const type = inputType.toUpperCase();
119
+
120
+ if (!definedRoutes[type]) {
121
+ return;
122
+ } else if (definedRoutes[type].includes(path)) {
123
+ return;
124
+ }
125
+
126
+ definedRoutes[type].push(path);
127
+ };
128
+ /**
129
+ * We must attach the server to our internal context if we want to have it accessible.
130
+ */
131
+
132
+
133
+ const app = (0, _fastify.default)(_objectSpread({}, params.options || {}));
134
+ /**
135
+ * We need to register routes in our system so we can output headers later on and dissallow overriding routes.
136
+ */
137
+
138
+ app.addHook("onRoute", route => {
139
+ const method = route.method;
140
+
141
+ if (Array.isArray(method)) {
142
+ for (const m of method) {
143
+ addDefinedRoute(m, route.path);
144
+ }
145
+
146
+ return;
147
+ }
148
+
149
+ addDefinedRoute(method, route.path);
150
+ });
151
+ /**
152
+ *
153
+ */
154
+
155
+ app.register(_cookie.default, {
156
+ parseOptions: {} // options for parsing cookies
157
+
158
+ });
159
+ /**
160
+ * Route helpers - mostly for users.
161
+ */
162
+
163
+ const routes = {
164
+ defined: definedRoutes,
165
+ onPost: (path, handler, options) => {
166
+ throwOnDefinedRoute("POST", path, options);
167
+ app.post(path, handler);
168
+ },
169
+ onGet: (path, handler, options) => {
170
+ throwOnDefinedRoute("GET", path, options);
171
+ app.get(path, handler);
172
+ },
173
+ onOptions: (path, handler, options) => {
174
+ throwOnDefinedRoute("OPTIONS", path, options);
175
+ app.options(path, handler);
176
+ },
177
+ onDelete: (path, handler, options) => {
178
+ throwOnDefinedRoute("DELETE", path, options);
179
+ app.delete(path, handler);
180
+ },
181
+ onPatch: (path, handler, options) => {
182
+ throwOnDefinedRoute("PATCH", path, options);
183
+ app.patch(path, handler);
184
+ },
185
+ onPut: (path, handler, options) => {
186
+ throwOnDefinedRoute("PUT", path, options);
187
+ app.put(path, handler);
188
+ },
189
+ onAll: (path, handler, options) => {
190
+ throwOnDefinedRoute("ALL", path, options);
191
+ app.all(path, handler);
192
+ },
193
+ onHead: (path, handler, options) => {
194
+ throwOnDefinedRoute("HEAD", path, options);
195
+ app.head(path, handler);
196
+ }
197
+ };
198
+ const context = new _Context.Context({
199
+ plugins: [
200
+ /**
201
+ * We must have handlerClient by default.
202
+ * And it must be one of the first context plugins applied.
203
+ */
204
+ (0, _handlerClient.createHandlerClient)(), ...(params.plugins || [])],
205
+
206
+ /**
207
+ * Inserted via webpack on build time.
208
+ */
209
+ WEBINY_VERSION: process.env.WEBINY_VERSION,
210
+ server: app,
211
+ routes
212
+ });
213
+ /**
214
+ * We are attaching our custom context to webiny variable on the fastify app so it is accessible everywhere
215
+ */
216
+
217
+ app.decorate("webiny", context);
218
+ /**
219
+ * We have few types of triggers:
220
+ * * Events - EventPlugin
221
+ * * Routes - RoutePlugin
222
+ *
223
+ * Routes are registered in fastify but events must be handled in package which implements cloud specific methods.
224
+ */
225
+
226
+ const routePlugins = app.webiny.plugins.byType(_RoutePlugin.RoutePlugin.type);
227
+ /**
228
+ * Add routes to the system.
229
+ */
230
+
231
+ for (const plugin of routePlugins) {
232
+ plugin.cb(_objectSpread(_objectSpread({}, app.webiny.routes), {}, {
233
+ context: app.webiny
234
+ }));
235
+ }
236
+ /**
237
+ * On every request we add default headers, which can be changed later.
238
+ * Also, if it is an options request, we skip everything after this hook and output options headers.
239
+ */
240
+
241
+
242
+ app.addHook("onRequest", async (request, reply) => {
243
+ const defaultHeaders = getDefaultHeaders(definedRoutes);
244
+ reply.headers(defaultHeaders);
245
+
246
+ if (request.method !== "OPTIONS") {
247
+ return;
248
+ }
249
+
250
+ const raw = reply.code(204).hijack().raw;
251
+
252
+ const headers = _objectSpread(_objectSpread({}, defaultHeaders), OPTIONS_HEADERS);
253
+
254
+ for (const key in headers) {
255
+ raw.setHeader(key, headers[key]);
256
+ }
257
+
258
+ raw.end("");
259
+ });
260
+ app.addHook("preParsing", async request => {
261
+ app.webiny.request = request;
262
+ const plugins = app.webiny.plugins.byType(_api.ContextPlugin.type);
263
+
264
+ for (const plugin of plugins) {
265
+ await plugin.apply(app.webiny);
266
+ }
267
+ });
268
+ /**
269
+ *
270
+ */
271
+
272
+ app.addHook("preHandler", async () => {
273
+ const plugins = app.webiny.plugins.byType(_BeforeHandlerPlugin.BeforeHandlerPlugin.type);
274
+
275
+ for (const plugin of plugins) {
276
+ await plugin.apply(app.webiny);
277
+ }
278
+ });
279
+ /**
280
+ *
281
+ */
282
+
283
+ const preSerialization = async (_, __, payload) => {
284
+ const plugins = app.webiny.plugins.byType(_HandlerResultPlugin.HandlerResultPlugin.type);
285
+
286
+ for (const plugin of plugins) {
287
+ await plugin.handle(app.webiny, payload);
288
+ }
289
+
290
+ return payload;
291
+ };
292
+
293
+ app.addHook("preSerialization", preSerialization);
294
+ app.addHook("onError", async (_, reply, error) => {
295
+ const plugins = app.webiny.plugins.byType(_HandlerErrorPlugin.HandlerErrorPlugin.type); // Log error to cloud, as these can be extremely annoying to debug!
296
+
297
+ console.log("@webiny/handler");
298
+ console.log(JSON.stringify(_objectSpread(_objectSpread({}, error || {}), {}, {
299
+ message: error === null || error === void 0 ? void 0 : error.message,
300
+ code: error === null || error === void 0 ? void 0 : error.code
301
+ })));
302
+ const handler = (0, _middleware.middleware)(plugins.map(pl => {
303
+ return (context, error, next) => {
304
+ return pl.handle(context, error, next);
305
+ };
306
+ }));
307
+ await handler(app.webiny, error);
308
+ return reply.headers({
309
+ "Cache-Control": "no-store"
310
+ }).status(500);
311
+ });
312
+ return app;
313
+ };
314
+
315
+ exports.createHandler = createHandler;
package/fastify.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"names":["DEFAULT_HEADERS","getWebinyVersionHeaders","getDefaultHeaders","routes","keys","Object","all","every","key","length","filter","type","Array","isArray","sort","join","OPTIONS_HEADERS","createHandler","params","definedRoutes","POST","GET","OPTIONS","DELETE","PATCH","PUT","HEAD","throwOnDefinedRoute","path","options","some","includes","WebinyError","override","addDefinedRoute","inputType","toUpperCase","push","app","fastify","addHook","route","method","m","register","fastifyCookies","parseOptions","defined","onPost","handler","post","onGet","get","onOptions","onDelete","delete","onPatch","patch","onPut","put","onAll","onHead","head","context","Context","plugins","createHandlerClient","WEBINY_VERSION","process","env","server","decorate","routePlugins","webiny","byType","RoutePlugin","plugin","cb","request","reply","defaultHeaders","headers","raw","code","hijack","setHeader","end","ContextPlugin","apply","BeforeHandlerPlugin","preSerialization","_","__","payload","HandlerResultPlugin","handle","error","HandlerErrorPlugin","console","log","JSON","stringify","message","middleware","map","pl","next","status"],"sources":["fastify.ts"],"sourcesContent":["import { PluginCollection } from \"@webiny/plugins/types\";\nimport fastify, {\n FastifyServerOptions as ServerOptions,\n preSerializationAsyncHookHandler\n} from \"fastify\";\nimport { getWebinyVersionHeaders } from \"@webiny/utils\";\nimport { ContextRoutes, DefinedContextRoutes, RouteMethodOptions, RouteTypes } from \"~/types\";\nimport { Context } from \"~/Context\";\nimport WebinyError from \"@webiny/error\";\nimport { RoutePlugin } from \"./plugins/RoutePlugin\";\nimport { createHandlerClient } from \"@webiny/handler-client\";\nimport fastifyCookies from \"@fastify/cookie\";\nimport { middleware } from \"~/middleware\";\nimport { ContextPlugin } from \"@webiny/api\";\nimport { BeforeHandlerPlugin } from \"./plugins/BeforeHandlerPlugin\";\nimport { HandlerResultPlugin } from \"./plugins/HandlerResultPlugin\";\nimport { HandlerErrorPlugin } from \"./plugins/HandlerErrorPlugin\";\n\nconst DEFAULT_HEADERS: Record<string, string> = {\n \"Cache-Control\": \"no-store\",\n \"Content-Type\": \"application/json; charset=utf-8\",\n \"Access-Control-Allow-Origin\": \"*\",\n \"Access-Control-Allow-Headers\": \"*\",\n \"Access-Control-Allow-Methods\": \"OPTIONS,POST,GET,DELETE,PUT,PATCH\",\n ...getWebinyVersionHeaders()\n};\n\nconst getDefaultHeaders = (routes: DefinedContextRoutes): Record<string, string> => {\n /**\n * If we are accepting all headers, just output that one.\n */\n const keys = Object.keys(routes);\n const all = keys.every(key => routes[key as RouteTypes].length > 0);\n if (all) {\n return {\n ...DEFAULT_HEADERS,\n \"Access-Control-Allow-Methods\": \"*\"\n };\n }\n return {\n ...DEFAULT_HEADERS,\n \"Access-Control-Allow-Methods\": keys\n .filter(key => {\n const type = key as unknown as RouteTypes;\n if (!routes[type] || Array.isArray(routes[type]) === false) {\n return false;\n }\n return routes[type].length > 0;\n })\n .sort()\n .join(\",\")\n };\n};\n\nconst OPTIONS_HEADERS: Record<string, string> = {\n \"Access-Control-Max-Age\": \"86400\",\n \"Cache-Control\": \"public, max-age=86400\"\n};\n\nexport interface CreateHandlerParams {\n plugins: PluginCollection;\n options?: ServerOptions;\n}\n\nexport const createHandler = (params: CreateHandlerParams) => {\n const definedRoutes: ContextRoutes[\"defined\"] = {\n POST: [],\n GET: [],\n OPTIONS: [],\n DELETE: [],\n PATCH: [],\n PUT: [],\n HEAD: []\n };\n\n const throwOnDefinedRoute = (\n type: RouteTypes | \"ALL\",\n path: string,\n options?: RouteMethodOptions\n ): void => {\n if (type === \"ALL\") {\n const all = Object.keys(definedRoutes).some(key => {\n const routes = definedRoutes[key as RouteTypes];\n return routes.includes(path);\n });\n if (!all) {\n return;\n }\n throw new WebinyError(\n `You cannot override a route with onAll() method, please remove unnecessary route from the system.`,\n \"OVERRIDE_ROUTE_ERROR\",\n {\n type,\n path\n }\n );\n } else if (definedRoutes[type].includes(path) === false) {\n return;\n } else if (options?.override === true) {\n return;\n }\n throw new WebinyError(\n `When you are trying to override existing route, you must send \"override\" parameter when adding that route.`,\n \"OVERRIDE_ROUTE_ERROR\",\n {\n type,\n path\n }\n );\n };\n\n const addDefinedRoute = (inputType: RouteTypes, path: string): void => {\n const type = (inputType as string).toUpperCase() as RouteTypes;\n if (!definedRoutes[type]) {\n return;\n } else if (definedRoutes[type].includes(path)) {\n return;\n }\n definedRoutes[type].push(path);\n };\n /**\n * We must attach the server to our internal context if we want to have it accessible.\n */\n const app = fastify({\n ...(params.options || {})\n });\n /**\n * We need to register routes in our system so we can output headers later on and dissallow overriding routes.\n */\n app.addHook(\"onRoute\", route => {\n const method = route.method;\n if (Array.isArray(method)) {\n for (const m of method) {\n addDefinedRoute(m, route.path);\n }\n return;\n }\n addDefinedRoute(method, route.path);\n });\n /**\n *\n */\n app.register(fastifyCookies, {\n parseOptions: {} // options for parsing cookies\n });\n /**\n * Route helpers - mostly for users.\n */\n const routes: ContextRoutes = {\n defined: definedRoutes,\n onPost: (path, handler, options) => {\n throwOnDefinedRoute(\"POST\", path, options);\n app.post(path, handler);\n },\n onGet: (path, handler, options) => {\n throwOnDefinedRoute(\"GET\", path, options);\n app.get(path, handler);\n },\n onOptions: (path, handler, options) => {\n throwOnDefinedRoute(\"OPTIONS\", path, options);\n app.options(path, handler);\n },\n onDelete: (path, handler, options) => {\n throwOnDefinedRoute(\"DELETE\", path, options);\n app.delete(path, handler);\n },\n onPatch: (path, handler, options) => {\n throwOnDefinedRoute(\"PATCH\", path, options);\n app.patch(path, handler);\n },\n onPut: (path, handler, options) => {\n throwOnDefinedRoute(\"PUT\", path, options);\n app.put(path, handler);\n },\n onAll: (path, handler, options) => {\n throwOnDefinedRoute(\"ALL\", path, options);\n app.all(path, handler);\n },\n onHead: (path, handler, options) => {\n throwOnDefinedRoute(\"HEAD\", path, options);\n app.head(path, handler);\n }\n };\n const context = new Context({\n plugins: [\n /**\n * We must have handlerClient by default.\n * And it must be one of the first context plugins applied.\n */\n createHandlerClient(),\n ...(params.plugins || [])\n ],\n /**\n * Inserted via webpack on build time.\n */\n WEBINY_VERSION: process.env.WEBINY_VERSION as string,\n server: app,\n routes\n });\n /**\n * We are attaching our custom context to webiny variable on the fastify app so it is accessible everywhere\n */\n app.decorate(\"webiny\", context);\n\n /**\n * We have few types of triggers:\n * * Events - EventPlugin\n * * Routes - RoutePlugin\n *\n * Routes are registered in fastify but events must be handled in package which implements cloud specific methods.\n */\n const routePlugins = app.webiny.plugins.byType<RoutePlugin>(RoutePlugin.type);\n\n /**\n * Add routes to the system.\n */\n for (const plugin of routePlugins) {\n plugin.cb({\n ...app.webiny.routes,\n context: app.webiny\n });\n }\n\n /**\n * On every request we add default headers, which can be changed later.\n * Also, if it is an options request, we skip everything after this hook and output options headers.\n */\n app.addHook(\"onRequest\", async (request, reply) => {\n const defaultHeaders = getDefaultHeaders(definedRoutes);\n reply.headers(defaultHeaders);\n if (request.method !== \"OPTIONS\") {\n return;\n }\n const raw = reply.code(204).hijack().raw;\n const headers = { ...defaultHeaders, ...OPTIONS_HEADERS };\n for (const key in headers) {\n raw.setHeader(key, headers[key]);\n }\n\n raw.end(\"\");\n });\n\n app.addHook(\"preParsing\", async request => {\n app.webiny.request = request;\n const plugins = app.webiny.plugins.byType<ContextPlugin>(ContextPlugin.type);\n for (const plugin of plugins) {\n await plugin.apply(app.webiny);\n }\n });\n /**\n *\n */\n app.addHook(\"preHandler\", async () => {\n const plugins = app.webiny.plugins.byType<BeforeHandlerPlugin>(BeforeHandlerPlugin.type);\n for (const plugin of plugins) {\n await plugin.apply(app.webiny);\n }\n });\n\n /**\n *\n */\n const preSerialization: preSerializationAsyncHookHandler<any> = async (_, __, payload) => {\n const plugins = app.webiny.plugins.byType<HandlerResultPlugin>(HandlerResultPlugin.type);\n for (const plugin of plugins) {\n await plugin.handle(app.webiny, payload);\n }\n return payload;\n };\n\n app.addHook(\"preSerialization\", preSerialization);\n\n app.addHook(\"onError\", async (_, reply, error) => {\n const plugins = app.webiny.plugins.byType<HandlerErrorPlugin>(HandlerErrorPlugin.type);\n // Log error to cloud, as these can be extremely annoying to debug!\n console.log(\"@webiny/handler\");\n console.log(\n JSON.stringify({\n ...(error || {}),\n message: error?.message,\n code: error?.code\n })\n );\n const handler = middleware(\n plugins.map(pl => {\n return (context: Context, error: Error, next: Function) => {\n return pl.handle(context, error, next);\n };\n })\n );\n await handler(app.webiny, error);\n\n return reply\n .headers({\n \"Cache-Control\": \"no-store\"\n })\n .status(500);\n });\n\n return app;\n};\n"],"mappings":";;;;;;;;;;;AACA;;AAIA;;AAEA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;;;;;AAEA,MAAMA,eAAuC;EACzC,iBAAiB,UADwB;EAEzC,gBAAgB,iCAFyB;EAGzC,+BAA+B,GAHU;EAIzC,gCAAgC,GAJS;EAKzC,gCAAgC;AALS,GAMtC,IAAAC,8BAAA,GANsC,CAA7C;;AASA,MAAMC,iBAAiB,GAAIC,MAAD,IAA0D;EAChF;AACJ;AACA;EACI,MAAMC,IAAI,GAAGC,MAAM,CAACD,IAAP,CAAYD,MAAZ,CAAb;EACA,MAAMG,GAAG,GAAGF,IAAI,CAACG,KAAL,CAAWC,GAAG,IAAIL,MAAM,CAACK,GAAD,CAAN,CAA0BC,MAA1B,GAAmC,CAArD,CAAZ;;EACA,IAAIH,GAAJ,EAAS;IACL,uCACON,eADP;MAEI,gCAAgC;IAFpC;EAIH;;EACD,uCACOA,eADP;IAEI,gCAAgCI,IAAI,CAC/BM,MAD2B,CACpBF,GAAG,IAAI;MACX,MAAMG,IAAI,GAAGH,GAAb;;MACA,IAAI,CAACL,MAAM,CAACQ,IAAD,CAAP,IAAiBC,KAAK,CAACC,OAAN,CAAcV,MAAM,CAACQ,IAAD,CAApB,MAAgC,KAArD,EAA4D;QACxD,OAAO,KAAP;MACH;;MACD,OAAOR,MAAM,CAACQ,IAAD,CAAN,CAAaF,MAAb,GAAsB,CAA7B;IACH,CAP2B,EAQ3BK,IAR2B,GAS3BC,IAT2B,CAStB,GATsB;EAFpC;AAaH,CAzBD;;AA2BA,MAAMC,eAAuC,GAAG;EAC5C,0BAA0B,OADkB;EAE5C,iBAAiB;AAF2B,CAAhD;;AAUO,MAAMC,aAAa,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ACE,OAAJ,CAAY,SAAZ,EAAuB,OAAOmD,CAAP,EAAUZ,KAAV,EAAiBiB,KAAjB,KAA2B;IAC9C,MAAM/B,OAAO,GAAG3B,GAAG,CAACmC,MAAJ,CAAWR,OAAX,CAAmBS,MAAnB,CAA8CuB,sCAAA,CAAmBtF,IAAjE,CAAhB,CAD8C,CAE9C;;IACAuF,OAAO,CAACC,GAAR,CAAY,iBAAZ;IACAD,OAAO,CAACC,GAAR,CACIC,IAAI,CAACC,SAAL,iCACQL,KAAK,IAAI,EADjB;MAEIM,OAAO,EAAEN,KAAF,aAAEA,KAAF,uBAAEA,KAAK,CAAEM,OAFpB;MAGInB,IAAI,EAAEa,KAAF,aAAEA,KAAF,uBAAEA,KAAK,CAAEb;IAHjB,GADJ;IAOA,MAAMlC,OAAO,GAAG,IAAAsD,sBAAA,EACZtC,OAAO,CAACuC,GAAR,CAAYC,EAAE,IAAI;MACd,OAAO,CAAC1C,OAAD,EAAmBiC,KAAnB,EAAiCU,IAAjC,KAAoD;QACvD,OAAOD,EAAE,CAACV,MAAH,CAAUhC,OAAV,EAAmBiC,KAAnB,EAA0BU,IAA1B,CAAP;MACH,CAFD;IAGH,CAJD,CADY,CAAhB;IAOA,MAAMzD,OAAO,CAACX,GAAG,CAACmC,MAAL,EAAauB,KAAb,CAAb;IAEA,OAAOjB,KAAK,CACPE,OADE,CACM;MACL,iBAAiB;IADZ,CADN,EAIF0B,MAJE,CAIK,GAJL,CAAP;EAKH,CAzBD;EA2BA,OAAOrE,GAAP;AACH,CA5OM"}
package/index.d.ts CHANGED
@@ -1 +1,8 @@
1
- export { default as createHandler } from "./createHandler";
1
+ export * from "./fastify";
2
+ export * from "@webiny/api/plugins/ContextPlugin";
3
+ export * from "./Context";
4
+ export * from "./plugins/EventPlugin";
5
+ export * from "./plugins/RoutePlugin";
6
+ export * from "./plugins/BeforeHandlerPlugin";
7
+ export * from "./plugins/HandlerErrorPlugin";
8
+ export * from "./plugins/HandlerResultPlugin";
package/index.js CHANGED
@@ -1,15 +1,109 @@
1
1
  "use strict";
2
2
 
3
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
-
5
3
  Object.defineProperty(exports, "__esModule", {
6
4
  value: true
7
5
  });
8
- Object.defineProperty(exports, "createHandler", {
9
- enumerable: true,
10
- get: function () {
11
- return _createHandler.default;
12
- }
6
+
7
+ var _fastify = require("./fastify");
8
+
9
+ Object.keys(_fastify).forEach(function (key) {
10
+ if (key === "default" || key === "__esModule") return;
11
+ if (key in exports && exports[key] === _fastify[key]) return;
12
+ Object.defineProperty(exports, key, {
13
+ enumerable: true,
14
+ get: function () {
15
+ return _fastify[key];
16
+ }
17
+ });
18
+ });
19
+
20
+ var _ContextPlugin = require("@webiny/api/plugins/ContextPlugin");
21
+
22
+ Object.keys(_ContextPlugin).forEach(function (key) {
23
+ if (key === "default" || key === "__esModule") return;
24
+ if (key in exports && exports[key] === _ContextPlugin[key]) return;
25
+ Object.defineProperty(exports, key, {
26
+ enumerable: true,
27
+ get: function () {
28
+ return _ContextPlugin[key];
29
+ }
30
+ });
31
+ });
32
+
33
+ var _Context = require("./Context");
34
+
35
+ Object.keys(_Context).forEach(function (key) {
36
+ if (key === "default" || key === "__esModule") return;
37
+ if (key in exports && exports[key] === _Context[key]) return;
38
+ Object.defineProperty(exports, key, {
39
+ enumerable: true,
40
+ get: function () {
41
+ return _Context[key];
42
+ }
43
+ });
44
+ });
45
+
46
+ var _EventPlugin = require("./plugins/EventPlugin");
47
+
48
+ Object.keys(_EventPlugin).forEach(function (key) {
49
+ if (key === "default" || key === "__esModule") return;
50
+ if (key in exports && exports[key] === _EventPlugin[key]) return;
51
+ Object.defineProperty(exports, key, {
52
+ enumerable: true,
53
+ get: function () {
54
+ return _EventPlugin[key];
55
+ }
56
+ });
57
+ });
58
+
59
+ var _RoutePlugin = require("./plugins/RoutePlugin");
60
+
61
+ Object.keys(_RoutePlugin).forEach(function (key) {
62
+ if (key === "default" || key === "__esModule") return;
63
+ if (key in exports && exports[key] === _RoutePlugin[key]) return;
64
+ Object.defineProperty(exports, key, {
65
+ enumerable: true,
66
+ get: function () {
67
+ return _RoutePlugin[key];
68
+ }
69
+ });
13
70
  });
14
71
 
15
- var _createHandler = _interopRequireDefault(require("./createHandler"));
72
+ var _BeforeHandlerPlugin = require("./plugins/BeforeHandlerPlugin");
73
+
74
+ Object.keys(_BeforeHandlerPlugin).forEach(function (key) {
75
+ if (key === "default" || key === "__esModule") return;
76
+ if (key in exports && exports[key] === _BeforeHandlerPlugin[key]) return;
77
+ Object.defineProperty(exports, key, {
78
+ enumerable: true,
79
+ get: function () {
80
+ return _BeforeHandlerPlugin[key];
81
+ }
82
+ });
83
+ });
84
+
85
+ var _HandlerErrorPlugin = require("./plugins/HandlerErrorPlugin");
86
+
87
+ Object.keys(_HandlerErrorPlugin).forEach(function (key) {
88
+ if (key === "default" || key === "__esModule") return;
89
+ if (key in exports && exports[key] === _HandlerErrorPlugin[key]) return;
90
+ Object.defineProperty(exports, key, {
91
+ enumerable: true,
92
+ get: function () {
93
+ return _HandlerErrorPlugin[key];
94
+ }
95
+ });
96
+ });
97
+
98
+ var _HandlerResultPlugin = require("./plugins/HandlerResultPlugin");
99
+
100
+ Object.keys(_HandlerResultPlugin).forEach(function (key) {
101
+ if (key === "default" || key === "__esModule") return;
102
+ if (key in exports && exports[key] === _HandlerResultPlugin[key]) return;
103
+ Object.defineProperty(exports, key, {
104
+ enumerable: true,
105
+ get: function () {
106
+ return _HandlerResultPlugin[key];
107
+ }
108
+ });
109
+ });
package/index.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"names":[],"sources":["index.ts"],"sourcesContent":["export * from \"~/fastify\";\nexport * from \"@webiny/api/plugins/ContextPlugin\";\nexport * from \"~/Context\";\nexport * from \"~/plugins/EventPlugin\";\nexport * from \"~/plugins/RoutePlugin\";\nexport * from \"~/plugins/BeforeHandlerPlugin\";\nexport * from \"~/plugins/HandlerErrorPlugin\";\nexport * from \"~/plugins/HandlerResultPlugin\";\n"],"mappings":";;;;;;AAAA;;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;;AACA;;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;;AACA;;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;;AACA;;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;;AACA;;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;;AACA;;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;;AACA;;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;;AACA;;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA"}
package/middleware.d.ts CHANGED
@@ -1,5 +1,4 @@
1
- declare const _default: (functions?: Array<Function>) => Function;
2
1
  /**
3
2
  * Compose a single middleware from the array of middleware functions
4
3
  */
5
- export default _default;
4
+ export declare const middleware: (functions?: Function[]) => Function;
package/middleware.js CHANGED
@@ -3,12 +3,12 @@
3
3
  Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
- exports.default = void 0;
6
+ exports.middleware = void 0;
7
7
 
8
8
  /**
9
9
  * Compose a single middleware from the array of middleware functions
10
10
  */
11
- var _default = (functions = []) => {
11
+ const middleware = (functions = []) => {
12
12
  return (...args) => {
13
13
  if (!functions.length) {
14
14
  return Promise.resolve();
@@ -48,4 +48,4 @@ var _default = (functions = []) => {
48
48
  };
49
49
  };
50
50
 
51
- exports.default = _default;
51
+ exports.middleware = middleware;
@@ -0,0 +1 @@
1
+ {"version":3,"names":["middleware","functions","args","length","Promise","resolve","chain","parentResolve","parentReject","next","fn","shift","reject","result","e","then","catch"],"sources":["middleware.ts"],"sourcesContent":["/**\n * Compose a single middleware from the array of middleware functions\n */\nexport const middleware = (functions: Function[] = []): Function => {\n return (...args: string[]): Promise<any> => {\n if (!functions.length) {\n return Promise.resolve();\n }\n\n // Create a clone of function chain to prevent modifying the original array with `shift()`\n const chain = [...functions];\n return new Promise((parentResolve: any, parentReject) => {\n const next = async (): Promise<any> => {\n const fn = chain.shift();\n if (!fn) {\n return Promise.resolve();\n }\n\n return new Promise(async (resolve, reject) => {\n try {\n const result = await fn(...args, resolve);\n if (typeof result !== \"undefined\") {\n return parentResolve(result);\n }\n } catch (e) {\n reject(e);\n }\n })\n .then(() => {\n return next();\n })\n .then(() => {\n parentResolve(...args);\n })\n .catch(e => {\n parentReject(e);\n });\n };\n\n return next();\n });\n };\n};\n"],"mappings":";;;;;;;AAAA;AACA;AACA;AACO,MAAMA,UAAU,GAAG,CAACC,SAAqB,GAAG,EAAzB,KAA0C;EAChE,OAAO,CAAC,GAAGC,IAAJ,KAAqC;IACxC,IAAI,CAACD,SAAS,CAACE,MAAf,EAAuB;MACnB,OAAOC,OAAO,CAACC,OAAR,EAAP;IACH,CAHuC,CAKxC;;;IACA,MAAMC,KAAK,GAAG,CAAC,GAAGL,SAAJ,CAAd;IACA,OAAO,IAAIG,OAAJ,CAAY,CAACG,aAAD,EAAqBC,YAArB,KAAsC;MACrD,MAAMC,IAAI,GAAG,YAA0B;QACnC,MAAMC,EAAE,GAAGJ,KAAK,CAACK,KAAN,EAAX;;QACA,IAAI,CAACD,EAAL,EAAS;UACL,OAAON,OAAO,CAACC,OAAR,EAAP;QACH;;QAED,OAAO,IAAID,OAAJ,CAAY,OAAOC,OAAP,EAAgBO,MAAhB,KAA2B;UAC1C,IAAI;YACA,MAAMC,MAAM,GAAG,MAAMH,EAAE,CAAC,GAAGR,IAAJ,EAAUG,OAAV,CAAvB;;YACA,IAAI,OAAOQ,MAAP,KAAkB,WAAtB,EAAmC;cAC/B,OAAON,aAAa,CAACM,MAAD,CAApB;YACH;UACJ,CALD,CAKE,OAAOC,CAAP,EAAU;YACRF,MAAM,CAACE,CAAD,CAAN;UACH;QACJ,CATM,EAUFC,IAVE,CAUG,MAAM;UACR,OAAON,IAAI,EAAX;QACH,CAZE,EAaFM,IAbE,CAaG,MAAM;UACRR,aAAa,CAAC,GAAGL,IAAJ,CAAb;QACH,CAfE,EAgBFc,KAhBE,CAgBIF,CAAC,IAAI;UACRN,YAAY,CAACM,CAAD,CAAZ;QACH,CAlBE,CAAP;MAmBH,CAzBD;;MA2BA,OAAOL,IAAI,EAAX;IACH,CA7BM,CAAP;EA8BH,CArCD;AAsCH,CAvCM"}
package/package.json CHANGED
@@ -1,30 +1,38 @@
1
1
  {
2
2
  "name": "@webiny/handler",
3
- "version": "0.0.0-mt-3",
3
+ "version": "0.0.0-unstable.8c4d9f045a",
4
4
  "main": "index.js",
5
- "license": "MIT",
6
5
  "repository": {
7
6
  "type": "git",
8
7
  "url": "https://github.com/webiny/webiny-js.git"
9
8
  },
10
- "description": "A pluginable function for the cloud.",
9
+ "description": "Our small wrapper around fastify to ease handling of http requests for the system.",
11
10
  "contributors": [
12
- "Pavel Denisjuk <pavel@webiny.com>",
13
- "Sven Al Hamad <sven@webiny.com>",
14
- "Adrian Smijulj <adrian@webiny.com>"
11
+ "Bruno Zorić <bruno@webiny.com>"
15
12
  ],
13
+ "license": "MIT",
16
14
  "dependencies": {
17
- "@babel/runtime": "7.15.4",
18
- "@webiny/plugins": "0.0.0-mt-3"
15
+ "@babel/runtime": "7.18.9",
16
+ "@fastify/cookie": "7.3.1",
17
+ "@webiny/api": "0.0.0-unstable.8c4d9f045a",
18
+ "@webiny/error": "0.0.0-unstable.8c4d9f045a",
19
+ "@webiny/handler-client": "0.0.0-unstable.8c4d9f045a",
20
+ "@webiny/plugins": "0.0.0-unstable.8c4d9f045a",
21
+ "@webiny/utils": "0.0.0-unstable.8c4d9f045a",
22
+ "fastify": "4.3.0"
19
23
  },
20
24
  "devDependencies": {
21
- "@babel/cli": "^7.5.5",
22
- "@babel/core": "^7.5.5",
23
- "@babel/preset-env": "^7.5.5",
24
- "@webiny/cli": "^0.0.0-mt-3",
25
- "@webiny/project-utils": "^0.0.0-mt-3",
25
+ "@babel/cli": "^7.16.0",
26
+ "@babel/core": "^7.16.0",
27
+ "@babel/preset-env": "^7.16.4",
28
+ "@babel/preset-typescript": "^7.16.0",
29
+ "@webiny/cli": "^0.0.0-unstable.8c4d9f045a",
30
+ "@webiny/project-utils": "^0.0.0-unstable.8c4d9f045a",
31
+ "babel-plugin-lodash": "^3.3.4",
32
+ "merge": "^1.2.1",
26
33
  "rimraf": "^3.0.2",
27
- "typescript": "^4.1.3"
34
+ "ttypescript": "^1.5.13",
35
+ "typescript": "4.7.4"
28
36
  },
29
37
  "publishConfig": {
30
38
  "access": "public",
@@ -34,5 +42,5 @@
34
42
  "build": "yarn webiny run build",
35
43
  "watch": "yarn webiny run watch"
36
44
  },
37
- "gitHead": "ebea815be2be99404591cba465cc1fe88355bd48"
45
+ "gitHead": "5f904a53a5956269bd80a9c084cc04f92b824d36"
38
46
  }
@@ -1,11 +1,12 @@
1
1
  import { Plugin } from "@webiny/plugins";
2
- interface Callable<TContext> {
3
- (context: TContext): void | Promise<void>;
2
+ import { Context } from "../types";
3
+ export interface BeforeHandlerCallable<T extends Context = Context> {
4
+ (context: T): void | Promise<void>;
4
5
  }
5
- export declare class BeforeHandlerPlugin<TContext> extends Plugin {
6
- static readonly type = "before-handler";
6
+ export declare class BeforeHandlerPlugin<T extends Context = Context> extends Plugin {
7
+ static readonly type: string;
7
8
  private readonly _callable;
8
- constructor(callable?: Callable<TContext>);
9
- apply(context: TContext): void | Promise<void>;
9
+ constructor(callable: BeforeHandlerCallable<T>);
10
+ apply(context: T): Promise<void>;
10
11
  }
11
- export {};
12
+ export declare const createBeforeHandlerPlugin: <T extends Context = Context>(callable: BeforeHandlerCallable<T>) => BeforeHandlerPlugin<T>;
@@ -5,7 +5,7 @@ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefau
5
5
  Object.defineProperty(exports, "__esModule", {
6
6
  value: true
7
7
  });
8
- exports.BeforeHandlerPlugin = void 0;
8
+ exports.createBeforeHandlerPlugin = exports.BeforeHandlerPlugin = void 0;
9
9
 
10
10
  var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
11
11
 
@@ -18,7 +18,7 @@ class BeforeHandlerPlugin extends _plugins.Plugin {
18
18
  this._callable = callable;
19
19
  }
20
20
 
21
- apply(context) {
21
+ async apply(context) {
22
22
  if (typeof this._callable !== "function") {
23
23
  throw Error(`Missing callable in BeforeHandlerPlugin! Either pass a callable to plugin constructor or extend the plugin and override the "apply" method.`);
24
24
  }
@@ -29,4 +29,10 @@ class BeforeHandlerPlugin extends _plugins.Plugin {
29
29
  }
30
30
 
31
31
  exports.BeforeHandlerPlugin = BeforeHandlerPlugin;
32
- (0, _defineProperty2.default)(BeforeHandlerPlugin, "type", "before-handler");
32
+ (0, _defineProperty2.default)(BeforeHandlerPlugin, "type", "before-handler");
33
+
34
+ const createBeforeHandlerPlugin = callable => {
35
+ return new BeforeHandlerPlugin(callable);
36
+ };
37
+
38
+ exports.createBeforeHandlerPlugin = createBeforeHandlerPlugin;
@@ -0,0 +1 @@
1
+ {"version":3,"names":["BeforeHandlerPlugin","Plugin","constructor","callable","_callable","apply","context","Error","createBeforeHandlerPlugin"],"sources":["BeforeHandlerPlugin.ts"],"sourcesContent":["import { Plugin } from \"@webiny/plugins\";\nimport { Context } from \"~/types\";\n\nexport interface BeforeHandlerCallable<T extends Context = Context> {\n (context: T): void | Promise<void>;\n}\n\nexport class BeforeHandlerPlugin<T extends Context = Context> extends Plugin {\n public static override readonly type: string = \"before-handler\";\n private readonly _callable: BeforeHandlerCallable<T>;\n\n constructor(callable: BeforeHandlerCallable<T>) {\n super();\n this._callable = callable;\n }\n\n public async apply(context: T): Promise<void> {\n if (typeof this._callable !== \"function\") {\n throw Error(\n `Missing callable in BeforeHandlerPlugin! Either pass a callable to plugin constructor or extend the plugin and override the \"apply\" method.`\n );\n }\n\n return this._callable(context);\n }\n}\n\nexport const createBeforeHandlerPlugin = <T extends Context = Context>(\n callable: BeforeHandlerCallable<T>\n): BeforeHandlerPlugin<T> => {\n return new BeforeHandlerPlugin<T>(callable);\n};\n"],"mappings":";;;;;;;;;;;AAAA;;AAOO,MAAMA,mBAAN,SAA+DC,eAA/D,CAAsE;EAIzEC,WAAW,CAACC,QAAD,EAAqC;IAC5C;IAD4C;IAE5C,KAAKC,SAAL,GAAiBD,QAAjB;EACH;;EAEiB,MAALE,KAAK,CAACC,OAAD,EAA4B;IAC1C,IAAI,OAAO,KAAKF,SAAZ,KAA0B,UAA9B,EAA0C;MACtC,MAAMG,KAAK,CACN,6IADM,CAAX;IAGH;;IAED,OAAO,KAAKH,SAAL,CAAeE,OAAf,CAAP;EACH;;AAjBwE;;;8BAAhEN,mB,UACsC,gB;;AAmB5C,MAAMQ,yBAAyB,GAClCL,QADqC,IAEZ;EACzB,OAAO,IAAIH,mBAAJ,CAA2BG,QAA3B,CAAP;AACH,CAJM"}
@@ -0,0 +1,25 @@
1
+ /**
2
+ * EventPlugin must be handled in the package which implements fastify for certain cloud.
3
+ * There is no standard input for AWS Lambda, Google Cloud Functions and MS Azure Functions so we let that
4
+ * to be sorted out in the implementation package.
5
+ *
6
+ * Note that only one EventPlugin can be defined per fastify initialisation.
7
+ * If more is needed, check ~/fastify.ts and implement that possibility.
8
+ */
9
+ import { Plugin } from "@webiny/plugins/Plugin";
10
+ import { Request, Context as BaseContext, Reply } from "../types";
11
+ export interface EventPluginCallableParams<Payload, Context extends BaseContext> {
12
+ context: Context;
13
+ payload: Payload;
14
+ request: Request;
15
+ reply: Reply;
16
+ }
17
+ export interface EventPluginCallable<Payload, Context extends BaseContext, Response> {
18
+ (params: EventPluginCallableParams<Payload, Context>): Promise<Response | Reply>;
19
+ }
20
+ export declare class EventPlugin<Payload = any, Context extends BaseContext = BaseContext, Response = any> extends Plugin {
21
+ static type: string;
22
+ readonly cb: EventPluginCallable<Payload, Context, Response>;
23
+ constructor(cb: EventPluginCallable<Payload, Context, Response>);
24
+ }
25
+ export declare const createEvent: <Payload = any, Context extends BaseContext = BaseContext, Response_1 = any>(cb: EventPluginCallable<Payload, Context, Response_1>) => EventPlugin<Payload, Context, Response_1>;
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+
5
+ Object.defineProperty(exports, "__esModule", {
6
+ value: true
7
+ });
8
+ exports.createEvent = exports.EventPlugin = void 0;
9
+
10
+ var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
11
+
12
+ var _Plugin = require("@webiny/plugins/Plugin");
13
+
14
+ /**
15
+ * EventPlugin must be handled in the package which implements fastify for certain cloud.
16
+ * There is no standard input for AWS Lambda, Google Cloud Functions and MS Azure Functions so we let that
17
+ * to be sorted out in the implementation package.
18
+ *
19
+ * Note that only one EventPlugin can be defined per fastify initialisation.
20
+ * If more is needed, check ~/fastify.ts and implement that possibility.
21
+ */
22
+ class EventPlugin extends _Plugin.Plugin {
23
+ constructor(cb) {
24
+ super();
25
+ (0, _defineProperty2.default)(this, "cb", void 0);
26
+ this.cb = cb;
27
+ }
28
+
29
+ }
30
+
31
+ exports.EventPlugin = EventPlugin;
32
+ (0, _defineProperty2.default)(EventPlugin, "type", "handler.fastify.event");
33
+
34
+ const createEvent = cb => {
35
+ return new EventPlugin(cb);
36
+ };
37
+
38
+ exports.createEvent = createEvent;
@@ -0,0 +1 @@
1
+ {"version":3,"names":["EventPlugin","Plugin","constructor","cb","createEvent"],"sources":["EventPlugin.ts"],"sourcesContent":["/**\n * EventPlugin must be handled in the package which implements fastify for certain cloud.\n * There is no standard input for AWS Lambda, Google Cloud Functions and MS Azure Functions so we let that\n * to be sorted out in the implementation package.\n *\n * Note that only one EventPlugin can be defined per fastify initialisation.\n * If more is needed, check ~/fastify.ts and implement that possibility.\n */\nimport { Plugin } from \"@webiny/plugins/Plugin\";\nimport { Request, Context as BaseContext, Reply } from \"~/types\";\n\nexport interface EventPluginCallableParams<Payload, Context extends BaseContext> {\n context: Context;\n payload: Payload;\n request: Request;\n reply: Reply;\n}\n\nexport interface EventPluginCallable<Payload, Context extends BaseContext, Response> {\n (params: EventPluginCallableParams<Payload, Context>): Promise<Response | Reply>;\n}\n\nexport class EventPlugin<\n Payload = any,\n Context extends BaseContext = BaseContext,\n Response = any\n> extends Plugin {\n public static override type = \"handler.fastify.event\";\n\n public readonly cb: EventPluginCallable<Payload, Context, Response>;\n\n public constructor(cb: EventPluginCallable<Payload, Context, Response>) {\n super();\n this.cb = cb;\n }\n}\n\nexport const createEvent = <\n Payload = any,\n Context extends BaseContext = BaseContext,\n Response = any\n>(\n cb: EventPluginCallable<Payload, Context, Response>\n) => {\n return new EventPlugin<Payload, Context, Response>(cb);\n};\n"],"mappings":";;;;;;;;;;;AAQA;;AARA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAeO,MAAMA,WAAN,SAIGC,cAJH,CAIU;EAKNC,WAAW,CAACC,EAAD,EAAsD;IACpE;IADoE;IAEpE,KAAKA,EAAL,GAAUA,EAAV;EACH;;AARY;;;8BAJJH,W,UAKqB,uB;;AAU3B,MAAMI,WAAW,GAKpBD,EALuB,IAMtB;EACD,OAAO,IAAIH,WAAJ,CAA4CG,EAA5C,CAAP;AACH,CARM"}
@@ -0,0 +1,12 @@
1
+ import { Plugin } from "@webiny/plugins";
2
+ import { Context } from "../types";
3
+ export interface HandlerErrorCallable<T extends Context = Context> {
4
+ (context: T, error: Error, next: Function): Promise<any>;
5
+ }
6
+ export declare class HandlerErrorPlugin<T extends Context = Context> extends Plugin {
7
+ static readonly type: string;
8
+ private readonly _callable;
9
+ constructor(callable: HandlerErrorCallable<T>);
10
+ handle(context: T, error: Error, next: Function): Promise<any>;
11
+ }
12
+ export declare const createHandlerErrorPlugin: <T extends Context = Context>(callable: HandlerErrorCallable<T>) => HandlerErrorPlugin<T>;
@@ -0,0 +1,34 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+
5
+ Object.defineProperty(exports, "__esModule", {
6
+ value: true
7
+ });
8
+ exports.createHandlerErrorPlugin = exports.HandlerErrorPlugin = void 0;
9
+
10
+ var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
11
+
12
+ var _plugins = require("@webiny/plugins");
13
+
14
+ class HandlerErrorPlugin extends _plugins.Plugin {
15
+ constructor(callable) {
16
+ super();
17
+ (0, _defineProperty2.default)(this, "_callable", void 0);
18
+ this._callable = callable;
19
+ }
20
+
21
+ async handle(context, error, next) {
22
+ return this._callable(context, error, next);
23
+ }
24
+
25
+ }
26
+
27
+ exports.HandlerErrorPlugin = HandlerErrorPlugin;
28
+ (0, _defineProperty2.default)(HandlerErrorPlugin, "type", "handler-error");
29
+
30
+ const createHandlerErrorPlugin = callable => {
31
+ return new HandlerErrorPlugin(callable);
32
+ };
33
+
34
+ exports.createHandlerErrorPlugin = createHandlerErrorPlugin;
@@ -0,0 +1 @@
1
+ {"version":3,"names":["HandlerErrorPlugin","Plugin","constructor","callable","_callable","handle","context","error","next","createHandlerErrorPlugin"],"sources":["HandlerErrorPlugin.ts"],"sourcesContent":["import { Plugin } from \"@webiny/plugins\";\nimport { Context } from \"~/types\";\n\nexport interface HandlerErrorCallable<T extends Context = Context> {\n (context: T, error: Error, next: Function): Promise<any>;\n}\n\nexport class HandlerErrorPlugin<T extends Context = Context> extends Plugin {\n public static override readonly type: string = \"handler-error\";\n\n private readonly _callable: HandlerErrorCallable<T>;\n\n public constructor(callable: HandlerErrorCallable<T>) {\n super();\n this._callable = callable;\n }\n\n public async handle(context: T, error: Error, next: Function): Promise<any> {\n return this._callable(context, error, next);\n }\n}\n\nexport const createHandlerErrorPlugin = <T extends Context = Context>(\n callable: HandlerErrorCallable<T>\n): HandlerErrorPlugin<T> => {\n return new HandlerErrorPlugin<T>(callable);\n};\n"],"mappings":";;;;;;;;;;;AAAA;;AAOO,MAAMA,kBAAN,SAA8DC,eAA9D,CAAqE;EAKjEC,WAAW,CAACC,QAAD,EAAoC;IAClD;IADkD;IAElD,KAAKC,SAAL,GAAiBD,QAAjB;EACH;;EAEkB,MAANE,MAAM,CAACC,OAAD,EAAaC,KAAb,EAA2BC,IAA3B,EAAyD;IACxE,OAAO,KAAKJ,SAAL,CAAeE,OAAf,EAAwBC,KAAxB,EAA+BC,IAA/B,CAAP;EACH;;AAZuE;;;8BAA/DR,kB,UACsC,e;;AAc5C,MAAMS,wBAAwB,GACjCN,QADoC,IAEZ;EACxB,OAAO,IAAIH,kBAAJ,CAA0BG,QAA1B,CAAP;AACH,CAJM"}
@@ -0,0 +1,12 @@
1
+ import { Plugin } from "@webiny/plugins";
2
+ import { Context } from "../types";
3
+ export interface HandlerResultCallable<T extends Context = Context> {
4
+ (context: T, result: any): Promise<any>;
5
+ }
6
+ export declare class HandlerResultPlugin<T extends Context = Context> extends Plugin {
7
+ static readonly type: string;
8
+ private readonly _callable;
9
+ constructor(callable: HandlerResultCallable<T>);
10
+ handle(context: T, result: any): Promise<any>;
11
+ }
12
+ export declare const createHandlerResultPlugin: <T extends Context = Context>(callable: HandlerResultCallable<T>) => HandlerResultPlugin<T>;
@@ -0,0 +1,34 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+
5
+ Object.defineProperty(exports, "__esModule", {
6
+ value: true
7
+ });
8
+ exports.createHandlerResultPlugin = exports.HandlerResultPlugin = void 0;
9
+
10
+ var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
11
+
12
+ var _plugins = require("@webiny/plugins");
13
+
14
+ class HandlerResultPlugin extends _plugins.Plugin {
15
+ constructor(callable) {
16
+ super();
17
+ (0, _defineProperty2.default)(this, "_callable", void 0);
18
+ this._callable = callable;
19
+ }
20
+
21
+ async handle(context, result) {
22
+ return this._callable(context, result);
23
+ }
24
+
25
+ }
26
+
27
+ exports.HandlerResultPlugin = HandlerResultPlugin;
28
+ (0, _defineProperty2.default)(HandlerResultPlugin, "type", "handler-result");
29
+
30
+ const createHandlerResultPlugin = callable => {
31
+ return new HandlerResultPlugin(callable);
32
+ };
33
+
34
+ exports.createHandlerResultPlugin = createHandlerResultPlugin;
@@ -0,0 +1 @@
1
+ {"version":3,"names":["HandlerResultPlugin","Plugin","constructor","callable","_callable","handle","context","result","createHandlerResultPlugin"],"sources":["HandlerResultPlugin.ts"],"sourcesContent":["import { Plugin } from \"@webiny/plugins\";\nimport { Context } from \"~/types\";\n\nexport interface HandlerResultCallable<T extends Context = Context> {\n (context: T, result: any): Promise<any>;\n}\n\nexport class HandlerResultPlugin<T extends Context = Context> extends Plugin {\n public static override readonly type: string = \"handler-result\";\n\n private readonly _callable: HandlerResultCallable<T>;\n\n public constructor(callable: HandlerResultCallable<T>) {\n super();\n this._callable = callable;\n }\n\n public async handle(context: T, result: any): Promise<any> {\n return this._callable(context, result);\n }\n}\n\nexport const createHandlerResultPlugin = <T extends Context = Context>(\n callable: HandlerResultCallable<T>\n): HandlerResultPlugin<T> => {\n return new HandlerResultPlugin<T>(callable);\n};\n"],"mappings":";;;;;;;;;;;AAAA;;AAOO,MAAMA,mBAAN,SAA+DC,eAA/D,CAAsE;EAKlEC,WAAW,CAACC,QAAD,EAAqC;IACnD;IADmD;IAEnD,KAAKC,SAAL,GAAiBD,QAAjB;EACH;;EAEkB,MAANE,MAAM,CAACC,OAAD,EAAaC,MAAb,EAAwC;IACvD,OAAO,KAAKH,SAAL,CAAeE,OAAf,EAAwBC,MAAxB,CAAP;EACH;;AAZwE;;;8BAAhEP,mB,UACsC,gB;;AAc5C,MAAMQ,yBAAyB,GAClCL,QADqC,IAEZ;EACzB,OAAO,IAAIH,mBAAJ,CAA2BG,QAA3B,CAAP;AACH,CAJM"}
@@ -0,0 +1,23 @@
1
+ import { Plugin } from "@webiny/plugins/Plugin";
2
+ import { Context, RouteMethod } from "../types";
3
+ interface RoutePluginCbParams<T extends Context> {
4
+ context: T;
5
+ onGet: RouteMethod;
6
+ onPost: RouteMethod;
7
+ onPut: RouteMethod;
8
+ onPatch: RouteMethod;
9
+ onDelete: RouteMethod;
10
+ onOptions: RouteMethod;
11
+ onAll: RouteMethod;
12
+ onHead: RouteMethod;
13
+ }
14
+ export interface RoutePluginCb<T extends Context> {
15
+ (params: RoutePluginCbParams<T>): void;
16
+ }
17
+ export declare class RoutePlugin<T extends Context = Context> extends Plugin {
18
+ static readonly type: string;
19
+ readonly cb: RoutePluginCb<T>;
20
+ constructor(cb: RoutePluginCb<T>);
21
+ }
22
+ export declare const createRoute: <T extends Context = Context>(cb: RoutePluginCb<T>) => RoutePlugin<T>;
23
+ export {};
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+
5
+ Object.defineProperty(exports, "__esModule", {
6
+ value: true
7
+ });
8
+ exports.createRoute = exports.RoutePlugin = void 0;
9
+
10
+ var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
11
+
12
+ var _Plugin = require("@webiny/plugins/Plugin");
13
+
14
+ class RoutePlugin extends _Plugin.Plugin {
15
+ constructor(cb) {
16
+ super();
17
+ (0, _defineProperty2.default)(this, "cb", void 0);
18
+ this.cb = cb;
19
+ }
20
+
21
+ }
22
+
23
+ exports.RoutePlugin = RoutePlugin;
24
+ (0, _defineProperty2.default)(RoutePlugin, "type", "handler.fastify.route");
25
+
26
+ const createRoute = cb => {
27
+ return new RoutePlugin(cb);
28
+ };
29
+
30
+ exports.createRoute = createRoute;
@@ -0,0 +1 @@
1
+ {"version":3,"names":["RoutePlugin","Plugin","constructor","cb","createRoute"],"sources":["RoutePlugin.ts"],"sourcesContent":["import { Plugin } from \"@webiny/plugins/Plugin\";\nimport { Context, RouteMethod } from \"~/types\";\n\ninterface RoutePluginCbParams<T extends Context> {\n context: T;\n onGet: RouteMethod;\n onPost: RouteMethod;\n onPut: RouteMethod;\n onPatch: RouteMethod;\n onDelete: RouteMethod;\n onOptions: RouteMethod;\n onAll: RouteMethod;\n onHead: RouteMethod;\n}\nexport interface RoutePluginCb<T extends Context> {\n (params: RoutePluginCbParams<T>): void;\n}\n\nexport class RoutePlugin<T extends Context = Context> extends Plugin {\n public static override readonly type: string = \"handler.fastify.route\";\n\n public readonly cb: RoutePluginCb<T>;\n\n public constructor(cb: RoutePluginCb<T>) {\n super();\n this.cb = cb;\n }\n}\n\nexport const createRoute = <T extends Context = Context>(cb: RoutePluginCb<T>): RoutePlugin<T> => {\n return new RoutePlugin<T>(cb);\n};\n"],"mappings":";;;;;;;;;;;AAAA;;AAkBO,MAAMA,WAAN,SAAuDC,cAAvD,CAA8D;EAK1DC,WAAW,CAACC,EAAD,EAAuB;IACrC;IADqC;IAErC,KAAKA,EAAL,GAAUA,EAAV;EACH;;AARgE;;;8BAAxDH,W,UACsC,uB;;AAU5C,MAAMI,WAAW,GAAiCD,EAA9B,IAAuE;EAC9F,OAAO,IAAIH,WAAJ,CAAmBG,EAAnB,CAAP;AACH,CAFM"}
package/types.d.ts CHANGED
@@ -1,37 +1,46 @@
1
- import { Plugin, PluginsContainer } from "@webiny/plugins/types";
2
- export declare type HandlerArgs = any[];
3
- export interface HandlerContext {
4
- plugins: PluginsContainer;
5
- args: HandlerArgs;
6
- readonly WEBINY_VERSION: string;
1
+ import { FastifyInstance, FastifyRequest, FastifyReply, HTTPMethods, RouteHandlerMethod } from "fastify";
2
+ export { FastifyInstance, HTTPMethods } from "fastify";
3
+ import { ClientContext } from "@webiny/handler-client/types";
4
+ export declare type RouteTypes = HTTPMethods;
5
+ export interface RouteMethodOptions {
6
+ override?: boolean;
7
7
  }
8
- export interface ContextInterface {
9
- plugins: PluginsContainer;
10
- args: HandlerArgs;
11
- readonly WEBINY_VERSION: string;
8
+ export declare type RouteMethodPath = `/${string}` | "*";
9
+ export interface RouteMethod {
10
+ (path: RouteMethodPath, handler: RouteHandlerMethod, options?: RouteMethodOptions): void;
12
11
  }
13
- export declare type Context<C0 = Record<string, any>, C1 = Record<string, any>, C2 = Record<string, any>, C3 = Record<string, any>, C4 = Record<string, any>, C5 = Record<string, any>, C6 = Record<string, any>, C7 = Record<string, any>, C8 = Record<string, any>, C9 = Record<string, any>> = {
14
- plugins: PluginsContainer;
15
- args: HandlerArgs;
16
- readonly WEBINY_VERSION: string;
17
- } & C0 & C1 & C2 & C3 & C4 & C5 & C6 & C7 & C8 & C9;
18
- export interface BeforeHandlerPlugin<T extends ContextInterface = ContextInterface> extends Plugin {
19
- type: "before-handler";
20
- apply: (context: T) => Promise<void>;
12
+ export declare type Request = FastifyRequest;
13
+ export declare type Reply = FastifyReply;
14
+ export declare type DefinedContextRoutes = Record<RouteTypes, string[]>;
15
+ export interface ContextRoutes {
16
+ defined: DefinedContextRoutes;
17
+ onGet: RouteMethod;
18
+ onPost: RouteMethod;
19
+ onPut: RouteMethod;
20
+ onPatch: RouteMethod;
21
+ onDelete: RouteMethod;
22
+ onOptions: RouteMethod;
23
+ onAll: RouteMethod;
24
+ onHead: RouteMethod;
25
+ }
26
+ export interface Context extends ClientContext {
27
+ /**
28
+ * An instance of fastify server.
29
+ * Use at your own risk.
30
+ * @instance
31
+ */
32
+ server: FastifyInstance;
33
+ /**
34
+ * Current request. Must be set only once!
35
+ */
36
+ request: FastifyRequest;
37
+ /**
38
+ * @internal
39
+ */
40
+ routes: ContextRoutes;
41
+ }
42
+ declare module "fastify" {
43
+ interface FastifyInstance {
44
+ webiny: Context;
45
+ }
21
46
  }
22
- export declare type ContextPlugin<C0 = Context, C1 = Context, C2 = Context, C3 = Context, C4 = Context, C5 = Context, C6 = Context, C7 = Context, C8 = Context, C9 = Context> = Plugin & {
23
- type: "context";
24
- apply(context: C0 & C1 & C2 & C3 & C4 & C5 & C6 & C7 & C8 & C9): Promise<void>;
25
- };
26
- export declare type HandlerPlugin<C0 = Context, C1 = Context, C2 = Context, C3 = Context, C4 = Context, C5 = Context, C6 = Context, C7 = Context, C8 = Context, C9 = Context> = Plugin & {
27
- type: "handler";
28
- handle(context: C0 & C1 & C2 & C3 & C4 & C5 & C6 & C7 & C8 & C9, next: Function): any;
29
- };
30
- export declare type HandlerResultPlugin<C0 = Context, C1 = Context, C2 = Context, C3 = Context, C4 = Context, C5 = Context, C6 = Context, C7 = Context, C8 = Context, C9 = Context> = Plugin & {
31
- type: "handler-result";
32
- handle(context: C0 & C1 & C2 & C3 & C4 & C5 & C6 & C7 & C8 & C9, result: any): any;
33
- };
34
- export declare type HandlerErrorPlugin<C0 = Context, C1 = Context, C2 = Context, C3 = Context, C4 = Context, C5 = Context, C6 = Context, C7 = Context, C8 = Context, C9 = Context> = Plugin & {
35
- type: "handler-error";
36
- handle(context: C0 & C1 & C2 & C3 & C4 & C5 & C6 & C7 & C8 & C9, error: any, next: Function): Promise<any>;
37
- };
package/types.js CHANGED
@@ -2,4 +2,18 @@
2
2
 
3
3
  Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
- });
5
+ });
6
+ Object.defineProperty(exports, "FastifyInstance", {
7
+ enumerable: true,
8
+ get: function () {
9
+ return _fastify.FastifyInstance;
10
+ }
11
+ });
12
+ Object.defineProperty(exports, "HTTPMethods", {
13
+ enumerable: true,
14
+ get: function () {
15
+ return _fastify.HTTPMethods;
16
+ }
17
+ });
18
+
19
+ var _fastify = require("fastify");
package/types.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"names":[],"sources":["types.ts"],"sourcesContent":["import {\n FastifyInstance,\n FastifyRequest,\n FastifyReply,\n HTTPMethods,\n RouteHandlerMethod\n} from \"fastify\";\n\nexport { FastifyInstance, HTTPMethods } from \"fastify\";\nimport { ClientContext } from \"@webiny/handler-client/types\";\n\nexport type RouteTypes = HTTPMethods;\n\nexport interface RouteMethodOptions {\n override?: boolean;\n}\n\nexport type RouteMethodPath = `/${string}` | \"*\";\nexport interface RouteMethod {\n (path: RouteMethodPath, handler: RouteHandlerMethod, options?: RouteMethodOptions): void;\n}\n\nexport type Request = FastifyRequest;\nexport type Reply = FastifyReply;\n\nexport type DefinedContextRoutes = Record<RouteTypes, string[]>;\nexport interface ContextRoutes {\n defined: DefinedContextRoutes;\n onGet: RouteMethod;\n onPost: RouteMethod;\n onPut: RouteMethod;\n onPatch: RouteMethod;\n onDelete: RouteMethod;\n onOptions: RouteMethod;\n onAll: RouteMethod;\n onHead: RouteMethod;\n}\n\nexport interface Context extends ClientContext {\n /**\n * An instance of fastify server.\n * Use at your own risk.\n * @instance\n */\n server: FastifyInstance;\n /**\n * Current request. Must be set only once!\n */\n request: FastifyRequest;\n /**\n * @internal\n */\n routes: ContextRoutes;\n}\n\ndeclare module \"fastify\" {\n interface FastifyInstance {\n webiny: Context;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA"}
@@ -1,2 +0,0 @@
1
- declare const _default: (...plugins: any[]) => (...args: any[]) => Promise<any>;
2
- export default _default;
package/createHandler.js DELETED
@@ -1,70 +0,0 @@
1
- "use strict";
2
-
3
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
-
5
- Object.defineProperty(exports, "__esModule", {
6
- value: true
7
- });
8
- exports.default = void 0;
9
-
10
- var _plugins = require("@webiny/plugins");
11
-
12
- var _middleware = _interopRequireDefault(require("./middleware"));
13
-
14
- var _default = (...plugins) => async (...args) => {
15
- const context = {
16
- plugins: new _plugins.PluginsContainer(plugins),
17
- args,
18
- // @ts-ignore
19
- // this is injected using webpack.DefinePlugin at build time
20
- WEBINY_VERSION: process.env.WEBINY_VERSION
21
- };
22
- const result = await handle(args, context);
23
- const handlerPlugins = context.plugins.byType("handler-result");
24
-
25
- for (let i = 0; i < handlerPlugins.length; i++) {
26
- if (handlerPlugins[i].apply) {
27
- await handlerPlugins[i].apply(result, context);
28
- }
29
- }
30
-
31
- return result;
32
- };
33
-
34
- exports.default = _default;
35
-
36
- async function handle(_, context) {
37
- try {
38
- const contextPlugins = context.plugins.byType("context");
39
-
40
- for (let i = 0; i < contextPlugins.length; i++) {
41
- if (contextPlugins[i].apply) {
42
- await contextPlugins[i].apply(context);
43
- }
44
- }
45
-
46
- const beforeHandlerPlugins = context.plugins.byType("before-handler");
47
-
48
- for (let i = 0; i < beforeHandlerPlugins.length; i++) {
49
- if (beforeHandlerPlugins[i].apply) {
50
- await beforeHandlerPlugins[i].apply(context);
51
- }
52
- }
53
-
54
- const handlers = context.plugins.byType("handler");
55
- const handler = (0, _middleware.default)(handlers.map(pl => pl.handle));
56
- const result = await handler(context);
57
-
58
- if (!result) {
59
- throw Error(`No result was returned from registered handlers.`);
60
- }
61
-
62
- return result;
63
- } catch (error) {
64
- // Log error to cloud, as these can be extremely annoying to debug!
65
- console.log(error);
66
- const handlers = context.plugins.byType("handler-error");
67
- const handler = (0, _middleware.default)(handlers.map(pl => pl.handle));
68
- return handler(context, error);
69
- }
70
- }
@@ -1,11 +0,0 @@
1
- import { Plugin } from "@webiny/plugins";
2
- interface Callable<TContext> {
3
- (context: TContext): void | Promise<void>;
4
- }
5
- export declare class ContextPlugin<TContext> extends Plugin {
6
- static readonly type = "context";
7
- private readonly _callable;
8
- constructor(callable?: Callable<TContext>);
9
- apply(context: TContext): void | Promise<void>;
10
- }
11
- export {};
@@ -1,32 +0,0 @@
1
- "use strict";
2
-
3
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
-
5
- Object.defineProperty(exports, "__esModule", {
6
- value: true
7
- });
8
- exports.ContextPlugin = void 0;
9
-
10
- var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
11
-
12
- var _plugins = require("@webiny/plugins");
13
-
14
- class ContextPlugin extends _plugins.Plugin {
15
- constructor(callable) {
16
- super();
17
- (0, _defineProperty2.default)(this, "_callable", void 0);
18
- this._callable = callable;
19
- }
20
-
21
- apply(context) {
22
- if (typeof this._callable !== "function") {
23
- throw Error(`Missing callable in ContextPlugin! Either pass a callable to plugin constructor or extend the plugin and override the "apply" method.`);
24
- }
25
-
26
- return this._callable(context);
27
- }
28
-
29
- }
30
-
31
- exports.ContextPlugin = ContextPlugin;
32
- (0, _defineProperty2.default)(ContextPlugin, "type", "context");