@modern-js/plugin-koa 1.4.2 → 1.4.5

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,35 @@
1
1
  # @modern-js/plugin-koa
2
2
 
3
+ ## 1.4.5
4
+
5
+ ### Patch Changes
6
+
7
+ - bebb39b6: chore: improve devDependencies and peerDependencies
8
+ - Updated dependencies [132f7b53]
9
+ - @modern-js/utils@1.3.7
10
+
11
+ ## 1.4.4
12
+
13
+ ### Patch Changes
14
+
15
+ - 952432ac: fix: upload files
16
+ - c1b8fa0a: feat: convert to new server plugin
17
+ - Updated dependencies [c2046f37]
18
+ - @modern-js/utils@1.3.6
19
+
20
+ ## 1.4.3
21
+
22
+ ### Patch Changes
23
+
24
+ - ef7b0a54: feat: convert to new plugin
25
+ - Updated dependencies [5bf5868d]
26
+ - Updated dependencies [d95f28c3]
27
+ - Updated dependencies [2e8dec93]
28
+ - Updated dependencies [2008fdbd]
29
+ - Updated dependencies [2e8dec93]
30
+ - @modern-js/utils@1.3.5
31
+ - @modern-js/server-core@1.2.3
32
+
3
33
  ## 1.4.2
4
34
 
5
35
  ### Patch Changes
@@ -1,50 +1,54 @@
1
1
  import * as path from 'path';
2
- import { useAppContext, createPlugin } from '@modern-js/core';
3
2
  import { createRuntimeExportsUtils } from '@modern-js/utils';
4
- export default createPlugin(() => {
5
- let bffExportsUtils;
6
- const runtimeModulePath = path.resolve(__dirname, '../runtime');
7
- return {
8
- config() {
9
- // eslint-disable-next-line react-hooks/rules-of-hooks
10
- const appContext = useAppContext();
11
- const {
12
- appDirectory
13
- } = appContext;
14
- bffExportsUtils = createRuntimeExportsUtils(appContext.internalDirectory, 'server');
15
- const serverRuntimePath = bffExportsUtils.getPath(); // Look up one level, because the artifacts after build have dist directories
3
+ export default (() => ({
4
+ name: '@modern-js/plugin-koa',
5
+ setup: api => {
6
+ let bffExportsUtils;
7
+ const {
8
+ useAppContext
9
+ } = api;
10
+ const runtimeModulePath = path.resolve(__dirname, '../runtime');
11
+ return {
12
+ config() {
13
+ // eslint-disable-next-line react-hooks/rules-of-hooks
14
+ const appContext = useAppContext();
15
+ const {
16
+ appDirectory
17
+ } = appContext;
18
+ bffExportsUtils = createRuntimeExportsUtils(appContext.internalDirectory, 'server');
19
+ const serverRuntimePath = bffExportsUtils.getPath(); // Look up one level, because the artifacts after build have dist directories
16
20
 
17
- let relativeRuntimePath = path.join('../', path.relative(appDirectory, serverRuntimePath));
21
+ let relativeRuntimePath = path.join('../', path.relative(appDirectory, serverRuntimePath));
18
22
 
19
- if (process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test') {
20
- relativeRuntimePath = `./${path.relative(appDirectory, serverRuntimePath)}`;
21
- }
23
+ if (process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test') {
24
+ relativeRuntimePath = `./${path.relative(appDirectory, serverRuntimePath)}`;
25
+ }
22
26
 
23
- return {
24
- source: {
25
- alias: {
26
- '@modern-js/runtime/server': relativeRuntimePath
27
+ return {
28
+ source: {
29
+ alias: {
30
+ '@modern-js/runtime/server': relativeRuntimePath
31
+ }
27
32
  }
28
- }
29
- };
30
- },
33
+ };
34
+ },
31
35
 
32
- addRuntimeExports(input) {
33
- // eslint-disable-next-line react-hooks/rules-of-hooks
34
- const {
35
- appDirectory
36
- } = useAppContext();
36
+ addRuntimeExports(input) {
37
+ // eslint-disable-next-line react-hooks/rules-of-hooks
38
+ const {
39
+ appDirectory
40
+ } = useAppContext();
37
41
 
38
- const runtimePath = require.resolve(`@modern-js/runtime`, {
39
- paths: [appDirectory]
40
- });
42
+ const runtimePath = require.resolve(`@modern-js/runtime`, {
43
+ paths: [appDirectory]
44
+ });
41
45
 
42
- const currentFile = bffExportsUtils.getPath();
43
- const runtimeDir = path.dirname(runtimePath);
44
- const relativeBffPath = path.relative(path.dirname(currentFile), path.join(runtimeDir, './exports/server'));
45
- const relativeRuntimeModulePath = path.relative(path.dirname(currentFile), runtimeModulePath);
46
- const relativeFramePath = path.relative(path.dirname(currentFile), require.resolve('koa'));
47
- bffExportsUtils.addExport(`const bffRuntime = require('${relativeBffPath}');
46
+ const currentFile = bffExportsUtils.getPath();
47
+ const runtimeDir = path.dirname(runtimePath);
48
+ const relativeBffPath = path.relative(path.dirname(currentFile), path.join(runtimeDir, './exports/server'));
49
+ const relativeRuntimeModulePath = path.relative(path.dirname(currentFile), runtimeModulePath);
50
+ const relativeFramePath = path.relative(path.dirname(currentFile), require.resolve('koa'));
51
+ bffExportsUtils.addExport(`const bffRuntime = require('${relativeBffPath}');
48
52
  const pluginRuntime = require('${relativeRuntimeModulePath}');
49
53
  const Koa = require('${relativeFramePath}')
50
54
  module.exports = {
@@ -53,10 +57,9 @@ export default createPlugin(() => {
53
57
  ...pluginRuntime
54
58
  }
55
59
  `);
56
- return input;
57
- }
60
+ return input;
61
+ }
58
62
 
59
- };
60
- }, {
61
- name: '@modern-js/plugin-koa'
62
- });
63
+ };
64
+ }
65
+ }));
@@ -1,4 +1,3 @@
1
- // eslint-disable-next-line filenames/match-exported
2
1
  import plugin from "./plugin";
3
2
  export * from "./context";
4
3
  export default plugin;
@@ -2,7 +2,6 @@ import * as path from 'path';
2
2
  import Koa from 'koa';
3
3
  import Router from 'koa-router';
4
4
  import koaBody from 'koa-body';
5
- import { createPlugin } from '@modern-js/server-core';
6
5
  import { requireModule } from '@modern-js/bff-utils';
7
6
  import { fs } from '@modern-js/utils';
8
7
  import { run } from "./context";
@@ -28,37 +27,85 @@ const initMiddlewares = (middleware, app) => {
28
27
  });
29
28
  };
30
29
 
31
- export default createPlugin(() => ({
32
- // eslint-disable-next-line max-statements
33
- async prepareApiServer({
34
- pwd,
35
- mode,
36
- config,
37
- prefix
38
- }) {
39
- let app;
40
- const router = new Router();
41
- const apiDir = path.join(pwd, './api');
42
-
43
- if (mode === 'framework') {
44
- app = await findAppModule(apiDir);
45
-
46
- if (!(app instanceof Koa)) {
30
+ export default (() => ({
31
+ name: '@modern-js/plugin-koa',
32
+ pre: ['@modern-js/plugin-bff'],
33
+ setup: () => ({
34
+ async prepareApiServer({
35
+ pwd,
36
+ mode,
37
+ config,
38
+ prefix
39
+ }) {
40
+ let app;
41
+ const router = new Router();
42
+ const apiDir = path.join(pwd, './api');
43
+
44
+ if (mode === 'framework') {
45
+ app = await findAppModule(apiDir);
46
+
47
+ if (!(app instanceof Koa)) {
48
+ app = new Koa();
49
+ app.use(koaBody({
50
+ multipart: true
51
+ }));
52
+ }
53
+
54
+ if (config) {
55
+ const {
56
+ middleware
57
+ } = config;
58
+ initMiddlewares(middleware, app);
59
+ }
60
+
61
+ app.use(run);
62
+ registerRoutes(router, prefix);
63
+ } else if (mode === 'function') {
47
64
  app = new Koa();
48
- app.use(koaBody());
49
- }
65
+ app.use(koaBody({
66
+ multipart: true
67
+ }));
68
+
69
+ if (config) {
70
+ const {
71
+ middleware
72
+ } = config;
73
+ initMiddlewares(middleware, app);
74
+ }
50
75
 
51
- if (config) {
52
- const {
53
- middleware
54
- } = config;
55
- initMiddlewares(middleware, app);
76
+ app.use(run);
77
+ registerRoutes(router, prefix);
78
+ } else {
79
+ throw new Error(`mode must be function or framework`);
56
80
  }
57
81
 
58
- app.use(run);
59
- registerRoutes(router, prefix);
60
- } else if (mode === 'function') {
61
- app = new Koa();
82
+ app.use(router.routes());
83
+ return (req, res) => {
84
+ app.on('error', err => {
85
+ if (err) {
86
+ throw err;
87
+ }
88
+ });
89
+ return Promise.resolve(app.callback()(req, res));
90
+ };
91
+ },
92
+
93
+ prepareWebServer({
94
+ config
95
+ }) {
96
+ const app = new Koa();
97
+ app.use(async (ctx, next) => {
98
+ await next();
99
+
100
+ if (!ctx.body) {
101
+ // restore statusCode
102
+ if (ctx.res.statusCode === 404 && !ctx.response._explicitStatus) {
103
+ ctx.res.statusCode = 200;
104
+ }
105
+
106
+ ctx.respond = false;
107
+ }
108
+ });
62
109
  app.use(koaBody());
63
110
 
64
111
  if (config) {
@@ -68,59 +115,15 @@ export default createPlugin(() => ({
68
115
  initMiddlewares(middleware, app);
69
116
  }
70
117
 
71
- app.use(run);
72
- registerRoutes(router, prefix);
73
- } else {
74
- throw new Error(`mode must be function or framework`);
118
+ return (req, res) => {
119
+ app.on('error', err => {
120
+ if (err) {
121
+ throw err;
122
+ }
123
+ });
124
+ return Promise.resolve(app.callback()(req, res));
125
+ };
75
126
  }
76
127
 
77
- app.use(router.routes());
78
- return (req, res) => {
79
- app.on('error', err => {
80
- if (err) {
81
- throw err;
82
- }
83
- });
84
- return Promise.resolve(app.callback()(req, res));
85
- };
86
- },
87
-
88
- prepareWebServer({
89
- config
90
- }) {
91
- const app = new Koa();
92
- app.use(async (ctx, next) => {
93
- await next();
94
-
95
- if (!ctx.body) {
96
- // restore statusCode
97
- if (ctx.res.statusCode === 404 && !ctx.response._explicitStatus) {
98
- ctx.res.statusCode = 200;
99
- }
100
-
101
- ctx.respond = false;
102
- }
103
- });
104
- app.use(koaBody());
105
-
106
- if (config) {
107
- const {
108
- middleware
109
- } = config;
110
- initMiddlewares(middleware, app);
111
- }
112
-
113
- return (req, res) => {
114
- app.on('error', err => {
115
- if (err) {
116
- throw err;
117
- }
118
- });
119
- return Promise.resolve(app.callback()(req, res));
120
- };
121
- }
122
-
123
- }), {
124
- name: '@modern-js/plugin-koa',
125
- pre: ['@modern-js/plugin-bff']
126
- });
128
+ })
129
+ }));
@@ -1,13 +1,6 @@
1
- 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; }
2
-
3
- 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) { _defineProperty(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; }
4
-
5
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
6
-
7
1
  import { HttpMethod, useAPIHandlerInfos } from '@modern-js/bff-utils';
8
2
  import { isSchemaHandler } from '@modern-js/bff-runtime';
9
3
  import typeIs from 'type-is';
10
- import formidable from 'formidable';
11
4
  import { sortDynamicRoutes } from '@modern-js/adapter-helpers';
12
5
  import { createDebugger } from '@modern-js/utils';
13
6
  const debug = createDebugger('koa');
@@ -35,25 +28,18 @@ const registerRoutes = (router, prefix) => {
35
28
 
36
29
  if (result.type !== 'HandleSuccess') {
37
30
  if (result.type === 'InputValidationError') {
38
- // eslint-disable-next-line require-atomic-updates
39
31
  ctx.status = 400;
40
32
  } else {
41
- // eslint-disable-next-line require-atomic-updates
42
33
  ctx.status = 500;
43
- } // eslint-disable-next-line require-atomic-updates
44
-
34
+ }
45
35
 
46
36
  ctx.body = result.message;
47
37
  } else {
48
- // eslint-disable-next-line require-atomic-updates
49
38
  ctx.body = result.value;
50
39
  }
51
40
  } else {
52
- const args = Object.values(input.params).concat(input); // eslint-disable-next-line require-atomic-updates
53
-
54
- ctx.type = 'json'; // eslint-disable-next-line @typescript-eslint/ban-ts-comment
41
+ const args = Object.values(input.params).concat(input); // eslint-disable-next-line @typescript-eslint/ban-ts-comment
55
42
  // @ts-expect-error
56
- // eslint-disable-next-line require-atomic-updates
57
43
 
58
44
  ctx.body = await handler(...args);
59
45
  }
@@ -85,7 +71,7 @@ const getInputFromRequest = async ctx => {
85
71
  if (typeIs.is(ctx.request.type, ['application/json'])) {
86
72
  draft.data = ctx.request.body;
87
73
  } else if (typeIs.is(ctx.request.type, ['multipart/form-data'])) {
88
- draft.formData = await resvoleFormData(ctx);
74
+ draft.formData = ctx.request.files;
89
75
  } else if (typeIs.is(ctx.request.type, ['application/x-www-form-urlencoded'])) {
90
76
  draft.formUrlencoded = ctx.request.body;
91
77
  } else {
@@ -93,19 +79,4 @@ const getInputFromRequest = async ctx => {
93
79
  }
94
80
 
95
81
  return draft;
96
- };
97
-
98
- const resvoleFormData = ctx => {
99
- const form = formidable({
100
- multiples: true
101
- });
102
- return new Promise((resolve, reject) => {
103
- form.parse(ctx.req, (err, fields, files) => {
104
- if (err) {
105
- reject(err);
106
- }
107
-
108
- resolve(_objectSpread(_objectSpread({}, fields), files));
109
- });
110
- });
111
82
  };
@@ -7,58 +7,61 @@ exports.default = void 0;
7
7
 
8
8
  var path = _interopRequireWildcard(require("path"));
9
9
 
10
- var _core = require("@modern-js/core");
11
-
12
10
  var _utils = require("@modern-js/utils");
13
11
 
14
12
  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); }
15
13
 
16
14
  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; }
17
15
 
18
- var _default = (0, _core.createPlugin)(() => {
19
- let bffExportsUtils;
20
- const runtimeModulePath = path.resolve(__dirname, '../runtime');
21
- return {
22
- config() {
23
- // eslint-disable-next-line react-hooks/rules-of-hooks
24
- const appContext = (0, _core.useAppContext)();
25
- const {
26
- appDirectory
27
- } = appContext;
28
- bffExportsUtils = (0, _utils.createRuntimeExportsUtils)(appContext.internalDirectory, 'server');
29
- const serverRuntimePath = bffExportsUtils.getPath(); // Look up one level, because the artifacts after build have dist directories
16
+ var _default = () => ({
17
+ name: '@modern-js/plugin-koa',
18
+ setup: api => {
19
+ let bffExportsUtils;
20
+ const {
21
+ useAppContext
22
+ } = api;
23
+ const runtimeModulePath = path.resolve(__dirname, '../runtime');
24
+ return {
25
+ config() {
26
+ // eslint-disable-next-line react-hooks/rules-of-hooks
27
+ const appContext = useAppContext();
28
+ const {
29
+ appDirectory
30
+ } = appContext;
31
+ bffExportsUtils = (0, _utils.createRuntimeExportsUtils)(appContext.internalDirectory, 'server');
32
+ const serverRuntimePath = bffExportsUtils.getPath(); // Look up one level, because the artifacts after build have dist directories
30
33
 
31
- let relativeRuntimePath = path.join('../', path.relative(appDirectory, serverRuntimePath));
34
+ let relativeRuntimePath = path.join('../', path.relative(appDirectory, serverRuntimePath));
32
35
 
33
- if (process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test') {
34
- relativeRuntimePath = `./${path.relative(appDirectory, serverRuntimePath)}`;
35
- }
36
+ if (process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test') {
37
+ relativeRuntimePath = `./${path.relative(appDirectory, serverRuntimePath)}`;
38
+ }
36
39
 
37
- return {
38
- source: {
39
- alias: {
40
- '@modern-js/runtime/server': relativeRuntimePath
40
+ return {
41
+ source: {
42
+ alias: {
43
+ '@modern-js/runtime/server': relativeRuntimePath
44
+ }
41
45
  }
42
- }
43
- };
44
- },
46
+ };
47
+ },
45
48
 
46
- addRuntimeExports(input) {
47
- // eslint-disable-next-line react-hooks/rules-of-hooks
48
- const {
49
- appDirectory
50
- } = (0, _core.useAppContext)();
49
+ addRuntimeExports(input) {
50
+ // eslint-disable-next-line react-hooks/rules-of-hooks
51
+ const {
52
+ appDirectory
53
+ } = useAppContext();
51
54
 
52
- const runtimePath = require.resolve(`@modern-js/runtime`, {
53
- paths: [appDirectory]
54
- });
55
+ const runtimePath = require.resolve(`@modern-js/runtime`, {
56
+ paths: [appDirectory]
57
+ });
55
58
 
56
- const currentFile = bffExportsUtils.getPath();
57
- const runtimeDir = path.dirname(runtimePath);
58
- const relativeBffPath = path.relative(path.dirname(currentFile), path.join(runtimeDir, './exports/server'));
59
- const relativeRuntimeModulePath = path.relative(path.dirname(currentFile), runtimeModulePath);
60
- const relativeFramePath = path.relative(path.dirname(currentFile), require.resolve('koa'));
61
- bffExportsUtils.addExport(`const bffRuntime = require('${relativeBffPath}');
59
+ const currentFile = bffExportsUtils.getPath();
60
+ const runtimeDir = path.dirname(runtimePath);
61
+ const relativeBffPath = path.relative(path.dirname(currentFile), path.join(runtimeDir, './exports/server'));
62
+ const relativeRuntimeModulePath = path.relative(path.dirname(currentFile), runtimeModulePath);
63
+ const relativeFramePath = path.relative(path.dirname(currentFile), require.resolve('koa'));
64
+ bffExportsUtils.addExport(`const bffRuntime = require('${relativeBffPath}');
62
65
  const pluginRuntime = require('${relativeRuntimeModulePath}');
63
66
  const Koa = require('${relativeFramePath}')
64
67
  module.exports = {
@@ -67,12 +70,11 @@ var _default = (0, _core.createPlugin)(() => {
67
70
  ...pluginRuntime
68
71
  }
69
72
  `);
70
- return input;
71
- }
73
+ return input;
74
+ }
72
75
 
73
- };
74
- }, {
75
- name: '@modern-js/plugin-koa'
76
+ };
77
+ }
76
78
  });
77
79
 
78
80
  exports.default = _default;
@@ -24,6 +24,5 @@ Object.keys(_context).forEach(function (key) {
24
24
 
25
25
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
26
26
 
27
- // eslint-disable-next-line filenames/match-exported
28
27
  var _default = _plugin.default;
29
28
  exports.default = _default;
@@ -13,8 +13,6 @@ var _koaRouter = _interopRequireDefault(require("koa-router"));
13
13
 
14
14
  var _koaBody = _interopRequireDefault(require("koa-body"));
15
15
 
16
- var _serverCore = require("@modern-js/server-core");
17
-
18
16
  var _bffUtils = require("@modern-js/bff-utils");
19
17
 
20
18
  var _utils = require("@modern-js/utils");
@@ -49,37 +47,85 @@ const initMiddlewares = (middleware, app) => {
49
47
  });
50
48
  };
51
49
 
52
- var _default = (0, _serverCore.createPlugin)(() => ({
53
- // eslint-disable-next-line max-statements
54
- async prepareApiServer({
55
- pwd,
56
- mode,
57
- config,
58
- prefix
59
- }) {
60
- let app;
61
- const router = new _koaRouter.default();
62
- const apiDir = path.join(pwd, './api');
63
-
64
- if (mode === 'framework') {
65
- app = await findAppModule(apiDir);
66
-
67
- if (!(app instanceof _koa.default)) {
50
+ var _default = () => ({
51
+ name: '@modern-js/plugin-koa',
52
+ pre: ['@modern-js/plugin-bff'],
53
+ setup: () => ({
54
+ async prepareApiServer({
55
+ pwd,
56
+ mode,
57
+ config,
58
+ prefix
59
+ }) {
60
+ let app;
61
+ const router = new _koaRouter.default();
62
+ const apiDir = path.join(pwd, './api');
63
+
64
+ if (mode === 'framework') {
65
+ app = await findAppModule(apiDir);
66
+
67
+ if (!(app instanceof _koa.default)) {
68
+ app = new _koa.default();
69
+ app.use((0, _koaBody.default)({
70
+ multipart: true
71
+ }));
72
+ }
73
+
74
+ if (config) {
75
+ const {
76
+ middleware
77
+ } = config;
78
+ initMiddlewares(middleware, app);
79
+ }
80
+
81
+ app.use(_context.run);
82
+ (0, _registerRoutes.default)(router, prefix);
83
+ } else if (mode === 'function') {
68
84
  app = new _koa.default();
69
- app.use((0, _koaBody.default)());
70
- }
85
+ app.use((0, _koaBody.default)({
86
+ multipart: true
87
+ }));
88
+
89
+ if (config) {
90
+ const {
91
+ middleware
92
+ } = config;
93
+ initMiddlewares(middleware, app);
94
+ }
71
95
 
72
- if (config) {
73
- const {
74
- middleware
75
- } = config;
76
- initMiddlewares(middleware, app);
96
+ app.use(_context.run);
97
+ (0, _registerRoutes.default)(router, prefix);
98
+ } else {
99
+ throw new Error(`mode must be function or framework`);
77
100
  }
78
101
 
79
- app.use(_context.run);
80
- (0, _registerRoutes.default)(router, prefix);
81
- } else if (mode === 'function') {
82
- app = new _koa.default();
102
+ app.use(router.routes());
103
+ return (req, res) => {
104
+ app.on('error', err => {
105
+ if (err) {
106
+ throw err;
107
+ }
108
+ });
109
+ return Promise.resolve(app.callback()(req, res));
110
+ };
111
+ },
112
+
113
+ prepareWebServer({
114
+ config
115
+ }) {
116
+ const app = new _koa.default();
117
+ app.use(async (ctx, next) => {
118
+ await next();
119
+
120
+ if (!ctx.body) {
121
+ // restore statusCode
122
+ if (ctx.res.statusCode === 404 && !ctx.response._explicitStatus) {
123
+ ctx.res.statusCode = 200;
124
+ }
125
+
126
+ ctx.respond = false;
127
+ }
128
+ });
83
129
  app.use((0, _koaBody.default)());
84
130
 
85
131
  if (config) {
@@ -89,61 +135,17 @@ var _default = (0, _serverCore.createPlugin)(() => ({
89
135
  initMiddlewares(middleware, app);
90
136
  }
91
137
 
92
- app.use(_context.run);
93
- (0, _registerRoutes.default)(router, prefix);
94
- } else {
95
- throw new Error(`mode must be function or framework`);
138
+ return (req, res) => {
139
+ app.on('error', err => {
140
+ if (err) {
141
+ throw err;
142
+ }
143
+ });
144
+ return Promise.resolve(app.callback()(req, res));
145
+ };
96
146
  }
97
147
 
98
- app.use(router.routes());
99
- return (req, res) => {
100
- app.on('error', err => {
101
- if (err) {
102
- throw err;
103
- }
104
- });
105
- return Promise.resolve(app.callback()(req, res));
106
- };
107
- },
108
-
109
- prepareWebServer({
110
- config
111
- }) {
112
- const app = new _koa.default();
113
- app.use(async (ctx, next) => {
114
- await next();
115
-
116
- if (!ctx.body) {
117
- // restore statusCode
118
- if (ctx.res.statusCode === 404 && !ctx.response._explicitStatus) {
119
- ctx.res.statusCode = 200;
120
- }
121
-
122
- ctx.respond = false;
123
- }
124
- });
125
- app.use((0, _koaBody.default)());
126
-
127
- if (config) {
128
- const {
129
- middleware
130
- } = config;
131
- initMiddlewares(middleware, app);
132
- }
133
-
134
- return (req, res) => {
135
- app.on('error', err => {
136
- if (err) {
137
- throw err;
138
- }
139
- });
140
- return Promise.resolve(app.callback()(req, res));
141
- };
142
- }
143
-
144
- }), {
145
- name: '@modern-js/plugin-koa',
146
- pre: ['@modern-js/plugin-bff']
148
+ })
147
149
  });
148
150
 
149
151
  exports.default = _default;
@@ -11,20 +11,12 @@ var _bffRuntime = require("@modern-js/bff-runtime");
11
11
 
12
12
  var _typeIs = _interopRequireDefault(require("type-is"));
13
13
 
14
- var _formidable = _interopRequireDefault(require("formidable"));
15
-
16
14
  var _adapterHelpers = require("@modern-js/adapter-helpers");
17
15
 
18
16
  var _utils = require("@modern-js/utils");
19
17
 
20
18
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
21
19
 
22
- 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; }
23
-
24
- 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) { _defineProperty(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; }
25
-
26
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
27
-
28
20
  const debug = (0, _utils.createDebugger)('koa');
29
21
 
30
22
  const registerRoutes = (router, prefix) => {
@@ -50,25 +42,18 @@ const registerRoutes = (router, prefix) => {
50
42
 
51
43
  if (result.type !== 'HandleSuccess') {
52
44
  if (result.type === 'InputValidationError') {
53
- // eslint-disable-next-line require-atomic-updates
54
45
  ctx.status = 400;
55
46
  } else {
56
- // eslint-disable-next-line require-atomic-updates
57
47
  ctx.status = 500;
58
- } // eslint-disable-next-line require-atomic-updates
59
-
48
+ }
60
49
 
61
50
  ctx.body = result.message;
62
51
  } else {
63
- // eslint-disable-next-line require-atomic-updates
64
52
  ctx.body = result.value;
65
53
  }
66
54
  } else {
67
- const args = Object.values(input.params).concat(input); // eslint-disable-next-line require-atomic-updates
68
-
69
- ctx.type = 'json'; // eslint-disable-next-line @typescript-eslint/ban-ts-comment
55
+ const args = Object.values(input.params).concat(input); // eslint-disable-next-line @typescript-eslint/ban-ts-comment
70
56
  // @ts-expect-error
71
- // eslint-disable-next-line require-atomic-updates
72
57
 
73
58
  ctx.body = await handler(...args);
74
59
  }
@@ -101,7 +86,7 @@ const getInputFromRequest = async ctx => {
101
86
  if (_typeIs.default.is(ctx.request.type, ['application/json'])) {
102
87
  draft.data = ctx.request.body;
103
88
  } else if (_typeIs.default.is(ctx.request.type, ['multipart/form-data'])) {
104
- draft.formData = await resvoleFormData(ctx);
89
+ draft.formData = ctx.request.files;
105
90
  } else if (_typeIs.default.is(ctx.request.type, ['application/x-www-form-urlencoded'])) {
106
91
  draft.formUrlencoded = ctx.request.body;
107
92
  } else {
@@ -109,19 +94,4 @@ const getInputFromRequest = async ctx => {
109
94
  }
110
95
 
111
96
  return draft;
112
- };
113
-
114
- const resvoleFormData = ctx => {
115
- const form = (0, _formidable.default)({
116
- multiples: true
117
- });
118
- return new Promise((resolve, reject) => {
119
- form.parse(ctx.req, (err, fields, files) => {
120
- if (err) {
121
- reject(err);
122
- }
123
-
124
- resolve(_objectSpread(_objectSpread({}, fields), files));
125
- });
126
- });
127
97
  };
@@ -1,20 +1,5 @@
1
- declare const _default: import("@modern-js/core").AsyncPlugin<Partial<import("@modern-js/core").Progresses2Threads<{
2
- config: import("@modern-js/core").ParallelWorkflow<void, unknown>;
3
- resolvedConfig: import("@modern-js/core").AsyncWaterfall<{
4
- resolved: import("@modern-js/core").NormalizedConfig;
5
- }>;
6
- validateSchema: import("@modern-js/core").ParallelWorkflow<void, unknown>;
7
- prepare: import("@modern-js/core").AsyncWorkflow<void, void>;
8
- commands: import("@modern-js/core").AsyncWorkflow<{
9
- program: import("commander").Command;
10
- }, void>;
11
- watchFiles: import("@modern-js/core").ParallelWorkflow<void, unknown>;
12
- fileChange: import("@modern-js/core").AsyncWorkflow<{
13
- filename: string;
14
- eventType: "add" | "unlink" | "change";
15
- }, void>;
16
- beforeExit: import("@modern-js/core").AsyncWorkflow<void, void>;
17
- beforeRestart: import("@modern-js/core").AsyncWorkflow<void, void>;
18
- } & import("@modern-js/core").ClearDraftProgress<import("@modern-js/core").Hooks>>>>;
1
+ import type { CliPlugin } from '@modern-js/core';
2
+
3
+ declare const _default: () => CliPlugin;
19
4
 
20
5
  export default _default;
@@ -1,5 +1,6 @@
1
+ import type { ServerPlugin } from '@modern-js/server-core';
1
2
  export declare type Mode = 'function' | 'framework';
2
3
 
3
- declare const _default: any;
4
+ declare const _default: () => ServerPlugin;
4
5
 
5
6
  export default _default;
package/jest.config.js CHANGED
@@ -2,7 +2,6 @@ const sharedConfig = require('@scripts/jest-config');
2
2
 
3
3
  /** @type {import('@jest/types').Config.InitialOptions} */
4
4
  module.exports = {
5
- // eslint-disable-next-line node/no-unsupported-features/es-syntax
6
5
  ...sharedConfig,
7
6
  rootDir: __dirname,
8
7
  };
package/package.json CHANGED
@@ -11,7 +11,7 @@
11
11
  "modern",
12
12
  "modern.js"
13
13
  ],
14
- "version": "1.4.2",
14
+ "version": "1.4.5",
15
15
  "jsnext:source": "./src/index.ts",
16
16
  "types": "./dist/types/index.d.ts",
17
17
  "main": "./dist/js/node/index.js",
@@ -35,30 +35,28 @@
35
35
  "dependencies": {
36
36
  "@babel/runtime": "^7.15.3",
37
37
  "@modern-js/adapter-helpers": "^1.2.1",
38
- "@modern-js/utils": "^1.3.4",
39
- "formidable": "^1.2.2",
38
+ "@modern-js/bff-runtime": "^1.2.1",
39
+ "@modern-js/bff-utils": "^1.2.2",
40
+ "@modern-js/utils": "^1.3.7",
40
41
  "koa-body": "^4.2.0",
41
42
  "koa-router": "^10.0.0",
42
- "type-is": "^1.6.18",
43
- "@modern-js/bff-utils": "^1.2.2",
44
- "@modern-js/core": "^1.4.6",
45
- "@modern-js/server-core": "^1.2.2",
46
- "@modern-js/bff-runtime": "^1.2.1"
43
+ "type-is": "^1.6.18"
47
44
  },
48
45
  "devDependencies": {
49
- "koa": "^2.13.3",
50
- "@types/formidable": "^1.2.3",
46
+ "@scripts/build": "0.0.0",
47
+ "@scripts/jest-config": "0.0.0",
51
48
  "@types/jest": "^27.0.1",
52
49
  "@types/koa": "^2.13.4",
53
50
  "@types/koa-router": "^7.4.4",
54
51
  "@types/node": "^14",
55
52
  "@types/supertest": "^2.0.11",
56
53
  "@types/type-is": "^1.6.3",
57
- "supertest": "^6.1.6",
58
- "typescript": "^4",
59
- "@scripts/build": "0.0.0",
60
54
  "jest": "^27",
61
- "@scripts/jest-config": "0.0.0"
55
+ "@modern-js/server-core": "1.2.5",
56
+ "@modern-js/core": "1.6.1",
57
+ "supertest": "^6.1.6",
58
+ "koa": "^2.13.3",
59
+ "typescript": "^4"
62
60
  },
63
61
  "modernConfig": {
64
62
  "output": {
@@ -0,0 +1,4 @@
1
+ export const post = ({ formData }) => ({
2
+ message: 'success',
3
+ formData,
4
+ });
@@ -0,0 +1,4 @@
1
+ export const post = ({ formData }) => ({
2
+ message: 'success',
3
+ formData,
4
+ });
@@ -50,4 +50,20 @@ describe('function-mode', () => {
50
50
  });
51
51
  expect(res3.status).toBe(500);
52
52
  });
53
+
54
+ test('should support upload file', done => {
55
+ request(apiHandler)
56
+ .post('/upload')
57
+ .field('my_field', 'value')
58
+ .attach('file', path.join(__dirname, './fixtures/assets/index.html'))
59
+ .end(async (err, res) => {
60
+ if (err) {
61
+ throw err;
62
+ }
63
+ expect(res.statusCode).toBe(200);
64
+ expect(res.body.message).toBe('success');
65
+ expect(res.body.formData).not.toBeUndefined();
66
+ done();
67
+ });
68
+ });
53
69
  });
@@ -18,6 +18,7 @@ describe('lambda-mode', () => {
18
18
  const id = '666';
19
19
  const name = 'foo';
20
20
  const foo = { id, name };
21
+ const prefix = '/api';
21
22
  let apiHandler: any;
22
23
 
23
24
  beforeAll(async () => {
@@ -28,36 +29,36 @@ describe('lambda-mode', () => {
28
29
  apiHandler = await runner.prepareApiServer({
29
30
  pwd,
30
31
  mode: 'framework',
31
- prefix: '/api',
32
+ prefix,
32
33
  });
33
34
  });
34
35
 
35
36
  test('should works', async () => {
36
- const res = await request(apiHandler).get('/api/hello');
37
+ const res = await request(apiHandler).get(`${prefix}/hello`);
37
38
  expect(res.status).toBe(200);
38
39
  });
39
40
 
40
41
  test('should works with query', async () => {
41
- const res = await request(apiHandler).get(`/api/nest/user?id=${id}`);
42
+ const res = await request(apiHandler).get(`${prefix}/nest/user?id=${id}`);
42
43
  expect(res.status).toBe(200);
43
44
  expect(res.body.query.id).toBe(id);
44
45
  });
45
46
 
46
47
  test('should works with body', async () => {
47
- const res = await request(apiHandler).post('/api/nest/user').send(foo);
48
+ const res = await request(apiHandler).post(`${prefix}/nest/user`).send(foo);
48
49
  expect(res.status).toBe(200);
49
50
  expect(res.body.data).toEqual(foo);
50
51
  });
51
52
 
52
53
  test('should works with dynamic route ', async () => {
53
- const res = await request(apiHandler).post(`/api/nest/${id}`);
54
+ const res = await request(apiHandler).post(`${prefix}/nest/${id}`);
54
55
  expect(res.status).toBe(200);
55
56
  expect(res.body).toEqual({ id });
56
57
  });
57
58
 
58
59
  test('should works with context', async () => {
59
60
  const res = await request(apiHandler)
60
- .post(`/api/nest/user?id=${id}`)
61
+ .post(`${prefix}/nest/user?id=${id}`)
61
62
  .send(foo);
62
63
  expect(res.status).toBe(200);
63
64
  expect(res.body.data).toEqual(foo);
@@ -66,7 +67,7 @@ describe('lambda-mode', () => {
66
67
 
67
68
  test('should support cookies', async () => {
68
69
  const res = await request(apiHandler)
69
- .post(`/api/nest/user?id=${id}`)
70
+ .post(`${prefix}/nest/user?id=${id}`)
70
71
  .set('Cookie', [`id=${id};name=${name}`]);
71
72
  expect(res.status).toBe(200);
72
73
  expect(res.body.cookies.id).toBe(id);
@@ -74,19 +75,19 @@ describe('lambda-mode', () => {
74
75
  });
75
76
 
76
77
  test('should works with schema', async () => {
77
- const res = await request(apiHandler).patch('/api/nest/user').send({
78
+ const res = await request(apiHandler).patch(`${prefix}/nest/user`).send({
78
79
  id: 777,
79
80
  name: 'xxx',
80
81
  });
81
82
  expect(res.status).toBe(200);
82
83
 
83
- const res2 = await request(apiHandler).patch('/api/nest/user').send({
84
+ const res2 = await request(apiHandler).patch(`${prefix}/nest/user`).send({
84
85
  id: 'aaa',
85
86
  name: 'xxx',
86
87
  });
87
88
  expect(res2.status).toBe(400);
88
89
 
89
- const res3 = await request(apiHandler).patch('/api/nest/user').send({
90
+ const res3 = await request(apiHandler).patch(`${prefix}/nest/user`).send({
90
91
  id: '777',
91
92
  name: 'xxx',
92
93
  });
@@ -95,11 +96,27 @@ describe('lambda-mode', () => {
95
96
 
96
97
  test('introspection', async () => {
97
98
  const res = await request(apiHandler).get(
98
- `/api${INTROSPECTION_ROUTE_PATH}`,
99
+ `${prefix}${INTROSPECTION_ROUTE_PATH}`,
99
100
  );
100
101
  expect(res.status).toBe(200);
101
102
  expect(res.body.protocol).toBe('Farrow-API');
102
103
  });
104
+
105
+ test('should support upload file', done => {
106
+ request(apiHandler)
107
+ .post(`${prefix}/upload`)
108
+ .field('my_field', 'value')
109
+ .attach('file', path.join(__dirname, './fixtures/assets/index.html'))
110
+ .end(async (err, res) => {
111
+ if (err) {
112
+ throw err;
113
+ }
114
+ expect(res.statusCode).toBe(200);
115
+ expect(res.body.message).toBe('success');
116
+ expect(res.body.formData).not.toBeUndefined();
117
+ done();
118
+ });
119
+ });
103
120
  });
104
121
 
105
122
  describe('add middlewares', () => {