@modern-js/plugin-express 1.4.4 → 1.5.2

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/CHANGELOG.md CHANGED
@@ -1,5 +1,62 @@
1
1
  # @modern-js/plugin-express
2
2
 
3
+ ## 1.5.2
4
+
5
+ ### Patch Changes
6
+
7
+ - 895fa0ff: chore: using "workspace:\*" in devDependencies
8
+ - Updated dependencies [2d155c4c]
9
+ - Updated dependencies [123e432d]
10
+ - Updated dependencies [e5a9b26d]
11
+ - Updated dependencies [0b26b93b]
12
+ - Updated dependencies [123e432d]
13
+ - Updated dependencies [f9f66ef9]
14
+ - Updated dependencies [592edabc]
15
+ - Updated dependencies [895fa0ff]
16
+ - Updated dependencies [3d1fac2a]
17
+ - Updated dependencies [3578913e]
18
+ - Updated dependencies [1c3beab3]
19
+ - @modern-js/utils@1.6.0
20
+ - @modern-js/bff-utils@1.2.4
21
+ - @modern-js/types@1.5.1
22
+
23
+ ## 1.5.1
24
+
25
+ ### Patch Changes
26
+
27
+ - 04ae5262: chore: bump @modern-js/utils to v1.4.1 in dependencies
28
+ - 60f7d8bf: feat: add tests dir to npmignore
29
+ - befd9e5b: fix: compatible with babel-plugin-resolver's handling of relative paths on windows
30
+ - 305e0bb4: fix: commander.commandsMap typing not work
31
+ - Updated dependencies [b8599d09]
32
+ - Updated dependencies [6cffe99d]
33
+ - Updated dependencies [04ae5262]
34
+ - Updated dependencies [60f7d8bf]
35
+ - Updated dependencies [befd9e5b]
36
+ - Updated dependencies [3bf4f8b0]
37
+ - @modern-js/utils@1.5.0
38
+ - @modern-js/adapter-helpers@1.2.3
39
+ - @modern-js/bff-runtime@1.2.2
40
+ - @modern-js/bff-utils@1.2.3
41
+ - @modern-js/types@1.5.0
42
+
43
+ ## 1.5.0
44
+
45
+ ### Minor Changes
46
+
47
+ - d2d1d6b2: feat: support server config
48
+
49
+ ### Patch Changes
50
+
51
+ - Updated dependencies [77ff9754]
52
+ - Updated dependencies [d2d1d6b2]
53
+ - Updated dependencies [07a4887e]
54
+ - Updated dependencies [ea2ae711]
55
+ - Updated dependencies [17d0cc46]
56
+ - Updated dependencies [d2d1d6b2]
57
+ - @modern-js/utils@1.4.0
58
+ - @modern-js/types@1.4.0
59
+
3
60
  ## 1.4.4
4
61
 
5
62
  ### Patch Changes
@@ -1,5 +1,6 @@
1
1
  import * as path from 'path';
2
2
  import { createRuntimeExportsUtils } from '@modern-js/utils';
3
+ import { getRelativeRuntimePath } from '@modern-js/adapter-helpers';
3
4
  export default (() => ({
4
5
  name: '@modern-js/plugin-express',
5
6
  setup: api => {
@@ -16,14 +17,8 @@ export default (() => ({
16
17
  appDirectory
17
18
  } = appContext;
18
19
  bffExportsUtils = createRuntimeExportsUtils(appContext.internalDirectory, 'server');
19
- const serverRuntimePath = bffExportsUtils.getPath(); // Look up one level, because the artifacts after build have dist directories
20
-
21
- let relativeRuntimePath = path.join('../', path.relative(appDirectory, serverRuntimePath));
22
-
23
- if (process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test') {
24
- relativeRuntimePath = `./${path.relative(appDirectory, serverRuntimePath)}`;
25
- }
26
-
20
+ const serverRuntimePath = bffExportsUtils.getPath();
21
+ const relativeRuntimePath = getRelativeRuntimePath(appDirectory, serverRuntimePath);
27
22
  return {
28
23
  source: {
29
24
  alias: {
@@ -74,8 +74,7 @@ export default (() => ({
74
74
  middleware
75
75
  } = config;
76
76
  initMiddlewares(middleware, app);
77
- } // eslint-disable-next-line react-hooks/rules-of-hooks
78
-
77
+ }
79
78
 
80
79
  useRun(app);
81
80
  registerRoutes(app);
@@ -88,8 +87,7 @@ export default (() => ({
88
87
  middleware
89
88
  } = config;
90
89
  initMiddlewares(middleware, app);
91
- } // eslint-disable-next-line react-hooks/rules-of-hooks
92
-
90
+ }
93
91
 
94
92
  useRun(app);
95
93
  registerRoutes(app);
@@ -9,6 +9,8 @@ var path = _interopRequireWildcard(require("path"));
9
9
 
10
10
  var _utils = require("@modern-js/utils");
11
11
 
12
+ var _adapterHelpers = require("@modern-js/adapter-helpers");
13
+
12
14
  function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
13
15
 
14
16
  function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
@@ -29,14 +31,8 @@ var _default = () => ({
29
31
  appDirectory
30
32
  } = appContext;
31
33
  bffExportsUtils = (0, _utils.createRuntimeExportsUtils)(appContext.internalDirectory, 'server');
32
- const serverRuntimePath = bffExportsUtils.getPath(); // Look up one level, because the artifacts after build have dist directories
33
-
34
- let relativeRuntimePath = path.join('../', path.relative(appDirectory, serverRuntimePath));
35
-
36
- if (process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test') {
37
- relativeRuntimePath = `./${path.relative(appDirectory, serverRuntimePath)}`;
38
- }
39
-
34
+ const serverRuntimePath = bffExportsUtils.getPath();
35
+ const relativeRuntimePath = (0, _adapterHelpers.getRelativeRuntimePath)(appDirectory, serverRuntimePath);
40
36
  return {
41
37
  source: {
42
38
  alias: {
@@ -95,8 +95,7 @@ var _default = () => ({
95
95
  middleware
96
96
  } = config;
97
97
  initMiddlewares(middleware, app);
98
- } // eslint-disable-next-line react-hooks/rules-of-hooks
99
-
98
+ }
100
99
 
101
100
  useRun(app);
102
101
  (0, _registerRoutes.default)(app);
@@ -109,8 +108,7 @@ var _default = () => ({
109
108
  middleware
110
109
  } = config;
111
110
  initMiddlewares(middleware, app);
112
- } // eslint-disable-next-line react-hooks/rules-of-hooks
113
-
111
+ }
114
112
 
115
113
  useRun(app);
116
114
  (0, _registerRoutes.default)(app);
package/package.json CHANGED
@@ -11,7 +11,7 @@
11
11
  "modern",
12
12
  "modern.js"
13
13
  ],
14
- "version": "1.4.4",
14
+ "version": "1.5.2",
15
15
  "jsnext:source": "./src/index.ts",
16
16
  "types": "./dist/types/index.d.ts",
17
17
  "main": "./dist/js/node/index.js",
@@ -34,18 +34,22 @@
34
34
  },
35
35
  "dependencies": {
36
36
  "@babel/runtime": "^7.15.3",
37
- "@modern-js/adapter-helpers": "^1.2.1",
38
- "@modern-js/utils": "^1.3.7",
37
+ "@modern-js/adapter-helpers": "^1.2.3",
38
+ "@modern-js/bff-runtime": "^1.2.2",
39
+ "@modern-js/bff-utils": "^1.2.4",
40
+ "@modern-js/types": "^1.5.1",
41
+ "@modern-js/utils": "^1.6.0",
39
42
  "cookie-parser": "^1.4.5",
40
43
  "finalhandler": "^1.1.2",
41
44
  "formidable": "^1.2.2",
42
- "type-is": "^1.6.18",
43
- "@modern-js/bff-utils": "^1.2.2",
44
- "@modern-js/bff-runtime": "^1.2.1"
45
+ "type-is": "^1.6.18"
45
46
  },
46
47
  "devDependencies": {
47
- "express": "^4.17.1",
48
- "@modern-js/server-utils": "^1.2.2",
48
+ "@modern-js/core": "1.9.0",
49
+ "@modern-js/server-core": "1.3.2",
50
+ "@modern-js/server-utils": "1.2.4",
51
+ "@scripts/build": "0.0.0",
52
+ "@scripts/jest-config": "0.0.0",
49
53
  "@types/cookie-parser": "^1.4.2",
50
54
  "@types/express": "^4.17.13",
51
55
  "@types/finalhandler": "^1.1.1",
@@ -54,13 +58,10 @@
54
58
  "@types/node": "^14",
55
59
  "@types/supertest": "^2.0.11",
56
60
  "@types/type-is": "^1.6.3",
57
- "supertest": "^6.1.6",
58
- "typescript": "^4",
59
- "@modern-js/core": "1.6.1",
60
- "@scripts/build": "0.0.0",
61
+ "express": "^4.17.1",
61
62
  "jest": "^27",
62
- "@modern-js/server-core": "1.2.5",
63
- "@scripts/jest-config": "0.0.0"
63
+ "supertest": "^6.1.6",
64
+ "typescript": "^4"
64
65
  },
65
66
  "modernConfig": {
66
67
  "output": {
@@ -1,6 +0,0 @@
1
- module.exports = {
2
- extends: ['@modern-js'],
3
- parserOptions: {
4
- project: require.resolve('./tsconfig.json'),
5
- },
6
- };
package/tests/common.ts DELETED
@@ -1,7 +0,0 @@
1
- // globby needs setImmediate
2
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
3
- // @ts-expect-error
4
- global.setImmediate = setTimeout;
5
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
6
- // @ts-expect-error
7
- global.clearImmediate = clearTimeout;
@@ -1,3 +0,0 @@
1
- export const get = () => ({ message: 'hello' });
2
-
3
- export const post = () => 'hello';
@@ -1,31 +0,0 @@
1
- // eslint-disable-next-line eslint-comments/disable-enable-pair
2
- /* eslint-disable react-hooks/rules-of-hooks */
3
- import { match } from '@modern-js/bff-runtime';
4
- import { useContext } from '../../../../../src/context';
5
-
6
- export const get = ({ query }: { query: Record<string, unknown> }) => {
7
- return { query };
8
- };
9
-
10
- export const post = ({ data }: { data: Record<string, unknown> }) => {
11
- const { req } = useContext();
12
- const { cookies } = req;
13
- return {
14
- query: req.query,
15
- data,
16
- cookies,
17
- };
18
- };
19
-
20
- export const patch = match(
21
- {
22
- request: {
23
- data: {
24
- id: Number,
25
- name: String,
26
- },
27
- },
28
- response: { id: Number },
29
- },
30
- ({ data: { id } }) => ({ id }),
31
- );
@@ -1,4 +0,0 @@
1
- export const post = ({ formData }) => ({
2
- message: 'success',
3
- formData,
4
- });
@@ -1 +0,0 @@
1
- // don't delete the file
@@ -1 +0,0 @@
1
- export const get = async () => ({ message: 'hello' });
@@ -1 +0,0 @@
1
- export const post = (id: string) => ({ id });
@@ -1,31 +0,0 @@
1
- // eslint-disable-next-line eslint-comments/disable-enable-pair
2
- /* eslint-disable react-hooks/rules-of-hooks */
3
- import { match } from '@modern-js/bff-runtime';
4
- import { useContext } from '../../../../../../src/context';
5
-
6
- export const get = ({ query }: { query: Record<string, unknown> }) => ({
7
- query,
8
- });
9
-
10
- export const post = ({ data }: { data: Record<string, unknown> }) => {
11
- const { req } = useContext();
12
- const { cookies } = req;
13
- return {
14
- query: req.query,
15
- data,
16
- cookies,
17
- };
18
- };
19
-
20
- export const patch = match(
21
- {
22
- request: {
23
- data: {
24
- id: Number,
25
- name: String,
26
- },
27
- },
28
- response: { id: Number },
29
- },
30
- ({ data: { id } }) => ({ id }),
31
- );
@@ -1,4 +0,0 @@
1
- export const post = ({ formData }) => ({
2
- message: 'success',
3
- formData,
4
- });
File without changes
File without changes
@@ -1,108 +0,0 @@
1
- import * as path from 'path';
2
- import request from 'supertest';
3
- import { serverManager } from '@modern-js/server-core';
4
- import { INTROSPECTION_ROUTE_PATH } from '@modern-js/bff-utils';
5
- import plugin from '../src/plugin';
6
- import { APIPlugin } from './helpers';
7
- import './common';
8
-
9
- const pwd = path.join(__dirname, './fixtures/function-mode');
10
-
11
- describe('function-mode', () => {
12
- const id = '666';
13
- const name = 'modern';
14
- const foo = { id, name };
15
- let apiHandler: any;
16
-
17
- beforeAll(async () => {
18
- const runner = await serverManager
19
- .clone()
20
- .usePlugin(APIPlugin, plugin)
21
- .init();
22
- apiHandler = await runner.prepareApiServer({
23
- pwd,
24
- mode: 'function',
25
- });
26
- });
27
-
28
- test('should works', async () => {
29
- const res = await request(apiHandler).get('/hello');
30
- expect(res.status).toBe(200);
31
- expect(res.body).toEqual({ message: 'hello' });
32
- });
33
-
34
- test('should works with string result', async () => {
35
- const res = await request(apiHandler).post('/hello');
36
- expect(res.status).toBe(200);
37
- expect(res.body).toEqual('hello');
38
- });
39
-
40
- test('should works with query', async () => {
41
- const res = await request(apiHandler).get(`/nest/user?id=${id}`);
42
- expect(res.status).toBe(200);
43
- expect(res.body.query.id).toBe(id);
44
- });
45
-
46
- test('should works with body', async () => {
47
- const res = await request(apiHandler).post('/nest/user').send(foo);
48
- expect(res.status).toBe(200);
49
- expect(res.body.data).toEqual(foo);
50
- });
51
-
52
- test('should works with context', async () => {
53
- const res = await request(apiHandler).post(`/nest/user?id=${id}`).send(foo);
54
- expect(res.status).toBe(200);
55
- expect(res.body.data).toEqual(foo);
56
- expect(res.body.query.id).toBe(id);
57
- });
58
-
59
- test('should support cookies', async () => {
60
- const res = await request(apiHandler)
61
- .post(`/nest/user?id=${id}`)
62
- .set('Cookie', [`id=${id};name=${name}`]);
63
- expect(res.status).toBe(200);
64
- expect(res.body.cookies.id).toBe(id);
65
- expect(res.body.cookies.name).toBe(name);
66
- });
67
-
68
- test('should works with schema', async () => {
69
- const res = await request(apiHandler).patch('/nest/user').send({
70
- id: 777,
71
- name: 'xxx',
72
- });
73
- expect(res.status).toBe(200);
74
-
75
- const res2 = await request(apiHandler).patch('/nest/user').send({
76
- id: 'aaa',
77
- name: 'xxx',
78
- });
79
- expect(res2.status).toBe(400);
80
-
81
- const res3 = await request(apiHandler).patch('/nest/user').send({
82
- id: '777',
83
- name: 'xxx',
84
- });
85
- expect(res3.status).toBe(500);
86
- });
87
-
88
- test('introspection', async () => {
89
- const res = await request(apiHandler).get(INTROSPECTION_ROUTE_PATH);
90
- expect(res.status).toBe(200);
91
- expect(res.body.protocol).toBe('Farrow-API');
92
- });
93
-
94
- test('should support upload file', done => {
95
- request(apiHandler)
96
- .post('/upload')
97
- .field('my_field', 'value')
98
- .attach('file', __filename)
99
- .end(async (err, res) => {
100
- if (err) {
101
- throw err;
102
- }
103
- expect(res.statusCode).toBe(200);
104
- expect(res.body.message).toBe('success');
105
- done();
106
- });
107
- });
108
- });
package/tests/helpers.ts DELETED
@@ -1,14 +0,0 @@
1
- import path from 'path';
2
- import { createPlugin } from '@modern-js/server-core';
3
- import { injectAPIHandlerInfos, API_DIR } from '@modern-js/bff-utils';
4
-
5
- export const APIPlugin = createPlugin(() => ({
6
- prepareApiServer(props, next) {
7
- const { pwd, prefix } = props;
8
- const apiDir = path.resolve(pwd, API_DIR);
9
-
10
- injectAPIHandlerInfos(apiDir, prefix);
11
-
12
- return next(props);
13
- },
14
- }));
@@ -1,364 +0,0 @@
1
- import path from 'path';
2
- import express from 'express';
3
- import request from 'supertest';
4
- import { serverManager } from '@modern-js/server-core';
5
- import { INTROSPECTION_ROUTE_PATH } from '@modern-js/bff-utils';
6
- import plugin from '../src/plugin';
7
- import { APIPlugin } from './helpers';
8
- import './common';
9
-
10
- const pwd = path.join(__dirname, './fixtures/lambda-mode');
11
- const API_DIR = './api';
12
-
13
- describe('lambda-mode', () => {
14
- const id = '666';
15
- const name = 'modern';
16
- const prefix = '/api';
17
- const foo = { id, name };
18
- let apiHandler: any;
19
-
20
- beforeAll(async () => {
21
- const runner = await serverManager
22
- .clone()
23
- .usePlugin(APIPlugin, plugin)
24
- .init();
25
-
26
- apiHandler = await runner.prepareApiServer({
27
- pwd,
28
- mode: 'framework',
29
- prefix,
30
- });
31
- });
32
-
33
- test('should works', async () => {
34
- const res = await request(apiHandler).get(`${prefix}/hello`);
35
- expect(res.status).toBe(200);
36
- expect(res.body).toEqual({ message: 'hello' });
37
- });
38
-
39
- test('should works with query', async () => {
40
- const res = await request(apiHandler).get(`${prefix}/nest/user?id=${id}`);
41
- expect(res.status).toBe(200);
42
- expect(res.body.query.id).toBe(id);
43
- });
44
-
45
- test('should works with body', async () => {
46
- const res = await request(apiHandler).post(`${prefix}/nest/user`).send(foo);
47
- expect(res.status).toBe(200);
48
- expect(res.body.data).toEqual(foo);
49
- });
50
-
51
- test('should works with dynamic route ', async () => {
52
- const res = await request(apiHandler).post(`${prefix}/nest/${id}`);
53
- expect(res.status).toBe(200);
54
- expect(res.body).toEqual({ id });
55
- });
56
-
57
- test('should works with context', async () => {
58
- const res = await request(apiHandler)
59
- .post(`${prefix}/nest/user?id=${id}`)
60
- .send(foo);
61
- expect(res.status).toBe(200);
62
- expect(res.body.data).toEqual(foo);
63
- expect(res.body.query.id).toBe(id);
64
- });
65
-
66
- test('should support cookies', async () => {
67
- const res = await request(apiHandler)
68
- .post(`${prefix}/nest/user?id=${id}`)
69
- .set('Cookie', [`id=${id};name=${name}`]);
70
- expect(res.status).toBe(200);
71
- expect(res.body.cookies.id).toBe(id);
72
- expect(res.body.cookies.name).toBe(name);
73
- });
74
-
75
- test('should works with schema', async () => {
76
- const res = await request(apiHandler).patch(`${prefix}/nest/user`).send({
77
- id: 777,
78
- name: 'xxx',
79
- });
80
- expect(res.status).toBe(200);
81
-
82
- const res2 = await request(apiHandler).patch(`${prefix}/nest/user`).send({
83
- id: 'aaa',
84
- name: 'xxx',
85
- });
86
- expect(res2.status).toBe(400);
87
-
88
- const res3 = await request(apiHandler).patch(`${prefix}/nest/user`).send({
89
- id: '777',
90
- name: 'xxx',
91
- });
92
- expect(res3.status).toBe(500);
93
- });
94
-
95
- test('introspection', async () => {
96
- const res = await request(apiHandler).get(
97
- `/api${INTROSPECTION_ROUTE_PATH}`,
98
- );
99
- expect(res.status).toBe(200);
100
- expect(res.body.protocol).toBe('Farrow-API');
101
- });
102
-
103
- test('should support upload file', done => {
104
- request(apiHandler)
105
- .post(`${prefix}/upload`)
106
- .field('my_field', 'value')
107
- .attach('file', __filename)
108
- .end(async (err, res) => {
109
- if (err) {
110
- throw err;
111
- }
112
- expect(res.statusCode).toBe(200);
113
- expect(res.body.message).toBe('success');
114
- done();
115
- });
116
- });
117
- });
118
-
119
- describe('add middwares', () => {
120
- let runner: any;
121
-
122
- beforeAll(async () => {
123
- serverManager.usePlugin(plugin);
124
- runner = await serverManager.init({});
125
- });
126
-
127
- test('should support add by function', async () => {
128
- const foo = 'foo';
129
-
130
- const fakeMiddleware = jest.fn((req, res, next) => {
131
- next();
132
- });
133
- const fakeMiddleware2 = jest.fn((req, res) => {
134
- res.send(foo);
135
- });
136
- // eslint-disable-next-line @typescript-eslint/naming-convention
137
- const [mock_fakeMiddleware, mock_fakeMiddleware2] = [
138
- fakeMiddleware,
139
- fakeMiddleware2,
140
- ];
141
- const apiHandler = await runner.prepareApiServer({
142
- pwd,
143
- mode: 'framework',
144
- config: {
145
- middleware: [
146
- mock_fakeMiddleware,
147
- mock_fakeMiddleware,
148
- mock_fakeMiddleware2,
149
- ],
150
- },
151
- });
152
-
153
- const res = await request(apiHandler).get('/user');
154
- expect(fakeMiddleware.mock.calls.length).toBe(2);
155
- expect(fakeMiddleware2.mock.calls.length).toBe(1);
156
- expect(res.status).toBe(200);
157
- expect(res.text).toEqual(foo);
158
- });
159
-
160
- test('should support add by string', async () => {
161
- const foo = 'foo';
162
-
163
- const middleware1 = jest.fn((req, res, next) => {
164
- next();
165
- });
166
- const middleware2 = jest.fn((req, res) => {
167
- res.send(foo);
168
- });
169
-
170
- const [mock_middleware1, mock_middleware2] = [middleware1, middleware2];
171
- jest.mock(
172
- path.resolve(__dirname, './fixtures/middlewares/middleware1'),
173
- () => ({
174
- __esModule: true,
175
- default: mock_middleware1,
176
- }),
177
- );
178
-
179
- jest.mock(
180
- path.resolve(__dirname, './fixtures/middlewares/middleware2'),
181
- () => ({
182
- __esModule: true,
183
- default: mock_middleware2,
184
- }),
185
- );
186
-
187
- const apiHandler = await runner.prepareApiServer({
188
- pwd,
189
- mode: 'framework',
190
- config: {
191
- middleware: [
192
- require.resolve('./fixtures/middlewares/middleware1'),
193
- require.resolve('./fixtures/middlewares/middleware1'),
194
- require.resolve('./fixtures/middlewares/middleware2'),
195
- ],
196
- },
197
- });
198
-
199
- const res = await request(apiHandler).get('/user');
200
- expect(middleware1.mock.calls.length).toBe(2);
201
- expect(middleware2.mock.calls.length).toBe(1);
202
- expect(res.status).toBe(200);
203
- expect(res.text).toEqual(foo);
204
- });
205
- });
206
-
207
- describe('support app.ts in lambda mode', () => {
208
- serverManager.usePlugin(APIPlugin, plugin);
209
- let runner: any;
210
-
211
- beforeAll(async () => {
212
- runner = await serverManager.init({});
213
- });
214
-
215
- beforeEach(() => {
216
- jest.resetModules();
217
- });
218
-
219
- test('support es module', async () => {
220
- const name = `modernjs`;
221
- const mock_express = express;
222
- jest.mock(
223
- path.join(pwd, 'app.ts'),
224
- () => {
225
- const app = mock_express();
226
- return {
227
- __esModule: true,
228
- default: app,
229
- };
230
- },
231
- { virtual: true },
232
- );
233
-
234
- const apiHandler = await runner.prepareApiServer({
235
- pwd,
236
- mode: 'framework',
237
- });
238
-
239
- const res = await request(apiHandler).get(`/nest/user?name=${name}`);
240
- expect(res.status).toBe(200);
241
- expect(res.body.query.name).toBe(name);
242
- });
243
-
244
- test('support commonjs module', async () => {
245
- const name = `modernjs`;
246
- const mock_express = express;
247
- jest.mock(
248
- path.join(pwd, API_DIR, 'app.ts'),
249
- () => {
250
- const app = mock_express();
251
- return app;
252
- },
253
- { virtual: true },
254
- );
255
-
256
- const apiHandler = await runner.prepareApiServer({
257
- pwd,
258
- mode: 'framework',
259
- });
260
-
261
- const res = await request(apiHandler).get(`/nest/user?name=${name}`);
262
- expect(res.status).toBe(200);
263
- expect(res.body.query.name).toBe(name);
264
- });
265
-
266
- test('support use middleware', async () => {
267
- const name = `modernjs`;
268
- const mock_express = express;
269
- jest.mock(
270
- path.join(pwd, API_DIR, 'app.ts'),
271
- () => {
272
- const app = mock_express();
273
- app.use((req, res, next) => {
274
- req.query.name = name;
275
- next();
276
- });
277
- return app;
278
- },
279
- { virtual: true },
280
- );
281
-
282
- const apiHandler = await runner.prepareApiServer({
283
- pwd,
284
- mode: 'framework',
285
- });
286
-
287
- const res = await request(apiHandler).get(`/nest/user`);
288
- expect(res.status).toBe(200);
289
- expect(res.body.query.name).toBe(name);
290
- });
291
-
292
- test('support use router', async () => {
293
- const name = `modernjs`;
294
- const mock_express = express;
295
- jest.mock(
296
- path.join(pwd, API_DIR, 'app.ts'),
297
- () => {
298
- const app = mock_express();
299
- app.get('/hello', (req, res) => {
300
- res.send(`foo`);
301
- res.end();
302
- });
303
-
304
- return app;
305
- },
306
- { virtual: true },
307
- );
308
-
309
- const apiHandler = await runner.prepareApiServer({
310
- pwd,
311
- mode: 'framework',
312
- });
313
-
314
- const res1 = await request(apiHandler).get(`/hello`);
315
- expect(res1.status).toBe(200);
316
- expect(res1.text).toBe('foo');
317
-
318
- const res2 = await request(apiHandler).get(`/nest/user?name=${name}`);
319
- expect(res2.status).toBe(200);
320
- expect(res2.body.query.name).toBe(name);
321
- });
322
- });
323
-
324
- describe('support as async handler', () => {
325
- let runner: any;
326
-
327
- beforeAll(async () => {
328
- serverManager.usePlugin(plugin);
329
- runner = await serverManager.init({});
330
- });
331
-
332
- test('API handler should works', async () => {
333
- const foo = 'foo';
334
- const order: number[] = [];
335
-
336
- const wrapMiddleware = jest.fn(async (req, res) => {
337
- await new Promise(resolve => {
338
- setTimeout(() => {
339
- order.push(1);
340
- resolve(true);
341
- }, 50);
342
- });
343
- order.push(2);
344
- res.send(foo);
345
- });
346
-
347
- const apiHandler = await runner.prepareApiServer({
348
- pwd,
349
- mode: 'framework',
350
- config: { middleware: [wrapMiddleware] },
351
- });
352
-
353
- const asyncHandler = async (req: any, res: any) => {
354
- await apiHandler(req, res);
355
- order.push(3);
356
- };
357
-
358
- const res = await request(asyncHandler).get('/user');
359
- expect(wrapMiddleware.mock.calls.length).toBe(1);
360
- expect(order).toEqual([1, 2, 3]);
361
- expect(res.status).toBe(200);
362
- expect(res.text).toEqual(foo);
363
- });
364
- });
@@ -1,12 +0,0 @@
1
- {
2
- "extends": "@modern-js/tsconfig/base",
3
- "compilerOptions": {
4
- "declaration": false,
5
- "jsx": "preserve",
6
- "baseUrl": "./",
7
- "isolatedModules": true,
8
- "sourceMap": true
9
- },
10
- "paths": {},
11
- "exclude": ["src/__test__/fixtures/**"]
12
- }
@@ -1,156 +0,0 @@
1
- import * as path from 'path';
2
- import { Buffer } from 'buffer';
3
- import { Request, Response } from 'express';
4
- import request from 'supertest';
5
- import { serverManager } from '@modern-js/server-core';
6
- import plugin from '../src/plugin';
7
- import './common';
8
-
9
- const pwd = path.join(__dirname, './fixtures/function-mode');
10
-
11
- describe('webServer', () => {
12
- const id = '666';
13
- const name = 'foo';
14
- const foo = { id, name };
15
- let webHandler: any;
16
- let runner: any;
17
-
18
- beforeAll(async () => {
19
- serverManager.usePlugin(plugin);
20
- runner = await serverManager.init({});
21
- });
22
-
23
- test('support buffer', async () => {
24
- const middleware = (req: Request, res: Response) => {
25
- res.type('html');
26
- res.send(Buffer.from(name));
27
- };
28
-
29
- webHandler = await runner.prepareWebServer({
30
- pwd,
31
- config: { middleware: [middleware] },
32
- });
33
-
34
- const res = await request(webHandler).get('/');
35
- expect(res.status).toBe(200);
36
- expect(res.get('content-type')).toBe('text/html; charset=utf-8');
37
- expect(res.text).toContain(name);
38
- });
39
-
40
- test('should support Multiple middleware', async () => {
41
- const middleware1 = (req: Request, res: Response, next: any) => {
42
- req.query.id = id;
43
- next();
44
- };
45
-
46
- const middleware2 = (req: Request, res: Response) => {
47
- const queryId = req.query.id;
48
- if (queryId && queryId === id) {
49
- res.send(foo);
50
- } else {
51
- res.send('');
52
- }
53
- };
54
-
55
- webHandler = await runner.prepareWebServer({
56
- pwd,
57
- config: { middleware: [middleware1, middleware2] },
58
- });
59
-
60
- const res = await request(webHandler).get('/');
61
- expect(res.status).toBe(200);
62
- expect(res.get('content-type')).toBe('application/json; charset=utf-8');
63
- expect(res.body).toEqual(foo);
64
- });
65
- });
66
-
67
- describe('support as async handler', () => {
68
- const id = '666';
69
- const name = 'foo';
70
- const foo = { id, name };
71
- let webHandler: any;
72
- let runner: any;
73
-
74
- beforeAll(async () => {
75
- serverManager.usePlugin(plugin);
76
- runner = await serverManager.init({});
77
- });
78
-
79
- test('support res end by outer', async () => {
80
- const order: number[] = [];
81
- const middleware1 = async (req: Request, res: Response, next: any) => {
82
- await new Promise(resolve => {
83
- setTimeout(() => {
84
- order.push(1);
85
- resolve(true);
86
- }, 50);
87
- });
88
- order.push(2);
89
- req.query.id = id;
90
- next();
91
- };
92
-
93
- webHandler = await runner.prepareWebServer({
94
- pwd,
95
- config: { middleware: [middleware1] },
96
- });
97
-
98
- const serveHandler = (req: Request, res: Response) => {
99
- if (req.url === '/') {
100
- res.writeHead(200, { 'Content-Type': 'text/html' });
101
- res.end(name);
102
- } else {
103
- res.end(name);
104
- }
105
- };
106
-
107
- const asyncHandler = async (req: Request, res: Response) => {
108
- await webHandler(req, res);
109
- order.push(3);
110
- serveHandler(req, res);
111
- };
112
- const res = await request(asyncHandler).get('/');
113
- expect(order).toEqual([1, 2, 3]);
114
- expect(res.status).toBe(200);
115
- expect(res.get('content-type')).toBe('text/html');
116
- });
117
-
118
- test('support call res send', async () => {
119
- const order: number[] = [];
120
- const middleware1 = async (req: Request, res: Response, next: any) => {
121
- await new Promise(resolve => {
122
- setTimeout(() => {
123
- order.push(1);
124
- resolve(true);
125
- }, 50);
126
- });
127
- order.push(2);
128
- req.query.id = id;
129
- next();
130
- };
131
-
132
- const middleware2 = (req: Request, res: Response) => {
133
- const queryId = req.query.id;
134
- if (queryId && queryId === id) {
135
- res.send(foo);
136
- } else {
137
- res.send('');
138
- }
139
- };
140
-
141
- webHandler = await runner.prepareWebServer({
142
- pwd,
143
- config: { middleware: [middleware1, middleware2] },
144
- });
145
-
146
- const asyncHandler = async (req: Request, res: Response) => {
147
- await webHandler(req, res);
148
- order.push(3);
149
- };
150
- const res = await request(asyncHandler).get('/');
151
- expect(order).toEqual([1, 2, 3]);
152
- expect(res.status).toBe(200);
153
- expect(res.get('content-type')).toBe('application/json; charset=utf-8');
154
- expect(res.body).toEqual(foo);
155
- });
156
- });