@webiny/handler 0.0.0-unstable.13771d80a8 → 0.0.0-unstable.2696f9d9e8

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 CHANGED
@@ -1,14 +1,21 @@
1
- import { Context as BaseContext, ContextParams as BaseContextParams } from "@webiny/api";
2
- import { Context as BaseContextType } from "./types";
1
+ import { Context as BaseContext, ContextParams as BaseContextParams, ContextPlugin as BaseContextPlugin, ContextPluginCallable as BaseContextPluginCallable } from "@webiny/api";
2
+ import { Context as ContextInterface } from "./types";
3
3
  export interface ContextParams extends BaseContextParams {
4
- server: BaseContextType["server"];
5
- routes: BaseContextType["routes"];
4
+ routes: ContextInterface["routes"];
6
5
  }
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
- reply: BaseContextType["reply"];
6
+ export declare class Context extends BaseContext implements ContextInterface {
7
+ readonly routes: ContextInterface["routes"];
8
+ handlerClient: ContextInterface["handlerClient"];
9
+ request: ContextInterface["request"];
10
+ reply: ContextInterface["reply"];
13
11
  constructor(params: ContextParams);
14
12
  }
13
+ /**
14
+ * We need to extend and reexport the ContextPlugin, ContextPluginCallable and createContextPlugin to support extended context.
15
+ *
16
+ * This can be removed when we introduce the type augmentation.
17
+ */
18
+ export declare type ContextPluginCallable<T extends ContextInterface = ContextInterface> = BaseContextPluginCallable<T>;
19
+ export declare class ContextPlugin<T extends ContextInterface = ContextInterface> extends BaseContextPlugin<T> {
20
+ }
21
+ export declare const createContextPlugin: <T extends ContextInterface = ContextInterface>(callable: ContextPluginCallable<T>) => BaseContextPlugin<T>;
package/Context.js CHANGED
@@ -1,28 +1,34 @@
1
1
  "use strict";
2
2
 
3
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
4
3
  Object.defineProperty(exports, "__esModule", {
5
4
  value: true
6
5
  });
7
- exports.Context = void 0;
8
- var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
6
+ exports.createContextPlugin = exports.ContextPlugin = exports.Context = void 0;
9
7
  var _api = require("@webiny/api");
10
8
  class Context extends _api.Context {
11
- // @ts-ignore
9
+ // @ts-expect-error
12
10
 
13
- // @ts-ignore
11
+ // @ts-expect-error
14
12
 
15
- // @ts-ignore
13
+ // @ts-expect-error
16
14
 
17
15
  constructor(params) {
18
16
  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
- (0, _defineProperty2.default)(this, "reply", void 0);
24
- this.server = params.server;
25
17
  this.routes = params.routes;
26
18
  }
27
19
  }
28
- exports.Context = Context;
20
+
21
+ /**
22
+ * We need to extend and reexport the ContextPlugin, ContextPluginCallable and createContextPlugin to support extended context.
23
+ *
24
+ * This can be removed when we introduce the type augmentation.
25
+ */
26
+ exports.Context = Context;
27
+ class ContextPlugin extends _api.ContextPlugin {}
28
+ exports.ContextPlugin = ContextPlugin;
29
+ const createContextPlugin = callable => {
30
+ return (0, _api.createContextPlugin)(callable);
31
+ };
32
+ exports.createContextPlugin = createContextPlugin;
33
+
34
+ //# sourceMappingURL=Context.js.map
package/Context.js.map CHANGED
@@ -1 +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 // @ts-ignore\n public reply: BaseContextType[\"reply\"];\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,OAAO,SAASC,YAAW,CAA4B;EAGhE;;EAEA;;EAEA;;EAGOC,WAAW,CAACC,MAAqB,EAAE;IACtC,KAAK,CAACA,MAAM,CAAC;IAAC;IAAA;IAAA;IAAA;IAAA;IACd,IAAI,CAACC,MAAM,GAAGD,MAAM,CAACC,MAAM;IAC3B,IAAI,CAACC,MAAM,GAAGF,MAAM,CAACE,MAAM;EAC/B;AACJ;AAAC"}
1
+ {"version":3,"names":["_api","require","Context","BaseContext","constructor","params","routes","exports","ContextPlugin","BaseContextPlugin","createContextPlugin","callable","baseCreateContextPlugin"],"sources":["Context.ts"],"sourcesContent":["import {\n Context as BaseContext,\n ContextParams as BaseContextParams,\n ContextPlugin as BaseContextPlugin,\n ContextPluginCallable as BaseContextPluginCallable,\n createContextPlugin as baseCreateContextPlugin\n} from \"@webiny/api\";\nimport { Context as ContextInterface } from \"~/types\";\n\nexport interface ContextParams extends BaseContextParams {\n routes: ContextInterface[\"routes\"];\n}\n\nexport class Context extends BaseContext implements ContextInterface {\n public readonly routes: ContextInterface[\"routes\"];\n // @ts-expect-error\n public handlerClient: ContextInterface[\"handlerClient\"];\n // @ts-expect-error\n public request: ContextInterface[\"request\"];\n // @ts-expect-error\n public reply: ContextInterface[\"reply\"];\n\n public constructor(params: ContextParams) {\n super(params);\n this.routes = params.routes;\n }\n}\n\n/**\n * We need to extend and reexport the ContextPlugin, ContextPluginCallable and createContextPlugin to support extended context.\n *\n * This can be removed when we introduce the type augmentation.\n */\nexport type ContextPluginCallable<T extends ContextInterface = ContextInterface> =\n BaseContextPluginCallable<T>;\n\nexport class ContextPlugin<\n T extends ContextInterface = ContextInterface\n> extends BaseContextPlugin<T> {}\n\nexport const createContextPlugin = <T extends ContextInterface = ContextInterface>(\n callable: ContextPluginCallable<T>\n) => {\n return baseCreateContextPlugin<T>(callable);\n};\n"],"mappings":";;;;;;AAAA,IAAAA,IAAA,GAAAC,OAAA;AAaO,MAAMC,OAAO,SAASC,YAAW,CAA6B;EAEjE;;EAEA;;EAEA;;EAGOC,WAAWA,CAACC,MAAqB,EAAE;IACtC,KAAK,CAACA,MAAM,CAAC;IACb,IAAI,CAACC,MAAM,GAAGD,MAAM,CAACC,MAAM;EAC/B;AACJ;;AAEA;AACA;AACA;AACA;AACA;AAJAC,OAAA,CAAAL,OAAA,GAAAA,OAAA;AAQO,MAAMM,aAAa,SAEhBC,kBAAiB,CAAI;AAAEF,OAAA,CAAAC,aAAA,GAAAA,aAAA;AAE1B,MAAME,mBAAmB,GAC5BC,QAAkC,IACjC;EACD,OAAO,IAAAC,wBAAuB,EAAID,QAAQ,CAAC;AAC/C,CAAC;AAACJ,OAAA,CAAAG,mBAAA,GAAAA,mBAAA"}
@@ -0,0 +1,25 @@
1
+ /// <reference types="node" />
2
+ import * as http from "http";
3
+ declare type ExtraHeaders = {
4
+ "content-type"?: string | undefined;
5
+ "x-webiny-version"?: http.OutgoingHttpHeader | undefined;
6
+ };
7
+ declare type AllHeaders = http.OutgoingHttpHeaders & ExtraHeaders;
8
+ export declare type StandardHeaderValue = http.OutgoingHttpHeader | boolean | undefined;
9
+ export declare type StandardHeaders = {
10
+ [K in keyof AllHeaders as string extends K ? never : number extends K ? never : K]: http.OutgoingHttpHeaders[K];
11
+ } & {
12
+ [name: string]: StandardHeaderValue;
13
+ };
14
+ declare type Setter<T> = ((value: T) => T) | T;
15
+ export declare class ResponseHeaders {
16
+ private readonly headers;
17
+ private constructor();
18
+ set<T extends keyof StandardHeaders>(header: T, setter: Setter<StandardHeaders[T]>): this;
19
+ merge(headers: ResponseHeaders): ResponseHeaders;
20
+ getHeaders(): {
21
+ [k: string]: StandardHeaderValue;
22
+ };
23
+ static create(initialHeaders?: StandardHeaders): ResponseHeaders;
24
+ }
25
+ export {};
@@ -0,0 +1,46 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.ResponseHeaders = void 0;
7
+ // Extract known standard headers, and remove all non-string keys.
8
+
9
+ function isFunction(setter) {
10
+ return typeof setter === "function";
11
+ }
12
+ class ResponseHeaders {
13
+ headers = new Map();
14
+ constructor(initialHeaders) {
15
+ if (initialHeaders) {
16
+ Object.keys(initialHeaders).forEach(key => {
17
+ this.headers.set(key, initialHeaders[key]);
18
+ });
19
+ }
20
+ }
21
+ set(header, setter) {
22
+ if (isFunction(setter)) {
23
+ const previousValue = this.headers.get(header);
24
+ const newValue = setter(previousValue);
25
+ this.headers.set(header, newValue);
26
+ return this;
27
+ }
28
+ this.headers.set(header, setter);
29
+ return this;
30
+ }
31
+ merge(headers) {
32
+ return ResponseHeaders.create({
33
+ ...this.getHeaders(),
34
+ ...headers.getHeaders()
35
+ });
36
+ }
37
+ getHeaders() {
38
+ return Object.fromEntries(this.headers);
39
+ }
40
+ static create(initialHeaders) {
41
+ return new ResponseHeaders(initialHeaders);
42
+ }
43
+ }
44
+ exports.ResponseHeaders = ResponseHeaders;
45
+
46
+ //# sourceMappingURL=ResponseHeaders.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"names":["isFunction","setter","ResponseHeaders","headers","Map","constructor","initialHeaders","Object","keys","forEach","key","set","header","previousValue","get","newValue","merge","create","getHeaders","fromEntries","exports"],"sources":["ResponseHeaders.ts"],"sourcesContent":["import * as http from \"http\";\n\ntype ExtraHeaders = {\n \"content-type\"?: string | undefined;\n \"x-webiny-version\"?: http.OutgoingHttpHeader | undefined;\n};\n\ntype AllHeaders = http.OutgoingHttpHeaders & ExtraHeaders;\n\nexport type StandardHeaderValue = http.OutgoingHttpHeader | boolean | undefined;\n\n// Extract known standard headers, and remove all non-string keys.\nexport type StandardHeaders = {\n [K in keyof AllHeaders as string extends K\n ? never\n : number extends K\n ? never\n : K]: http.OutgoingHttpHeaders[K];\n} & {\n [name: string]: StandardHeaderValue;\n};\n\nfunction isFunction<T>(setter: unknown): setter is (value: T) => T {\n return typeof setter === \"function\";\n}\n\ntype Setter<T> = ((value: T) => T) | T;\n\nexport class ResponseHeaders {\n private readonly headers = new Map<keyof StandardHeaders, StandardHeaderValue>();\n\n private constructor(initialHeaders?: StandardHeaders) {\n if (initialHeaders) {\n (Object.keys(initialHeaders) as Array<keyof StandardHeaders>).forEach(key => {\n this.headers.set(key, initialHeaders[key]);\n });\n }\n }\n\n set<T extends keyof StandardHeaders>(header: T, setter: Setter<StandardHeaders[T]>) {\n if (isFunction<StandardHeaders[T]>(setter)) {\n const previousValue = this.headers.get(header) as StandardHeaders[T];\n const newValue = setter(previousValue);\n this.headers.set(header, newValue);\n return this;\n }\n\n this.headers.set(header, setter);\n\n return this;\n }\n\n merge(headers: ResponseHeaders) {\n return ResponseHeaders.create({ ...this.getHeaders(), ...headers.getHeaders() });\n }\n\n getHeaders() {\n return Object.fromEntries(this.headers);\n }\n\n static create(initialHeaders?: StandardHeaders) {\n return new ResponseHeaders(initialHeaders);\n }\n}\n"],"mappings":";;;;;;AAWA;;AAWA,SAASA,UAAUA,CAAIC,MAAe,EAA6B;EAC/D,OAAO,OAAOA,MAAM,KAAK,UAAU;AACvC;AAIO,MAAMC,eAAe,CAAC;EACRC,OAAO,GAAG,IAAIC,GAAG,CAA6C,CAAC;EAExEC,WAAWA,CAACC,cAAgC,EAAE;IAClD,IAAIA,cAAc,EAAE;MACfC,MAAM,CAACC,IAAI,CAACF,cAAc,CAAC,CAAkCG,OAAO,CAACC,GAAG,IAAI;QACzE,IAAI,CAACP,OAAO,CAACQ,GAAG,CAACD,GAAG,EAAEJ,cAAc,CAACI,GAAG,CAAC,CAAC;MAC9C,CAAC,CAAC;IACN;EACJ;EAEAC,GAAGA,CAAkCC,MAAS,EAAEX,MAAkC,EAAE;IAChF,IAAID,UAAU,CAAqBC,MAAM,CAAC,EAAE;MACxC,MAAMY,aAAa,GAAG,IAAI,CAACV,OAAO,CAACW,GAAG,CAACF,MAAM,CAAuB;MACpE,MAAMG,QAAQ,GAAGd,MAAM,CAACY,aAAa,CAAC;MACtC,IAAI,CAACV,OAAO,CAACQ,GAAG,CAACC,MAAM,EAAEG,QAAQ,CAAC;MAClC,OAAO,IAAI;IACf;IAEA,IAAI,CAACZ,OAAO,CAACQ,GAAG,CAACC,MAAM,EAAEX,MAAM,CAAC;IAEhC,OAAO,IAAI;EACf;EAEAe,KAAKA,CAACb,OAAwB,EAAE;IAC5B,OAAOD,eAAe,CAACe,MAAM,CAAC;MAAE,GAAG,IAAI,CAACC,UAAU,CAAC,CAAC;MAAE,GAAGf,OAAO,CAACe,UAAU,CAAC;IAAE,CAAC,CAAC;EACpF;EAEAA,UAAUA,CAAA,EAAG;IACT,OAAOX,MAAM,CAACY,WAAW,CAAC,IAAI,CAAChB,OAAO,CAAC;EAC3C;EAEA,OAAOc,MAAMA,CAACX,cAAgC,EAAE;IAC5C,OAAO,IAAIJ,eAAe,CAACI,cAAc,CAAC;EAC9C;AACJ;AAACc,OAAA,CAAAlB,eAAA,GAAAA,eAAA"}
package/fastify.d.ts CHANGED
@@ -1,8 +1,9 @@
1
1
  /// <reference types="node" />
2
- import { PluginCollection } from "@webiny/plugins/types";
2
+ import { PluginCollection, PluginsContainer } from "@webiny/plugins/types";
3
3
  import { FastifyServerOptions as ServerOptions } from "fastify";
4
4
  export interface CreateHandlerParams {
5
- plugins: PluginCollection;
5
+ plugins: PluginCollection | PluginsContainer;
6
6
  options?: ServerOptions;
7
+ debug?: boolean;
7
8
  }
8
9
  export declare const createHandler: (params: CreateHandlerParams) => import("fastify").FastifyInstance<import("fastify").RawServerDefault, import("http").IncomingMessage, import("http").ServerResponse<import("http").IncomingMessage>, import("fastify").FastifyBaseLogger, import("fastify").FastifyTypeProviderDefault> & PromiseLike<import("fastify").FastifyInstance<import("fastify").RawServerDefault, import("http").IncomingMessage, import("http").ServerResponse<import("http").IncomingMessage>, import("fastify").FastifyBaseLogger, import("fastify").FastifyTypeProviderDefault>>;
package/fastify.js CHANGED
@@ -5,7 +5,7 @@ Object.defineProperty(exports, "__esModule", {
5
5
  value: true
6
6
  });
7
7
  exports.createHandler = void 0;
8
- var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));
8
+ var _types = require("@webiny/plugins/types");
9
9
  var _fastify = _interopRequireDefault(require("fastify"));
10
10
  var _utils = require("@webiny/utils");
11
11
  var _Context = require("./Context");
@@ -21,35 +21,46 @@ var _HandlerResultPlugin = require("./plugins/HandlerResultPlugin");
21
21
  var _HandlerErrorPlugin = require("./plugins/HandlerErrorPlugin");
22
22
  var _ModifyFastifyPlugin = require("./plugins/ModifyFastifyPlugin");
23
23
  var _HandlerOnRequestPlugin = require("./plugins/HandlerOnRequestPlugin");
24
- const DEFAULT_HEADERS = (0, _objectSpread2.default)({
25
- "Cache-Control": "no-store",
26
- "Content-Type": "application/json; charset=utf-8",
27
- "Access-Control-Allow-Origin": "*",
28
- "Access-Control-Allow-Headers": "*",
29
- "Access-Control-Allow-Methods": "OPTIONS,POST,GET,DELETE,PUT,PATCH"
30
- }, (0, _utils.getWebinyVersionHeaders)());
24
+ var _ResponseHeaders = require("./ResponseHeaders");
25
+ var _ModifyResponseHeadersPlugin = require("./plugins/ModifyResponseHeadersPlugin");
26
+ function createDefaultHeaders() {
27
+ return _ResponseHeaders.ResponseHeaders.create({
28
+ "content-type": "application/json; charset=utf-8",
29
+ "cache-control": "no-store",
30
+ "access-control-allow-origin": "*",
31
+ "access-control-allow-headers": "*",
32
+ "access-control-allow-methods": "OPTIONS,POST,GET,DELETE,PUT,PATCH",
33
+ ...(0, _utils.getWebinyVersionHeaders)()
34
+ });
35
+ }
36
+ const getDefaultOptionsHeaders = () => {
37
+ return _ResponseHeaders.ResponseHeaders.create({
38
+ "access-control-max-age": "86400",
39
+ "cache-control": "public, max-age=86400"
40
+ });
41
+ };
31
42
  const getDefaultHeaders = routes => {
43
+ const headers = createDefaultHeaders();
44
+
32
45
  /**
33
46
  * If we are accepting all headers, just output that one.
34
47
  */
35
48
  const keys = Object.keys(routes);
36
49
  const all = keys.every(key => routes[key].length > 0);
37
50
  if (all) {
38
- return (0, _objectSpread2.default)((0, _objectSpread2.default)({}, DEFAULT_HEADERS), {}, {
39
- "Access-Control-Allow-Methods": "*"
40
- });
41
- }
42
- return (0, _objectSpread2.default)((0, _objectSpread2.default)({}, DEFAULT_HEADERS), {}, {
43
- "Access-Control-Allow-Methods": keys.filter(type => {
44
- if (!routes[type] || Array.isArray(routes[type]) === false) {
51
+ headers.set("access-control-allow-methods", "*");
52
+ } else {
53
+ const allowedMethods = keys.filter(type => {
54
+ if (!routes[type] || !Array.isArray(routes[type])) {
45
55
  return false;
46
56
  }
47
57
  return routes[type].length > 0;
48
- }).sort().join(",")
49
- });
58
+ }).sort().join(",");
59
+ headers.set("access-control-allow-methods", allowedMethods);
60
+ }
61
+ return headers;
50
62
  };
51
63
  const stringifyError = error => {
52
- var _error$constructor;
53
64
  const {
54
65
  name,
55
66
  message,
@@ -57,18 +68,15 @@ const stringifyError = error => {
57
68
  stack,
58
69
  data
59
70
  } = error;
60
- return JSON.stringify((0, _objectSpread2.default)((0, _objectSpread2.default)({}, error), {}, {
61
- constructorName: ((_error$constructor = error.constructor) === null || _error$constructor === void 0 ? void 0 : _error$constructor.name) || "UnknownError",
71
+ return JSON.stringify({
72
+ ...error,
73
+ constructorName: error.constructor?.name || "UnknownError",
62
74
  name: name || "No error name",
63
75
  message: message || "No error message",
64
76
  code: code || "NO_CODE",
65
77
  data,
66
78
  stack: process.env.DEBUG === "true" ? stack : "Turn on the debug flag to see the stack."
67
- }));
68
- };
69
- const OPTIONS_HEADERS = {
70
- "Access-Control-Max-Age": "86400",
71
- "Cache-Control": "public, max-age=86400"
79
+ });
72
80
  };
73
81
  const createHandler = params => {
74
82
  const definedRoutes = {
@@ -98,18 +106,18 @@ const createHandler = params => {
98
106
  if (!all) {
99
107
  return;
100
108
  }
101
- console.log(`Error while registering onAll route. One of the routes is already defined.`);
102
- console.log(JSON.stringify(all));
109
+ console.error(`Error while registering onAll route. One of the routes is already defined.`);
110
+ console.error(JSON.stringify(all));
103
111
  throw new _error.default(`You cannot override a route with onAll() method, please remove unnecessary route from the system.`, "OVERRIDE_ROUTE_ERROR", {
104
112
  type,
105
113
  path
106
114
  });
107
115
  } else if (definedRoutes[type].includes(path) === false) {
108
116
  return;
109
- } else if ((options === null || options === void 0 ? void 0 : options.override) === true) {
117
+ } else if (options?.override === true) {
110
118
  return;
111
119
  }
112
- console.log(`Error while trying to override route: [${type}] ${path}`);
120
+ console.error(`Error while trying to override route: [${type}] ${path}`);
113
121
  throw new _error.default(`When you are trying to override existing route, you must send "override" parameter when adding that route.`, "OVERRIDE_ROUTE_ERROR", {
114
122
  type,
115
123
  path
@@ -126,7 +134,9 @@ const createHandler = params => {
126
134
  /**
127
135
  * We must attach the server to our internal context if we want to have it accessible.
128
136
  */
129
- const app = (0, _fastify.default)((0, _objectSpread2.default)({}, params.options || {}));
137
+ const app = (0, _fastify.default)({
138
+ ...(params.options || {})
139
+ });
130
140
  /**
131
141
  * We need to register routes in our system so we can output headers later on and dissallow overriding routes.
132
142
  */
@@ -205,24 +215,25 @@ const createHandler = params => {
205
215
  }
206
216
  };
207
217
  let context;
218
+ const plugins = new _types.PluginsContainer([
219
+ /**
220
+ * We must have handlerClient by default.
221
+ * And it must be one of the first context plugins applied.
222
+ */
223
+ (0, _handlerClient.createHandlerClient)()]);
224
+ plugins.merge(params.plugins || []);
208
225
  try {
209
226
  context = new _Context.Context({
210
- plugins: [
211
- /**
212
- * We must have handlerClient by default.
213
- * And it must be one of the first context plugins applied.
214
- */
215
- (0, _handlerClient.createHandlerClient)(), ...(params.plugins || [])],
227
+ plugins,
216
228
  /**
217
- * Inserted via webpack on build time.
229
+ * Inserted via webpack at build time.
218
230
  */
219
231
  WEBINY_VERSION: process.env.WEBINY_VERSION,
220
- server: app,
221
232
  routes
222
233
  });
223
234
  } catch (ex) {
224
- console.log(`Error while constructing the Context.`);
225
- console.log(stringifyError(ex));
235
+ console.error(`Error while constructing the Context.`);
236
+ console.error(stringifyError(ex));
226
237
  throw ex;
227
238
  }
228
239
 
@@ -231,42 +242,18 @@ const createHandler = params => {
231
242
  */
232
243
  app.decorate("webiny", context);
233
244
 
234
- /**
235
- * We have few types of triggers:
236
- * * Events - EventPlugin
237
- * * Routes - RoutePlugin
238
- *
239
- * Routes are registered in fastify but events must be handled in package which implements cloud specific methods.
240
- */
241
- const routePlugins = app.webiny.plugins.byType(_RoutePlugin.RoutePlugin.type);
242
-
243
- /**
244
- * Add routes to the system.
245
- */
246
- let routePluginName;
247
- try {
248
- for (const plugin of routePlugins) {
249
- routePluginName = plugin.name;
250
- plugin.cb((0, _objectSpread2.default)((0, _objectSpread2.default)({}, app.webiny.routes), {}, {
251
- context: app.webiny
252
- }));
253
- }
254
- } catch (ex) {
255
- console.log(`Error while running the "RoutePlugin" ${routePluginName ? `(${routePluginName})` : ""} plugin in the beginning of the "createHandler" callable.`);
256
- console.log(stringifyError(ex));
257
- throw ex;
258
- }
259
-
260
245
  /**
261
246
  * On every request we add default headers, which can be changed later.
262
247
  * Also, if it is an options request, we skip everything after this hook and output options headers.
263
248
  */
264
249
  app.addHook("onRequest", async (request, reply) => {
250
+ const isOptionsRequest = request.method === "OPTIONS";
265
251
  /**
266
252
  * Our default headers are always set. Users can override them.
267
253
  */
268
254
  const defaultHeaders = getDefaultHeaders(definedRoutes);
269
- reply.headers(defaultHeaders);
255
+ const initialHeaders = isOptionsRequest ? defaultHeaders.merge(getDefaultOptionsHeaders()) : defaultHeaders;
256
+ reply.headers(initialHeaders.getHeaders());
270
257
  /**
271
258
  * Users can define their own custom handlers for the onRequest event - so let's run them first.
272
259
  */
@@ -281,8 +268,8 @@ const createHandler = params => {
281
268
  }
282
269
  }
283
270
  } catch (ex) {
284
- console.log(`Error while running the "HandlerOnRequestPlugin" ${name ? `(${name})` : ""} plugin in the onRequest hook.`);
285
- console.log(stringifyError(ex));
271
+ console.error(`Error while running the "HandlerOnRequestPlugin" ${name ? `(${name})` : ""} plugin in the onRequest hook.`);
272
+ console.error(stringifyError(ex));
286
273
  throw ex;
287
274
  }
288
275
  /**
@@ -290,20 +277,20 @@ const createHandler = params => {
290
277
  *
291
278
  * Users can prevent this by creating their own HandlerOnRequestPlugin and returning false as the result of the callable.
292
279
  */
293
- if (request.method !== "OPTIONS") {
280
+ if (!isOptionsRequest) {
294
281
  return;
295
282
  }
296
283
  if (reply.sent) {
297
284
  /**
298
285
  * At this point throwing an exception will not do anything with the response. So just log it.
299
286
  */
300
- console.log(JSON.stringify({
287
+ console.error(JSON.stringify({
301
288
  message: `Output was already sent. Please check custom plugins of type "HandlerOnRequestPlugin".`,
302
289
  explanation: "This error can happen if the user plugin ended the reply, but did not return false as response."
303
290
  }));
304
291
  return;
305
292
  }
306
- reply.headers((0, _objectSpread2.default)((0, _objectSpread2.default)({}, defaultHeaders), OPTIONS_HEADERS)).code(204).send("").hijack();
293
+ reply.code(204).send("").hijack();
307
294
  });
308
295
  app.addHook("preParsing", async (request, reply) => {
309
296
  app.webiny.request = request;
@@ -316,8 +303,8 @@ const createHandler = params => {
316
303
  await plugin.apply(app.webiny);
317
304
  }
318
305
  } catch (ex) {
319
- console.log(`Error while running the "ContextPlugin" ${name ? `(${name})` : ""} plugin in the preParsing hook.`);
320
- console.log(stringifyError(ex));
306
+ console.error(`Error while running the "ContextPlugin" ${name ? `(${name})` : ""} plugin in the preParsing hook.`);
307
+ console.error(stringifyError(ex));
321
308
  throw ex;
322
309
  }
323
310
  });
@@ -333,8 +320,8 @@ const createHandler = params => {
333
320
  await plugin.apply(app.webiny);
334
321
  }
335
322
  } catch (ex) {
336
- console.log(`Error while running the "BeforeHandlerPlugin" ${name ? `(${name})` : ""} plugin in the preHandler hook.`);
337
- console.log(stringifyError(ex));
323
+ console.error(`Error while running the "BeforeHandlerPlugin" ${name ? `(${name})` : ""} plugin in the preHandler hook.`);
324
+ console.error(stringifyError(ex));
338
325
  throw ex;
339
326
  }
340
327
  });
@@ -351,8 +338,8 @@ const createHandler = params => {
351
338
  await plugin.handle(app.webiny, payload);
352
339
  }
353
340
  } catch (ex) {
354
- console.log(`Error while running the "HandlerResultPlugin" ${name ? `(${name})` : ""} plugin in the preSerialization hook.`);
355
- console.log(stringifyError(ex));
341
+ console.error(`Error while running the "HandlerResultPlugin" ${name ? `(${name})` : ""} plugin in the preSerialization hook.`);
342
+ console.error(stringifyError(ex));
356
343
  throw ex;
357
344
  }
358
345
  return payload;
@@ -376,8 +363,8 @@ const createHandler = params => {
376
363
  /**
377
364
  * Log error to cloud, as these can be extremely annoying to debug!
378
365
  */
379
- console.log("@webiny/handler");
380
- console.log(stringifyError(error));
366
+ console.error("@webiny/handler");
367
+ console.error(stringifyError(error));
381
368
  reply.status(500).headers({
382
369
  "Cache-Control": "no-store"
383
370
  }).send(
@@ -398,6 +385,29 @@ const createHandler = params => {
398
385
  return reply;
399
386
  });
400
387
 
388
+ /**
389
+ * Apply response headers modifier plugins.
390
+ */
391
+ app.addHook("onSend", async (request, reply, payload) => {
392
+ const modifyHeaders = app.webiny.plugins.byType(_ModifyResponseHeadersPlugin.ModifyResponseHeadersPlugin.type);
393
+ const headers = _ResponseHeaders.ResponseHeaders.create(reply.getHeaders());
394
+ modifyHeaders.forEach(plugin => {
395
+ plugin.modify(request, headers);
396
+ });
397
+ reply.headers(headers.getHeaders());
398
+ return payload;
399
+ });
400
+
401
+ /**
402
+ * We need to output the benchmark results at the end of the request in both response and timeout cases
403
+ */
404
+ app.addHook("onResponse", async () => {
405
+ await context.benchmark.output();
406
+ });
407
+ app.addHook("onTimeout", async () => {
408
+ await context.benchmark.output();
409
+ });
410
+
401
411
  /**
402
412
  * With these plugins we give users possibility to do anything they want on our fastify instance.
403
413
  */
@@ -409,10 +419,39 @@ const createHandler = params => {
409
419
  plugin.modify(app);
410
420
  }
411
421
  } catch (ex) {
412
- console.log(`Error while running the "ModifyFastifyPlugin" ${modifyFastifyPluginName ? `(${modifyFastifyPluginName})` : ""} plugin in the end of the "createHandler" callable.`);
413
- console.log(stringifyError(ex));
422
+ console.error(`Error while running the "ModifyFastifyPlugin" ${modifyFastifyPluginName ? `(${modifyFastifyPluginName})` : ""} plugin in the end of the "createHandler" callable.`);
423
+ console.error(stringifyError(ex));
424
+ throw ex;
425
+ }
426
+
427
+ /**
428
+ * We have few types of triggers:
429
+ * * Events - EventPlugin
430
+ * * Routes - RoutePlugin
431
+ *
432
+ * Routes are registered in fastify but events must be handled in package which implements cloud specific methods.
433
+ */
434
+ const routePlugins = app.webiny.plugins.byType(_RoutePlugin.RoutePlugin.type);
435
+
436
+ /**
437
+ * Add routes to the system.
438
+ */
439
+ let routePluginName;
440
+ try {
441
+ for (const plugin of routePlugins) {
442
+ routePluginName = plugin.name;
443
+ plugin.cb({
444
+ ...app.webiny.routes,
445
+ context: app.webiny
446
+ });
447
+ }
448
+ } catch (ex) {
449
+ console.error(`Error while running the "RoutePlugin" ${routePluginName ? `(${routePluginName})` : ""} plugin in the beginning of the "createHandler" callable.`);
450
+ console.error(stringifyError(ex));
414
451
  throw ex;
415
452
  }
416
453
  return app;
417
454
  };
418
- exports.createHandler = createHandler;
455
+ exports.createHandler = createHandler;
456
+
457
+ //# sourceMappingURL=fastify.js.map