@wooksjs/express-adapter 0.2.0 → 0.3.0

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
@@ -3,7 +3,7 @@
3
3
  **!!! This is work-in-progress library, breaking changes are expected !!!**
4
4
 
5
5
  <p align="center">
6
- <img src="./docs/icon.png" height="156px"><br>
6
+ <img src="./docs/wooksjs-express.png" height="156px"><br>
7
7
  <a href="https://github.com/wooksjs/express-adapter/blob/main/LICENSE">
8
8
  <img src="https://img.shields.io/badge/License-MIT-green?style=for-the-badge" />
9
9
  </a>
@@ -17,6 +17,10 @@ Want to use [@wooksjs/event-http](https://www.npmjs.com/package/@wooksjs/event-h
17
17
 
18
18
  ## Usage
19
19
 
20
+ There are two options to use express with wooks
21
+
22
+ ### 1. Adapter for express API:
23
+ This one will modify express `get`, `post`, ..., methods. Take this one if you want to keep using express app API.
20
24
  ```ts
21
25
  import express from 'express'
22
26
  import { applyExpressAdapter } from '@wooksjs/express-adapter'
@@ -44,3 +48,37 @@ app.get('/error', () => {
44
48
 
45
49
  app.listen(3000, () => console.log('listening 3000'))
46
50
  ```
51
+
52
+ ### 2. Adapter for WooksHttp API:
53
+ This one does not modify anything. It just applies express middleware and reroutes requests through wooks. Use this one if you want to use wooks app API (compatible with [@moostjs/event-http](https://www.npmjs.com/package/@moostjs/event-http))
54
+
55
+ ```ts
56
+ import express from 'express'
57
+ import { WooksExpress } from '@wooksjs/express-adapter'
58
+ import { useBody } from '@wooksjs/http-body'
59
+ import { HttpError } from '@wooksjs/event-http'
60
+ import { useRouteParams } from '@wooksjs/event-core'
61
+
62
+ const expressApp = express()
63
+
64
+ const wooksApp = new WooksExpress(expressApp, { raise404: true })
65
+
66
+ wooksApp.get('/test/:param', () => {
67
+ const { get } = useRouteParams()
68
+ return { message: 'it works', param: get('param') }
69
+ })
70
+
71
+ wooksApp.post('/post', () => {
72
+ const { parseBody } = useBody()
73
+ return parseBody()
74
+ })
75
+
76
+ wooksApp.get('/error', () => {
77
+ throw new HttpError(400, 'test error')
78
+ })
79
+
80
+ wooksApp.listen(3000, () => console.log('listening 3000'))
81
+ ```
82
+
83
+
84
+ ⚠️ Check out official [wooks documentation](https://wooksjs.org/guide/http/express.html).
package/dist/index.cjs CHANGED
@@ -12,7 +12,7 @@ const methods = [
12
12
  "head",
13
13
  "all"
14
14
  ];
15
- function applyExpressAdapter(app) {
15
+ function applyExpressAdapter(app, eventOptions) {
16
16
  const responder = eventHttp.createWooksResponder();
17
17
  function useWooksDecorator(fn) {
18
18
  return async () => {
@@ -28,7 +28,7 @@ function applyExpressAdapter(app) {
28
28
  clearCtx();
29
29
  };
30
30
  }
31
- app.use(wooksContext);
31
+ app.use(wooksContext(eventOptions));
32
32
  for (const m of methods) {
33
33
  const defFn = app[m].bind(app);
34
34
  const newFn = ((...args) => {
@@ -37,14 +37,65 @@ function applyExpressAdapter(app) {
37
37
  Object.defineProperty(app, m, { value: newFn });
38
38
  }
39
39
  }
40
- function wooksContext(req, res, next) {
41
- const { store } = eventHttp.createHttpContext({ req, res });
42
- store("routeParams").value = new Proxy({}, {
43
- get(target, prop, receiver) {
44
- return req.params && req.params[prop];
45
- }
46
- });
47
- next();
40
+ function wooksContext(eventOptions) {
41
+ return (req, res, next) => {
42
+ const { store } = eventHttp.createHttpContext({ req, res }, eventOptions || {});
43
+ store("routeParams").value = new Proxy({}, {
44
+ get(target, prop, receiver) {
45
+ return req.params && req.params[prop];
46
+ }
47
+ });
48
+ next();
49
+ };
50
+ }
51
+
52
+ class WooksExpress extends eventHttp.WooksHttp {
53
+ constructor(expressApp, opts) {
54
+ super(opts);
55
+ this.expressApp = expressApp;
56
+ this.opts = opts;
57
+ expressApp.use(this.getServerCb());
58
+ }
59
+ async listen(...args) {
60
+ const server = this.server = this.expressApp.listen(...args);
61
+ return new Promise((resolve, reject) => {
62
+ server.once("listening", resolve);
63
+ server.once("error", reject);
64
+ });
65
+ }
66
+ getServerCb() {
67
+ return async (req, res, next) => {
68
+ const { restoreCtx, clearCtx } = eventHttp.createHttpContext(
69
+ { req, res },
70
+ this.mergeEventOptions(this.opts?.eventOptions)
71
+ );
72
+ const { handlers } = this.wooks.lookup(req.method, req.url);
73
+ if (handlers || this.opts?.onNotFound) {
74
+ try {
75
+ await this.processHandlers(handlers || [this.opts?.onNotFound]);
76
+ } catch (e) {
77
+ console.error("Internal error, please report: ", e);
78
+ if (e.stack) {
79
+ console.warn(e.stack);
80
+ }
81
+ restoreCtx();
82
+ this.respond(e);
83
+ clearCtx();
84
+ }
85
+ } else {
86
+ this.logger.debug(
87
+ `404 Not found (${req.method})${req.url}`
88
+ );
89
+ if (this.opts?.raise404) {
90
+ this.respond(new eventHttp.HttpError(404));
91
+ clearCtx();
92
+ } else if (next) {
93
+ next();
94
+ }
95
+ }
96
+ };
97
+ }
48
98
  }
49
99
 
100
+ exports.WooksExpress = WooksExpress;
50
101
  exports.applyExpressAdapter = applyExpressAdapter;
package/dist/index.d.ts CHANGED
@@ -1,5 +1,19 @@
1
- import { Express } from 'express';
1
+ import { TWooksHttpOptions, WooksHttp } from '@wooksjs/event-http';
2
+ import Express$1, { Express } from 'express';
3
+ import { Server, IncomingMessage, ServerResponse } from 'http';
2
4
 
3
- declare function applyExpressAdapter(app: Express): void;
5
+ declare function applyExpressAdapter(app: Express, eventOptions?: TWooksHttpOptions['eventOptions']): void;
4
6
 
5
- export { applyExpressAdapter };
7
+ declare class WooksExpress extends WooksHttp {
8
+ protected expressApp: Express$1.Application;
9
+ protected opts?: (TWooksHttpOptions & {
10
+ raise404?: boolean | undefined;
11
+ }) | undefined;
12
+ constructor(expressApp: Express$1.Application, opts?: (TWooksHttpOptions & {
13
+ raise404?: boolean | undefined;
14
+ }) | undefined);
15
+ listen(...args: Parameters<Server['listen']>): Promise<unknown>;
16
+ getServerCb(): (req: IncomingMessage, res: ServerResponse, next?: Express$1.NextFunction) => Promise<void>;
17
+ }
18
+
19
+ export { WooksExpress, applyExpressAdapter };
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { createWooksResponder, createHttpContext, useHttpContext } from '@wooksjs/event-http';
1
+ import { createWooksResponder, createHttpContext, useHttpContext, WooksHttp, HttpError } from '@wooksjs/event-http';
2
2
 
3
3
  const methods = [
4
4
  "get",
@@ -10,7 +10,7 @@ const methods = [
10
10
  "head",
11
11
  "all"
12
12
  ];
13
- function applyExpressAdapter(app) {
13
+ function applyExpressAdapter(app, eventOptions) {
14
14
  const responder = createWooksResponder();
15
15
  function useWooksDecorator(fn) {
16
16
  return async () => {
@@ -26,7 +26,7 @@ function applyExpressAdapter(app) {
26
26
  clearCtx();
27
27
  };
28
28
  }
29
- app.use(wooksContext);
29
+ app.use(wooksContext(eventOptions));
30
30
  for (const m of methods) {
31
31
  const defFn = app[m].bind(app);
32
32
  const newFn = ((...args) => {
@@ -35,14 +35,64 @@ function applyExpressAdapter(app) {
35
35
  Object.defineProperty(app, m, { value: newFn });
36
36
  }
37
37
  }
38
- function wooksContext(req, res, next) {
39
- const { store } = createHttpContext({ req, res });
40
- store("routeParams").value = new Proxy({}, {
41
- get(target, prop, receiver) {
42
- return req.params && req.params[prop];
43
- }
44
- });
45
- next();
38
+ function wooksContext(eventOptions) {
39
+ return (req, res, next) => {
40
+ const { store } = createHttpContext({ req, res }, eventOptions || {});
41
+ store("routeParams").value = new Proxy({}, {
42
+ get(target, prop, receiver) {
43
+ return req.params && req.params[prop];
44
+ }
45
+ });
46
+ next();
47
+ };
48
+ }
49
+
50
+ class WooksExpress extends WooksHttp {
51
+ constructor(expressApp, opts) {
52
+ super(opts);
53
+ this.expressApp = expressApp;
54
+ this.opts = opts;
55
+ expressApp.use(this.getServerCb());
56
+ }
57
+ async listen(...args) {
58
+ const server = this.server = this.expressApp.listen(...args);
59
+ return new Promise((resolve, reject) => {
60
+ server.once("listening", resolve);
61
+ server.once("error", reject);
62
+ });
63
+ }
64
+ getServerCb() {
65
+ return async (req, res, next) => {
66
+ const { restoreCtx, clearCtx } = createHttpContext(
67
+ { req, res },
68
+ this.mergeEventOptions(this.opts?.eventOptions)
69
+ );
70
+ const { handlers } = this.wooks.lookup(req.method, req.url);
71
+ if (handlers || this.opts?.onNotFound) {
72
+ try {
73
+ await this.processHandlers(handlers || [this.opts?.onNotFound]);
74
+ } catch (e) {
75
+ console.error("Internal error, please report: ", e);
76
+ if (e.stack) {
77
+ console.warn(e.stack);
78
+ }
79
+ restoreCtx();
80
+ this.respond(e);
81
+ clearCtx();
82
+ }
83
+ } else {
84
+ this.logger.debug(
85
+ `404 Not found (${req.method})${req.url}`
86
+ );
87
+ if (this.opts?.raise404) {
88
+ this.respond(new HttpError(404));
89
+ clearCtx();
90
+ } else if (next) {
91
+ next();
92
+ }
93
+ }
94
+ };
95
+ }
46
96
  }
47
97
 
48
- export { applyExpressAdapter };
98
+ export { WooksExpress, applyExpressAdapter };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wooksjs/express-adapter",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Express Adapter for Wooks Composables",
5
5
  "main": "dist/index.cjs",
6
6
  "module": "dist/index.mjs",
@@ -59,7 +59,8 @@
59
59
  },
60
60
  "homepage": "https://github.com/wooksjs/express-adapter#readme",
61
61
  "peerDependencies": {
62
- "@wooksjs/event-http": "^0.2.9",
62
+ "@wooksjs/event-http": "^0.3.0",
63
+ "wooks": "^0.3.0",
63
64
  "express": "^4.0.0"
64
65
  },
65
66
  "devDependencies": {
@@ -69,8 +70,8 @@
69
70
  "@types/node": "^18.11.0",
70
71
  "@typescript-eslint/eslint-plugin": "^5.42.0",
71
72
  "@typescript-eslint/parser": "^5.0.0",
72
- "@wooksjs/event-http": "^0.2.9",
73
- "@wooksjs/http-body": "^0.2.9",
73
+ "@wooksjs/event-http": "^0.3.0",
74
+ "@wooksjs/http-body": "^0.3.0",
74
75
  "conventional-changelog": "^3.1.24",
75
76
  "conventional-changelog-cli": "^2.1.1",
76
77
  "enquirer": "^2.3.6",