@gasket/plugin-fastify 7.0.0-next.6 → 7.0.0-next.61

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/README.md CHANGED
@@ -6,26 +6,22 @@ Adds Fastify to your application.
6
6
 
7
7
  #### New apps
8
8
 
9
- ```
10
- gasket create <app-name> --plugins @gasket/plugin-fastify
11
- ```
12
-
13
- #### Existing apps
14
-
15
9
  ```
16
10
  npm i @gasket/plugin-fastify
17
11
  ```
18
12
 
19
- Modify `plugins` section of your `gasket.config.js`:
13
+ Update your `gasket` file plugin configuration:
20
14
 
21
15
  ```diff
22
- module.exports = {
23
- plugins: {
24
- add: [
25
- + '@gasket/plugin-fastify'
26
- ]
27
- }
28
- }
16
+ // gasket.js
17
+
18
+ + import pluginFastify from '@gasket/plugin-fastify';
19
+
20
+ export default makeGasket({
21
+ plugins: [
22
+ + pluginFastify
23
+ ]
24
+ });
29
25
  ```
30
26
 
31
27
  ## Configuration
@@ -34,80 +30,34 @@ All the configurations for the plugin are added under `fastify` in the config:
34
30
 
35
31
  - `compression`: true by default. Can be set to false if applying compression
36
32
  differently.
37
- - `excludedRoutesRegex`: Routes to be excluded based on a regex
38
33
  - `trustProxy`: Enable trust proxy option, [see Fastify documentation for possible values](https://fastify.dev/docs/latest/Reference/Server/#trustproxy)
39
34
 
40
35
  #### Example configuration
41
36
 
42
37
  ```js
43
- module.exports = {
44
- plugins: {
45
- add: ['@gasket/fastify']
46
- },
38
+ export default makeGasket({
39
+ plugins: [
40
+ pluginFastify
41
+ ],
47
42
  fastify: {
48
43
  compression: false,
44
+ routes: 'api/*.js',
49
45
  excludedRoutesRegex: /^(?!\/_next\/)/,
50
46
  trustProxy: true
51
47
  }
52
- }
53
- ```
54
-
55
- ### Middleware paths
56
-
57
- The `gasket.config.js` can contain a `middleware` property, which is an array of
58
- objects that map plugins to route or path patterns, allowing apps to tune which
59
- middleware are triggered for which requests.
60
-
61
- ```js
62
- middleware: [
63
- {
64
- plugin:'gasket-plugin-example', // Name of the Gasket plugin
65
- paths: ['/api']
66
- },
67
- {
68
- plugin:'@some/gasket-plugin-example',
69
- paths: [/\/default/]
70
- },
71
- {
72
- plugin: '@another/gasket-plugin-example',
73
- paths: ['/proxy', /\/home/]
74
- }
75
- ]
48
+ });
76
49
  ```
77
50
 
78
51
  ## Lifecycles
79
52
 
80
- ### middleware
81
-
82
- Executed when the `fastify` server has been created, it will apply all returned
83
- functions as middleware.
84
-
85
- ```js
86
- module.exports = {
87
- hooks: {
88
- /**
89
- * Add Fastify middleware
90
- *
91
- * @param {Gasket} gasket The Gasket API
92
- * @param {Fastify} app - Fastify app instance
93
- * @returns {function|function[]} middleware(s)
94
- */
95
- middleware: function (gasket, app) {
96
- return require('x-xss-protection')();
97
- }
98
- }
99
- }
100
- ```
101
-
102
- You may also return an `Array` to inject more than one middleware.
103
-
104
53
  ### fastify
105
54
 
106
55
  Executed **after** the `middleware` event for when you need full control over
107
56
  the `fastify` instance.
108
57
 
109
58
  ```js
110
- module.exports = {
59
+ export default {
60
+ name: 'sample-plugin',
111
61
  hooks: {
112
62
  /**
113
63
  * Update Fastify app instance
@@ -119,7 +69,7 @@ module.exports = {
119
69
  fastify: async function (gasket, fastify) {
120
70
  }
121
71
  }
122
- }
72
+ };
123
73
  ```
124
74
 
125
75
  ### errorMiddleware
@@ -128,7 +78,8 @@ Executed after the `fastify` event. All middleware functions returned from this
128
78
  hook will be applied to Fastify.
129
79
 
130
80
  ```js
131
- module.exports = {
81
+ export default {
82
+ name: 'sample-plugin',
132
83
  hooks: {
133
84
  /**
134
85
  * Add Fastify error middlewares
@@ -139,7 +90,7 @@ module.exports = {
139
90
  errorMiddleware: function (gasket) {
140
91
  }
141
92
  }
142
- }
93
+ };
143
94
  ```
144
95
 
145
96
  ## How it works
@@ -0,0 +1,53 @@
1
+ /// <reference types="@gasket/plugin-https" />
2
+ /// <reference types="@gasket/plugin-logger" />
3
+
4
+ const { alignLogger } = require('./utils');
5
+
6
+ /**
7
+ * Create the Fastify instance and setup the lifecycle hooks.
8
+ * Fastify is compatible with express middleware out of the box, so we can
9
+ * use the same middleware lifecycles.
10
+ * @type {import('@gasket/core').HookHandler<'createServers'>}
11
+ */
12
+ // eslint-disable-next-line max-statements
13
+ module.exports = async function createServers(gasket, serverOpts) {
14
+ const fastify = require('fastify');
15
+
16
+ const { config } = gasket;
17
+ const {
18
+ fastify: {
19
+ routes,
20
+ trustProxy = false
21
+ } = {},
22
+ http2
23
+ } = config;
24
+
25
+ const fastifyLogger = alignLogger(gasket.logger);
26
+
27
+ // @ts-ignore
28
+ const app = fastify({ logger: fastifyLogger, trustProxy, http2 });
29
+
30
+ // allow consuming apps to directly append options to their server
31
+ await gasket.exec('fastify', app);
32
+
33
+ if (routes) {
34
+ for (const route of routes) {
35
+ if (typeof route !== 'function') {
36
+ throw new Error('Route must be a function');
37
+ }
38
+ await route(app);
39
+ }
40
+ }
41
+
42
+ const postRenderingStacks = (await gasket.exec('errorMiddleware')).filter(Boolean);
43
+ // @ts-ignore
44
+ postRenderingStacks.forEach((stack) => app.use(stack));
45
+
46
+ return {
47
+ ...serverOpts,
48
+ handler: async function handler(...args) {
49
+ await app.ready();
50
+ app.server.emit('request', ...args);
51
+ }
52
+ };
53
+ };
package/lib/create.js ADDED
@@ -0,0 +1,34 @@
1
+ /// <reference types="@gasket/core" />
2
+
3
+ const { name, version, devDependencies } = require('../package.json');
4
+
5
+ /**
6
+ * Add files & extend package.json for new apps.
7
+ * @type {import('@gasket/core').HookHandler<'create'>}
8
+ */
9
+ module.exports = async function create(gasket, context) {
10
+ const generatorDir = `${__dirname}/../generator`;
11
+
12
+ context.gasketConfig.addPlugin('pluginFastify', name);
13
+
14
+ context.pkg.add('dependencies', {
15
+ [name]: `^${version}`,
16
+ fastify: devDependencies.fastify
17
+ });
18
+
19
+ if ('apiApp' in context && context.apiApp) {
20
+ context.gasketConfig.add('fastify', {
21
+ routes: []
22
+ });
23
+
24
+ if ('typescript' in context && context.typescript) {
25
+ context.files.add(`${generatorDir}/**/!(*.js)`);
26
+ } else {
27
+ context.files.add(`${generatorDir}/**/!(*.ts)`);
28
+ }
29
+
30
+ context.gasketConfig
31
+ .addImport('{ routes }', './routes/index.js')
32
+ .injectValue('fastify.routes', 'routes');
33
+ }
34
+ };
package/lib/index.d.ts CHANGED
@@ -1,18 +1,45 @@
1
- import type { MaybeAsync, MaybeMultiple } from '@gasket/engine';
2
- import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
1
+ import type { MaybeAsync, MaybeMultiple, Plugin } from '@gasket/core';
2
+ import { Logger } from '@gasket/plugin-logger';
3
+ import type {
4
+ FastifyInstance,
5
+ FastifyRequest,
6
+ FastifyReply,
7
+ FastifyServerOptions
8
+ } from 'fastify';
9
+ import { Http2SecureServer, Http2ServerRequest, Http2ServerResponse } from 'http2'
3
10
 
4
- declare module '@gasket/engine' {
11
+ export type AppRoutes = Array<MaybeAsync<(app: FastifyInstance) => void>>;
12
+
13
+ declare module '@gasket/core' {
5
14
  export interface GasketConfig {
6
- compression?: boolean,
7
- excludedRoutesRegex?: RegExp
15
+ fastify?: {
16
+ /** Enable compression */
17
+ compression?: boolean;
18
+ /** Filter for which request URLs invoke Gasket middleware */
19
+ middlewareInclusionRegex?: RegExp;
20
+ /** @deprecated */
21
+ excludedRoutesRegex?: RegExp;
22
+ /** Trust proxy configuration */
23
+ trustProxy?: FastifyServerOptions['trustProxy'];
24
+ /** Glob pattern for source files setting up fastify routes */
25
+ routes?: Array<MaybeAsync<(app: FastifyInstance<Http2SecureServer, Http2ServerRequest, Http2ServerResponse>) => void>>;
26
+ };
27
+ /** Middleware configuration */
28
+ middleware?: {
29
+ /** Plugin name */
30
+ plugin: string;
31
+ /** Paths for middleware */
32
+ paths?: (string | RegExp)[];
33
+ }[];
8
34
  }
9
35
 
10
- // The middie middleware is added for express compatibility
11
- type Handler = (
12
- req: FastifyRequest,
13
- res: FastifyReply,
14
- next: (error?: Error) => void
15
- ) => void;
36
+ /**
37
+ * Handler function type - The middie middleware is added for express
38
+ * compatibility
39
+ */
40
+ type Handler = (req: any, res: any, next: (error?: Error) => void) => void;
41
+
42
+ /** Error handler function type */
16
43
  type ErrorHandler = (
17
44
  error: Error,
18
45
  req: FastifyRequest,
@@ -21,8 +48,33 @@ declare module '@gasket/engine' {
21
48
  ) => void;
22
49
 
23
50
  export interface HookExecTypes {
24
- middleware(fastify: FastifyInstance): MaybeAsync<MaybeMultiple<Handler>>,
25
- fastify(fastify: FastifyInstance): MaybeAsync<void>,
26
- errorMiddleware(fastify: FastifyInstance): MaybeAsync<MaybeMultiple<ErrorHandler>>
51
+ middleware(
52
+ app: FastifyInstance<Http2SecureServer, Http2ServerRequest, Http2ServerResponse>
53
+ ): MaybeAsync<MaybeMultiple<Handler> & { paths?: (string | RegExp)[] }>;
54
+ fastify(app: FastifyInstance<Http2SecureServer, Http2ServerRequest, Http2ServerResponse>): MaybeAsync<void>;
55
+ errorMiddleware(): MaybeAsync<MaybeMultiple<ErrorHandler>>;
56
+ }
57
+ }
58
+
59
+ type FastifyLogger = Logger & {
60
+ trace?: () => MaybeAsync<any>,
61
+ fatal?: () => MaybeAsync<any>
62
+ }
63
+
64
+ export function alignLogger(
65
+ logger: Logger
66
+ ): FastifyLogger
67
+
68
+ declare module 'create-gasket-app' {
69
+ export interface CreateContext {
70
+ /** Flag indicating if API app is enabled */
71
+ apiApp?: boolean;
27
72
  }
28
73
  }
74
+
75
+ const plugin: Plugin = {
76
+ name: '@gasket/plugin-fastify',
77
+ hooks: {}
78
+ };
79
+
80
+ export = plugin;
package/lib/index.js CHANGED
@@ -1,161 +1,82 @@
1
- const debug = require('diagnostics')('gasket:fastify');
2
- const { peerDependencies, name } = require('../package.json');
1
+ /// <reference types="@gasket/core" />
2
+ /// <reference types="@gasket/plugin-metadata" />
3
3
 
4
- module.exports = {
4
+ const {
5
5
  name,
6
- hooks: {
7
- /**
8
- * Add files & extend package.json for new apps.
9
- *
10
- * @param {Gasket} gasket - The gasket API.
11
- * @param {CreateContext} context - Create context
12
- * @param {PackageJson} context.pkg - The Gasket PackageJson API.
13
- * @public
14
- */
15
- create: async function create(gasket, context) {
16
- const generatorDir = `${ __dirname }/../generator`;
17
-
18
- context.pkg.add('dependencies', {
19
- fastify: peerDependencies.fastify
20
- });
21
-
22
- if (context.apiApp) {
23
- context.files.add(`${ generatorDir }/**/*`);
24
-
25
- context.gasketConfig.add('fastify', {
26
- routes: './routes/*'
27
- });
28
- }
29
- },
30
- /**
31
- * Create the Fastify instance and setup the lifecycle hooks.
32
- * Fastify is compatible with express middleware out of the box, so we can
33
- * use the same middleware lifecycles.
34
- *
35
- * @param {Gasket} gasket Gasket API.
36
- * @param {Object} serverOpts Server options.
37
- * @returns {Express} The web server.
38
- * @public
39
- */
40
- // eslint-disable-next-line max-statements
41
- createServers: async function createServers(gasket, serverOpts) {
42
- const fastify = require('fastify');
43
- const middie = require('middie');
44
- const cookieParser = require('cookie-parser');
45
- const compression = require('compression');
46
-
47
- const { logger, config } = gasket;
48
- const { middleware: middlewareConfig } = config;
49
- const trustProxy = config.fastify?.trustProxy ?? false;
50
- const excludedRoutesRegex = config.fastify && config.fastify.excludedRoutesRegex;
51
- const app = fastify({ logger, trustProxy });
52
-
53
- // Enable middleware for fastify@3
54
- await app.register(middie);
55
-
56
- // Add express-like `res.locals` object attaching data
57
- app.use(function attachLocals(req, res, next) {
58
- res.locals = {};
59
- next();
60
- });
61
-
62
- if (excludedRoutesRegex) {
63
- app.use(excludedRoutesRegex, cookieParser());
64
- } else {
65
- app.use(cookieParser());
66
- }
67
-
68
- const { compression: compressionConfig = true } = config.fastify || {};
69
- if (compressionConfig) {
70
- app.use(compression());
71
- }
72
-
73
- const middlewares = [];
74
- await gasket.execApply('middleware', async (plugin, handler) => {
75
- const middleware = await handler(app);
76
- if (middleware) {
77
- if (middlewareConfig) {
78
- const pluginName = plugin && plugin.name ? plugin.name : '';
79
- const mwConfig = middlewareConfig.find(mw => mw.plugin === pluginName);
80
- if (mwConfig) {
81
- middleware.paths = mwConfig.paths;
82
- if (excludedRoutesRegex) {
83
- middleware.paths.push(excludedRoutesRegex);
84
- }
85
- }
86
- }
87
- middlewares.push(middleware);
88
- }
89
- });
6
+ version,
7
+ description
8
+ } = require('../package.json');
9
+ const create = require('./create');
10
+ const createServers = require('./create-servers');
90
11
 
91
- debug('applied %s middleware layers to fastify', middlewares.length);
92
- middlewares.forEach(layer => {
93
- const { paths } = layer;
94
- if (paths) {
95
- app.use(paths, layer);
96
- } else if (excludedRoutesRegex) {
97
- app.use(excludedRoutesRegex, layer);
98
- } else {
99
- app.use(layer);
100
- }
101
- });
102
-
103
- // allow consuming apps to directly append options to their server
104
- await gasket.exec('fastify', app);
105
-
106
- const postRenderingStacks = (await gasket.exec('errorMiddleware')).filter(Boolean);
107
- postRenderingStacks.forEach(stack => app.use(stack));
108
-
109
- return {
110
- ...serverOpts,
111
- handler: async function handler(...args) {
112
- await app.ready();
113
- app.server.emit('request', ...args);
114
- }
115
- };
116
- },
12
+ /** @type {import('@gasket/core').Plugin} */
13
+ const plugin = {
14
+ name,
15
+ version,
16
+ description,
17
+ hooks: {
18
+ create,
19
+ createServers,
117
20
  metadata(gasket, meta) {
118
21
  return {
119
22
  ...meta,
120
- lifecycles: [{
121
- name: 'middleware',
122
- method: 'exec',
123
- description: 'Add Express style middleware for Fastify',
124
- link: 'README.md#middleware',
125
- parent: 'createServers'
126
- }, {
127
- name: 'fastify',
128
- method: 'exec',
129
- description: 'Modify the Fastify instance to for adding endpoints',
130
- link: 'README.md#express',
131
- parent: 'createServers',
132
- after: 'middleware'
133
- }, {
134
- name: 'errorMiddleware',
135
- method: 'exec',
136
- description: 'Add Express style middleware for handling errors with Fastify',
137
- link: 'README.md#errorMiddleware',
138
- parent: 'createServers',
139
- after: 'express'
140
- }],
141
- configurations: [{
142
- name: 'fastify',
143
- link: 'README.md#configuration',
144
- description: 'Fastify configuration object',
145
- type: 'object'
146
- }, {
147
- name: 'fastify.compression',
148
- link: 'README.md#configuration',
149
- description: 'Automatic compression',
150
- type: 'boolean',
151
- default: true
152
- }, {
153
- name: 'fastify.excludedRoutesRegex',
154
- link: 'README.md#configuration',
155
- description: 'Routes to be excluded based on a regex',
156
- type: 'RegExp'
157
- }]
23
+ actions: [
24
+ {
25
+ name: 'getFastifyApp',
26
+ description: 'Get the Fastify app instance',
27
+ link: 'README.md'
28
+ }
29
+ ],
30
+ lifecycles: [
31
+ {
32
+ name: 'middleware',
33
+ method: 'exec',
34
+ description: 'Add Express style middleware for Fastify',
35
+ link: 'README.md#middleware',
36
+ parent: 'createServers'
37
+ },
38
+ {
39
+ name: 'fastify',
40
+ method: 'exec',
41
+ description: 'Modify the Fastify instance to for adding endpoints',
42
+ link: 'README.md#express',
43
+ parent: 'createServers',
44
+ after: 'middleware'
45
+ },
46
+ {
47
+ name: 'errorMiddleware',
48
+ method: 'exec',
49
+ description:
50
+ 'Add Express style middleware for handling errors with Fastify',
51
+ link: 'README.md#errorMiddleware',
52
+ parent: 'createServers',
53
+ after: 'express'
54
+ }
55
+ ],
56
+ configurations: [
57
+ {
58
+ name: 'fastify',
59
+ link: 'README.md#configuration',
60
+ description: 'Fastify configuration object',
61
+ type: 'object'
62
+ },
63
+ {
64
+ name: 'fastify.compression',
65
+ link: 'README.md#configuration',
66
+ description: 'Automatic compression',
67
+ type: 'boolean',
68
+ default: true
69
+ },
70
+ {
71
+ name: 'fastify.excludedRoutesRegex',
72
+ link: 'README.md#configuration',
73
+ description: 'Routes to be excluded based on a regex',
74
+ type: 'RegExp'
75
+ }
76
+ ]
158
77
  };
159
78
  }
160
79
  }
161
80
  };
81
+
82
+ module.exports = plugin;
package/lib/utils.js ADDED
@@ -0,0 +1,25 @@
1
+ /* eslint-disable no-console */
2
+ const fallbackMap = {
3
+ fatal: 'error',
4
+ trace: 'debug'
5
+ };
6
+
7
+ /**
8
+ * A helper function to ensure that all the required log levels
9
+ * for a Fastify server are present.
10
+ * @type {import('./index').alignLogger}
11
+ */
12
+ function alignLogger(logger) {
13
+ const fastifyLogger = logger;
14
+ ['fatal', 'trace'].map(level => {
15
+ if (!logger[level]) {
16
+ fastifyLogger[level] = logger[fallbackMap[level]];
17
+ }
18
+ });
19
+
20
+ return fastifyLogger;
21
+ }
22
+
23
+ module.exports = {
24
+ alignLogger
25
+ };
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@gasket/plugin-fastify",
3
- "version": "7.0.0-next.6",
3
+ "version": "7.0.0-next.61",
4
4
  "description": "Adds fastify support to your application",
5
- "main": "lib",
5
+ "main": "lib/index.js",
6
6
  "types": "lib/index.d.ts",
7
7
  "files": [
8
8
  "lib"
@@ -13,7 +13,9 @@
13
13
  "test": "cross-env NODE_OPTIONS='--unhandled-rejections=strict' jest",
14
14
  "test:watch": "jest --watch",
15
15
  "test:coverage": "jest --coverage",
16
- "posttest": "npm run lint"
16
+ "posttest": "npm run lint && npm run typecheck",
17
+ "typecheck": "tsc",
18
+ "typecheck:watch": "tsc --watch"
17
19
  },
18
20
  "repository": {
19
21
  "type": "git",
@@ -36,33 +38,31 @@
36
38
  "url": "https://github.com/godaddy/gasket/issues"
37
39
  },
38
40
  "homepage": "https://github.com/godaddy/gasket/tree/main/packages/gasket-plugin-fastify",
39
- "dependencies": {
40
- "compression": "^1.7.4",
41
- "cookie-parser": "^1.4.6",
42
- "diagnostics": "^2.0.2",
43
- "middie": "^5.4.0"
44
- },
45
41
  "devDependencies": {
46
- "@gasket/engine": "^7.0.0-next.6",
42
+ "@gasket/core": "7.0.0-next.61",
47
43
  "cross-env": "^7.0.3",
48
44
  "eslint": "^8.56.0",
49
- "eslint-config-godaddy": "^7.0.2",
50
- "eslint-plugin-jest": "^27.6.3",
45
+ "eslint-config-godaddy": "^7.1.1",
46
+ "eslint-plugin-jest": "^28.6.0",
51
47
  "eslint-plugin-json": "^3.1.0",
52
- "eslint-plugin-unicorn": "^44.0.0",
53
- "fastify": "^3.3.0",
54
- "jest": "^29.7.0"
48
+ "eslint-plugin-unicorn": "^55.0.0",
49
+ "fastify": "^4.28.1",
50
+ "http2": "^3.3.7",
51
+ "jest": "^29.7.0",
52
+ "typescript": "^5.4.5"
55
53
  },
56
54
  "peerDependencies": {
57
- "fastify": "^3.0.0"
55
+ "fastify": "^3 || ^4"
58
56
  },
59
57
  "eslintConfig": {
60
58
  "extends": [
61
59
  "godaddy",
62
- "plugin:jest/recommended"
60
+ "plugin:jest/recommended",
61
+ "plugin:jsdoc/recommended-typescript-flavor"
63
62
  ],
64
63
  "plugins": [
65
- "unicorn"
64
+ "unicorn",
65
+ "jsdoc"
66
66
  ],
67
67
  "rules": {
68
68
  "unicorn/filename-case": "error"
@@ -71,5 +71,5 @@
71
71
  "eslintIgnore": [
72
72
  "generator"
73
73
  ],
74
- "gitHead": "805a1026959d8aa783ee32be8a8ff76c06badd2f"
74
+ "gitHead": "6bfc613e64088429e95e89211008b1c9ab530ca7"
75
75
  }