diff --git a/packages/egg-layer/package.json b/packages/egg-layer/package.json index e96ae150..fc3c9753 100644 --- a/packages/egg-layer/package.json +++ b/packages/egg-layer/package.json @@ -24,7 +24,7 @@ "@midwayjs/serverless-fc-trigger": "^0.2.22", "@midwayjs/serverless-scf-starter": "^0.2.22", "@midwayjs/serverless-scf-trigger": "^0.2.22", - "midway-bin": "1", + "midway-bin": "beta", "supertest": "^4.0.2" }, "files": [ diff --git a/packages/faas-cli-command-core/package.json b/packages/faas-cli-command-core/package.json index 3d224952..d37f2f30 100644 --- a/packages/faas-cli-command-core/package.json +++ b/packages/faas-cli-command-core/package.json @@ -10,7 +10,7 @@ "minimist": "^1.2.0" }, "devDependencies": { - "midway-bin": "1" + "midway-bin": "beta" }, "files": [ "dist", diff --git a/packages/faas-cli-plugin-create/package.json b/packages/faas-cli-plugin-create/package.json index d4f43eb4..85aa64fb 100644 --- a/packages/faas-cli-plugin-create/package.json +++ b/packages/faas-cli-plugin-create/package.json @@ -9,7 +9,7 @@ "light-generator": "^1.3.2" }, "devDependencies": { - "midway-bin": "1" + "midway-bin": "beta" }, "files": [ "src", diff --git a/packages/faas-cli-plugin-deploy/package.json b/packages/faas-cli-plugin-deploy/package.json index 45e6a56f..339c3833 100644 --- a/packages/faas-cli-plugin-deploy/package.json +++ b/packages/faas-cli-plugin-deploy/package.json @@ -7,7 +7,7 @@ "@midwayjs/fcli-command-core": "^0.2.22" }, "devDependencies": { - "midway-bin": "1" + "midway-bin": "beta" }, "files": [ "src", diff --git a/packages/faas-cli-plugin-fc/package.json b/packages/faas-cli-plugin-fc/package.json index edfa2d84..ac7cf31c 100644 --- a/packages/faas-cli-plugin-fc/package.json +++ b/packages/faas-cli-plugin-fc/package.json @@ -12,7 +12,7 @@ "devDependencies": { "@midwayjs/fcli-plugin-package": "^0.2.26", "fs-extra": "^8.1.0", - "midway-bin": "1" + "midway-bin": "beta" }, "files": [ "src", diff --git a/packages/faas-cli-plugin-invoke/package.json b/packages/faas-cli-plugin-invoke/package.json index 7ea477e3..420611f1 100644 --- a/packages/faas-cli-plugin-invoke/package.json +++ b/packages/faas-cli-plugin-invoke/package.json @@ -8,7 +8,7 @@ "@midwayjs/serverless-invoke": "^0.2.25" }, "devDependencies": { - "midway-bin": "1" + "midway-bin": "beta" }, "files": [ "src", diff --git a/packages/faas-cli-plugin-invoke/src/index.ts b/packages/faas-cli-plugin-invoke/src/index.ts index 4c844498..6cbb6d87 100644 --- a/packages/faas-cli-plugin-invoke/src/index.ts +++ b/packages/faas-cli-plugin-invoke/src/index.ts @@ -39,9 +39,11 @@ export class InvokePlugin extends BasePlugin { this.core.cli.log(JSON.stringify(result)); this.core.cli.log(''); this.core.cli.log('--------- result end --------'); + process.exit(); } catch (e) { const errorLog = this.core.cli.error || this.core.cli.log; errorLog(e && e.message ? `[Error] ${e.message}` : e); + process.exit(1); } }, }; diff --git a/packages/faas-cli-plugin-package/package.json b/packages/faas-cli-plugin-package/package.json index e3dd3465..650fdc73 100644 --- a/packages/faas-cli-plugin-package/package.json +++ b/packages/faas-cli-plugin-package/package.json @@ -10,7 +10,7 @@ "archiver": "^3.1.1", "fs-extra": "^8.1.0", "globby": "^10.0.1", - "midway-bin": "1" + "midway-bin": "beta" }, "files": [ "src", diff --git a/packages/faas-cli-plugin-package/src/index.ts b/packages/faas-cli-plugin-package/src/index.ts index 0e9b78c8..59ec9318 100644 --- a/packages/faas-cli-plugin-package/src/index.ts +++ b/packages/faas-cli-plugin-package/src/index.ts @@ -320,31 +320,17 @@ export class PackagePlugin extends BasePlugin { this.core.cli.log(' - Using tradition build mode'); if (this.codeAnalyzeResult.integrationProject) { // 生成一个临时 tsconfig - const tempConfigFilePath = join( - this.servicePath, - 'tsconfig_integration_faas.json' - ); - - await tsIntegrationProjectCompile(this.servicePath, { - sourceDir: this.options.sourceDir || 'src', + const tsConfig = await tsIntegrationProjectCompile(this.servicePath, { buildRoot: this.midwayBuildPath, tsCodeRoot: this.codeAnalyzeResult.tsCodeRoot, incremental: false, clean: true, }); - // 把临时的 tsconfig 移动进去 - await move( - tempConfigFilePath, - join(this.midwayBuildPath, 'tsconfig.json'), - { - overwrite: true, - } - ); + writeJSON(join(this.midwayBuildPath, 'tsconfig.json'), tsConfig); } else { await tsCompile(this.servicePath, { clean: true, - tsConfigName: 'tsconfig.json', - source: this.options.sourceDir || 'src', + tsConfigName: 'tsconfig.json' }); // copy dist to artifact directory await move( @@ -500,7 +486,7 @@ export class PackagePlugin extends BasePlugin { const deployOrigin = this.core.service.aggregation[aggregationName] .deployOrigin; - const allPaths = []; + const allAggred = []; let handlers = []; if (this.core.service.aggregation[aggregationName].functions) { handlers = this.core.service.aggregation[aggregationName].functions @@ -520,7 +506,10 @@ export class PackagePlugin extends BasePlugin { if (!httpEvent || !httpEvent.http.path) { return; } - allPaths.push(httpEvent.http.path); + allAggred.push({ + path: httpEvent.http.path, + method: httpEvent.http.method + }); if (!deployOrigin) { // 不把原有的函数进行部署 this.core.cli.log( @@ -536,6 +525,7 @@ export class PackagePlugin extends BasePlugin { .filter((func: any) => !!func); } + const allPaths = allAggred.map(aggre => aggre.path); let currentPath = commonPrefix(allPaths); currentPath = currentPath ? `${currentPath}/*` : '/*'; this.core.cli.log( @@ -549,6 +539,7 @@ export class PackagePlugin extends BasePlugin { } allAggregationPaths.push(currentPath); this.core.service.functions[aggregationFuncName]._handlers = handlers; + this.core.service.functions[aggregationFuncName]._allAggred = allAggred; this.core.service.functions[aggregationFuncName].events = [ { http: { method: 'get', path: currentPath } }, ]; diff --git a/packages/faas-cli-plugin-package/src/utils.ts b/packages/faas-cli-plugin-package/src/utils.ts index ba4963ad..763a2a15 100644 --- a/packages/faas-cli-plugin-package/src/utils.ts +++ b/packages/faas-cli-plugin-package/src/utils.ts @@ -42,7 +42,7 @@ export function commonPrefix(arr: string[]): string { prefix = commonPrefixUtil(prefix, arr[i].replace(/([^\/])$/, '$1/')); } if (!prefix || prefix === '/') { - return prefix; + return ''; } const result = prefix.replace(/\/[^\/]*$/ig, '') || '/'; if (result && !/^\//.test(result)) { diff --git a/packages/faas-cli-plugin-package/test/commonPrefix.test.ts b/packages/faas-cli-plugin-package/test/commonPrefix.test.ts new file mode 100644 index 00000000..5fa2d52d --- /dev/null +++ b/packages/faas-cli-plugin-package/test/commonPrefix.test.ts @@ -0,0 +1,14 @@ +import { commonPrefix } from '../src/utils'; +import * as assert from 'assert'; +describe('/test/commonPrefix.test.ts', () => { + describe('commonPrefix', () => { + it('/', async () => { + const prefix = commonPrefix(['/api/index', '/api/api2', '/']); + assert(prefix === ''); + }); + it('/*', async () => { + const prefix = commonPrefix(['/api/index', '/api/api2', '//*']); + assert(prefix === ''); + }); + }); +}); diff --git a/packages/faas-cli-plugin-package/test/package.test.ts b/packages/faas-cli-plugin-package/test/package.test.ts index f7ba943f..c50367ab 100644 --- a/packages/faas-cli-plugin-package/test/package.test.ts +++ b/packages/faas-cli-plugin-package/test/package.test.ts @@ -1,6 +1,6 @@ import { CommandHookCore, loadSpec } from '@midwayjs/fcli-command-core'; import { PackagePlugin } from '../src/index'; -import { join, resolve } from 'path'; +import { resolve, join } from 'path'; import { existsSync, remove } from 'fs-extra'; import * as assert from 'assert'; diff --git a/packages/faas-cli-plugin-test/package.json b/packages/faas-cli-plugin-test/package.json index 1158cabf..40d02fe1 100644 --- a/packages/faas-cli-plugin-test/package.json +++ b/packages/faas-cli-plugin-test/package.json @@ -5,7 +5,7 @@ "typings": "dist/index.d.ts", "dependencies": { "@midwayjs/fcli-command-core": "^0.2.22", - "midway-bin": "1" + "midway-bin": "beta" }, "files": [ "src", diff --git a/packages/faas-cli/package.json b/packages/faas-cli/package.json index d390c8a1..780856f0 100644 --- a/packages/faas-cli/package.json +++ b/packages/faas-cli/package.json @@ -19,7 +19,7 @@ "f": "bin/fun.js" }, "devDependencies": { - "midway-bin": "1" + "midway-bin": "beta" }, "files": [ "bin", diff --git a/packages/faas-cli/src/index.ts b/packages/faas-cli/src/index.ts index 200efb5d..ec76981f 100644 --- a/packages/faas-cli/src/index.ts +++ b/packages/faas-cli/src/index.ts @@ -30,6 +30,8 @@ export class CLI extends BaseCLI { if (this.argv.v || this.argv.version) { this.displayVersion(); + } else { // 默认没有command的时候展示帮助 + this.argv.h = true; } } @@ -49,7 +51,7 @@ export class CLI extends BaseCLI { async checkProvider() { // ignore f -v / f -h / f create - if (!this.commands.length || this.commands[0] === 'create' || this.argv.h) { + if (!this.commands.length || this.argv.h || this.commands[0] === 'create') { return; } if (!this.spec.provider) { diff --git a/packages/faas-util-ts-compile/package.json b/packages/faas-util-ts-compile/package.json index 629192e9..145a3198 100644 --- a/packages/faas-util-ts-compile/package.json +++ b/packages/faas-util-ts-compile/package.json @@ -5,7 +5,7 @@ "typings": "dist/index.d.ts", "dependencies": { "fs-extra": "^8.1.0", - "midway-bin": "1" + "midway-bin": "beta" }, "scripts": { "build": "npm run lint && midway-bin build -c", diff --git a/packages/faas-util-ts-compile/src/index.ts b/packages/faas-util-ts-compile/src/index.ts index 9a75d59e..09c2de69 100644 --- a/packages/faas-util-ts-compile/src/index.ts +++ b/packages/faas-util-ts-compile/src/index.ts @@ -1,53 +1,50 @@ -import { join, relative } from 'path'; -import { remove, writeJSON } from 'fs-extra'; +import { join, relative, resolve } from 'path'; +import { readFileSync, existsSync } from 'fs-extra'; import { BuildCommand } from 'midway-bin'; +import { combineTsConfig } from './utils'; export const tsIntegrationProjectCompile = async (baseDir, options: { - sourceDir: string; buildRoot: string; tsCodeRoot: string; incremental: boolean; + tsConfig?: any; // 临时的ts配置 clean: boolean; }) => { - const tsFaaSConfigFilename = 'tsconfig_integration_faas.json'; - // 生成一个临时 tsconfig - const tempConfigFilePath = join(baseDir, tsFaaSConfigFilename); - await remove(tempConfigFilePath); - // 重新写一个新的 - await writeJSON(tempConfigFilePath, { - compileOnSave: true, - compilerOptions: { - incremental: !!options.incremental, - target: 'ES2018', - module: 'commonjs', - moduleResolution: 'node', - experimentalDecorators: true, - emitDecoratorMetadata: true, - inlineSourceMap: true, - noImplicitThis: true, - noUnusedLocals: true, - stripInternal: true, - pretty: true, - declaration: true, - jsx: 'react', - outDir: relative( - baseDir, - join(options.buildRoot, 'dist') - ), - }, - include: [ - `${relative( - baseDir, - options.tsCodeRoot - )}/**/*`, - ], - exclude: ['dist', 'node_modules', 'test'], - }); - await tsCompile(baseDir, { - tsConfigName: tsFaaSConfigFilename, - source: options.sourceDir, + const tsConfig = await tsCompile(baseDir, { + tsConfig: options.tsConfig, clean: options.clean, + incremental: options.incremental, + innerTsConfig: { + compileOnSave: true, + compilerOptions: { + incremental: !!options.incremental, + target: 'ES2018', + module: 'commonjs', + moduleResolution: 'node', + experimentalDecorators: true, + emitDecoratorMetadata: true, + inlineSourceMap: true, + noImplicitThis: true, + noUnusedLocals: true, + stripInternal: true, + pretty: true, + declaration: true, + jsx: 'react', + outDir: relative( + baseDir, + join(options.buildRoot, 'dist') + ), + }, + include: [ + `${relative( + baseDir, + options.tsCodeRoot + )}/**/*` + ], + exclude: ['dist', 'node_modules', 'test'], + } }); + return tsConfig; }; /** @@ -59,17 +56,47 @@ export const tsIntegrationProjectCompile = async (baseDir, options: { * @param options.clean 是否在构建前清理 */ export const tsCompile = async (baseDir: string, options: { - source?: string; tsConfigName?: string; clean?: boolean; + innerTsConfig?: any; + tsConfig?: any; // extra tsconfig + incremental?: boolean; } = {}) => { const builder = new BuildCommand(); + let tsJson = null; + if (options.tsConfigName) { + try { + tsJson = JSON.parse(readFileSync(resolve(baseDir, options.tsConfigName)).toString()); + } catch (e) {} + } + const tsConfig = combineTsConfig({}, options.innerTsConfig, options.tsConfig, tsJson); + + if (tsConfig.compilerOptions) { + if (tsConfig.compilerOptions.inlineSourceMap) { + tsConfig.compilerOptions.sourceMap = false; + } + if (options.incremental === true || options.incremental === false) { + tsConfig.compilerOptions.incremental = options.incremental; + } + if (tsConfig.compilerOptions.incremental) { + let tsBuildInfoFile = ''; + if (tsConfig.compilerOptions.outDir && existsSync(tsConfig.compilerOptions.outDir)) { + tsBuildInfoFile = resolve(tsConfig.compilerOptions.outDir, '.tsbuildinfo'); + } else { + const tmpDir = ['build', 'dist'].find(dirName => existsSync(resolve(baseDir, dirName))); + tsBuildInfoFile = resolve(tmpDir || baseDir, '.tsbuildinfo'); + } + tsConfig.compilerOptions.tsBuildInfoFile = tsBuildInfoFile; + } + } + await builder.run({ cwd: baseDir, argv: { clean: typeof options.clean === 'undefined' ? true : options.clean, - project: options.tsConfigName || 'tsconfig.json', - srcDir: options.source || 'src', + tsConfig }, }); + + return tsConfig; }; diff --git a/packages/faas-util-ts-compile/src/utils.ts b/packages/faas-util-ts-compile/src/utils.ts new file mode 100644 index 00000000..c72eec62 --- /dev/null +++ b/packages/faas-util-ts-compile/src/utils.ts @@ -0,0 +1,23 @@ +const getType = (v: any) => (({}).toString.call(v).slice(8, -1).toLowerCase()); +export const combineTsConfig = (config, ...tsConfig: any[]) => { + const combined = config || {}; + for (const config of tsConfig || []) { + for (const key in config || {}) { + const value = config[key]; + const valueType = getType(value); + if (valueType === 'object') { + combined[key] = combineTsConfig({}, combined[key], value); + } else if (valueType === 'array') { + if (!combined[key]) { + combined[key] = []; + } + combined[key].push(...value); + } else { + if (value || value === false) { + combined[key] = value; + } + } + } + } + return combined; +}; diff --git a/packages/faas/package.json b/packages/faas/package.json index f59086d3..bbf02b3e 100644 --- a/packages/faas/package.json +++ b/packages/faas/package.json @@ -17,7 +17,7 @@ "src" ], "devDependencies": { - "midway-bin": "1" + "midway-bin": "beta" }, "license": "MIT", "scripts": { diff --git a/packages/faas/src/starter.ts b/packages/faas/src/starter.ts index 43be855b..8c1304a4 100644 --- a/packages/faas/src/starter.ts +++ b/packages/faas/src/starter.ts @@ -125,7 +125,7 @@ export class FaaSStarter implements IFaaSStarter { } const context: FaaSContext = this.getContext(args.shift()); - if (funOptions.mod) { + if (funOptions && funOptions.mod) { // invoke middleware, just for http let fnMiddleawere = []; fnMiddleawere = fnMiddleawere.concat(this.globalMiddleware); diff --git a/packages/runtime-engine/package.json b/packages/runtime-engine/package.json index 90743ee1..1f6bb4fa 100644 --- a/packages/runtime-engine/package.json +++ b/packages/runtime-engine/package.json @@ -7,7 +7,7 @@ "egg-logger": "^2.3.1" }, "devDependencies": { - "midway-bin": "1" + "midway-bin": "beta" }, "scripts": { "build": "npm run lint && midway-bin build -c", diff --git a/packages/runtime-mock/package.json b/packages/runtime-mock/package.json index 7fdfd006..a8360949 100644 --- a/packages/runtime-mock/package.json +++ b/packages/runtime-mock/package.json @@ -7,7 +7,7 @@ "@midwayjs/runtime-engine": "^0.2.22" }, "devDependencies": { - "midway-bin": "1" + "midway-bin": "beta" }, "files": [ "dist" diff --git a/packages/serverless-aws-starter/package.json b/packages/serverless-aws-starter/package.json index 54cb4989..34b99f91 100644 --- a/packages/serverless-aws-starter/package.json +++ b/packages/serverless-aws-starter/package.json @@ -7,7 +7,7 @@ "@midwayjs/runtime-engine": "^0.2.22" }, "devDependencies": { - "midway-bin": "1", + "midway-bin": "beta", "raw-body": "^2.4.1" }, "files": [ diff --git a/packages/serverless-fc-starter/package.json b/packages/serverless-fc-starter/package.json index c99735a0..ac669268 100644 --- a/packages/serverless-fc-starter/package.json +++ b/packages/serverless-fc-starter/package.json @@ -10,7 +10,7 @@ }, "devDependencies": { "@midwayjs/runtime-mock": "^0.2.22", - "midway-bin": "1", + "midway-bin": "beta", "raw-body": "^2.4.1" }, "files": [ diff --git a/packages/serverless-fc-trigger/package.json b/packages/serverless-fc-trigger/package.json index 059e1791..555475fb 100644 --- a/packages/serverless-fc-trigger/package.json +++ b/packages/serverless-fc-trigger/package.json @@ -9,7 +9,7 @@ "express": "^4.17.1" }, "devDependencies": { - "midway-bin": "1", + "midway-bin": "beta", "supertest": "^4.0.2" }, "files": [ diff --git a/packages/serverless-invoke/package.json b/packages/serverless-invoke/package.json index 024b3306..9bf167e1 100644 --- a/packages/serverless-invoke/package.json +++ b/packages/serverless-invoke/package.json @@ -21,7 +21,7 @@ }, "devDependencies": { "@midwayjs/faas": "^0.2.23", - "midway-bin": "1" + "midway-bin": "beta" }, "files": [ "dist", diff --git a/packages/serverless-invoke/src/core.ts b/packages/serverless-invoke/src/core.ts index 09079d45..2e895348 100644 --- a/packages/serverless-invoke/src/core.ts +++ b/packages/serverless-invoke/src/core.ts @@ -103,24 +103,25 @@ export abstract class InvokeCore implements IInvoke { if (this.codeAnalyzeResult.integrationProject) { // 一体化调整目录 await tsIntegrationProjectCompile(baseDir, { - sourceDir: 'src', buildRoot: this.buildDir, tsCodeRoot: this.codeAnalyzeResult.tsCodeRoot, incremental: this.options.incremental, - clean: this.options.clean, + tsConfig: { + compilerOptions: { + sourceRoot: this.codeAnalyzeResult.tsCodeRoot // for sourceMap + } + }, + clean: this.options.clean }); - // remove tsconfig - await move( - join(baseDir, 'tsconfig_integration_faas.json'), - join(this.buildDir, 'tsconfig.json'), - opts - ); } else { - // TODO 重构 midway-bin 不生成 tsconfig await tsCompile(baseDir, { - source: 'src', tsConfigName: 'tsconfig.json', - clean: this.options.clean, + tsConfig: { + compilerOptions: { + sourceRoot: resolve(baseDir, 'src') // for sourceMap + } + }, + clean: this.options.clean }); await move(join(baseDir, 'dist'), join(this.buildDir, 'dist'), opts); } diff --git a/packages/serverless-invoke/src/main.ts b/packages/serverless-invoke/src/main.ts index 35145d2b..a1e754b8 100644 --- a/packages/serverless-invoke/src/main.ts +++ b/packages/serverless-invoke/src/main.ts @@ -38,7 +38,10 @@ export const getInvoke = (Invoke, debugPath) => { }); } }); - + process.on('SIGINT', () => { + child.kill(); + process.exit(); + }); return new Promise((resolve, reject) => { get(child, 'faastest').then(data => { child.kill(); diff --git a/packages/serverless-invoke/test/fixtures/baseApp/tsconfig.json b/packages/serverless-invoke/test/fixtures/baseApp/tsconfig.json index aa9b0585..2b03248d 100644 --- a/packages/serverless-invoke/test/fixtures/baseApp/tsconfig.json +++ b/packages/serverless-invoke/test/fixtures/baseApp/tsconfig.json @@ -6,13 +6,14 @@ "moduleResolution": "node", "experimentalDecorators": true, "emitDecoratorMetadata": true, - "inlineSourceMap":true, + "inlineSourceMap": true, "noImplicitThis": true, "noUnusedLocals": true, "stripInternal": true, "pretty": true, "declaration": true, - "outDir": "dist" + "outDir": "dist", + "sourceRoot": "" }, "exclude": [ "dist", diff --git a/packages/serverless-invoke/test/index.test.ts b/packages/serverless-invoke/test/index.test.ts index fc4a4da9..be5f4342 100644 --- a/packages/serverless-invoke/test/index.test.ts +++ b/packages/serverless-invoke/test/index.test.ts @@ -12,6 +12,9 @@ describe('/test/index.test.ts', () => { if (existsSync(join(__dirname, 'fixtures/ice-faas-ts-standard/.faas_debug_tmp'))) { await remove(join(__dirname, 'fixtures/ice-faas-ts-standard/.faas_debug_tmp')); } + if (existsSync(join(__dirname, 'fixtures/ice-faas-ts-standard/.tsbuildinfo'))) { + await remove(join(__dirname, 'fixtures/ice-faas-ts-standard/.tsbuildinfo')); + } }); it('should use origin http trigger', async () => { diff --git a/packages/serverless-scf-starter/package.json b/packages/serverless-scf-starter/package.json index 8eb650f5..a3ee83a8 100644 --- a/packages/serverless-scf-starter/package.json +++ b/packages/serverless-scf-starter/package.json @@ -9,7 +9,7 @@ }, "devDependencies": { "@midwayjs/runtime-mock": "^0.2.22", - "midway-bin": "1", + "midway-bin": "beta", "raw-body": "^2.4.1" }, "files": [ diff --git a/packages/serverless-scf-trigger/package.json b/packages/serverless-scf-trigger/package.json index ab60d8c0..dd58fd9e 100644 --- a/packages/serverless-scf-trigger/package.json +++ b/packages/serverless-scf-trigger/package.json @@ -10,7 +10,7 @@ "express": "^4.17.1" }, "devDependencies": { - "midway-bin": "1" + "midway-bin": "beta" }, "files": [ "dist" diff --git a/packages/serverless-spec-builder/package.json b/packages/serverless-spec-builder/package.json index 6cd076f4..69fd3988 100644 --- a/packages/serverless-spec-builder/package.json +++ b/packages/serverless-spec-builder/package.json @@ -10,7 +10,7 @@ "mkdirp": "^0.5.1" }, "devDependencies": { - "midway-bin": "1" + "midway-bin": "beta" }, "files": [ "dist", diff --git a/packages/serverless-spec-builder/src/wrapper.ts b/packages/serverless-spec-builder/src/wrapper.ts index bf1e503e..05314b97 100644 --- a/packages/serverless-spec-builder/src/wrapper.ts +++ b/packages/serverless-spec-builder/src/wrapper.ts @@ -32,12 +32,24 @@ exports.<%=handlerData.name%> = asyncWrapper(async (...args) => { <% if (handlerData.handler) { %> return runtime.asyncEvent(starter.handleInvokeWrapper('<%=handlerData.handler%>'))(...args); <% } else { %> + const allHandlers = <%-JSON.stringify(handlerData.handlers)%>; return runtime.asyncEvent(async (ctx) => { - <% handlerData.handlers.forEach(function(multiHandler){ %> if (ctx && ctx.path === '<%=multiHandler.path%>') { - return starter.handleInvokeWrapper('<%=multiHandler.handler%>')(ctx); - } else <% }); %>{ - return 'unhandler path: ' + (ctx && ctx.path || ''); + let handler = null; + let ctxPath = ctx && ctx.path || ''; + if (ctxPath) { + handler = allHandlers.find(handler => { + return ctxPath.indexOf(handler.path) != -1; + }); + } + + if (!handler) { + handler = allHandlers[allHandlers.length - 1]; + } + + if (handler) { + return starter.handleInvokeWrapper(handler.hanlder)(ctx); } + return 'unhandler path: ' + ctxPath + '; handlerInfo: ' + JSON.stringify(allHandlers); })(...args); <% } %> }); @@ -49,8 +61,9 @@ export function writeWrapper(options: { baseDir: string; distDir: string; starter: string; + cover?: boolean; }) { - const { service, distDir, starter, baseDir } = options; + const { service, distDir, starter, baseDir, cover } = options; const files = {}; const functions = service.functions || {}; for (const func in functions) { @@ -59,7 +72,7 @@ export function writeWrapper(options: { continue; } const [handlerFileName, name] = handlerConf.handler.split('.'); - if (existsSync(join(baseDir, handlerFileName + '.js'))) { + if (!cover && existsSync(join(baseDir, handlerFileName + '.js'))) { // 如果入口文件名存在,则跳过 continue; } @@ -76,7 +89,7 @@ export function writeWrapper(options: { if (handlerConf._isAggregation && handlerConf.functions) { files[handlerFileName].handlers.push({ name, - handlers: handlerConf._handlers, + handlers: formetAggregationHandlers(handlerConf._handlers), }); } else { files[handlerFileName].handlers.push({ @@ -100,3 +113,19 @@ export function writeWrapper(options: { writeFileSync(fileName, content); } } + +export function formetAggregationHandlers(handlers) { + if (!handlers || !handlers.length) { + return []; + } + return handlers.map(handler => { + const path = handler.path.replace(/\**$/, ''); + return { + handler: handler.handler, + path, + level: path.split('/').length - 1 + }; + }).sort((handlerA, handlerB) => { + return handlerB.level - handlerA.level; + }); +} diff --git a/packages/serverless-spec-builder/test/fixtures/wrapper/aggre.js b/packages/serverless-spec-builder/test/fixtures/wrapper/aggre.js new file mode 100644 index 00000000..95de5ee4 --- /dev/null +++ b/packages/serverless-spec-builder/test/fixtures/wrapper/aggre.js @@ -0,0 +1,48 @@ +const { FaaSStarter } = require('@midwayjs/faas'); +const { asyncWrapper, start } = require('testStarter'); + + +let starter; +let runtime; +let inited = false; + +const initializeMethod = async (config = {}) => { + runtime = await start({ + layers: [] + }); + starter = new FaaSStarter({ config, baseDir: __dirname }); + await starter.start(); + inited = true; +}; + +exports.initializer = asyncWrapper(async ({config} = {}) => { + await initializeMethod(config); +}); + + +exports.handler = asyncWrapper(async (...args) => { + if (!inited) { + await initializeMethod(); + } + + const allHandlers = [{"handler":"index.handler","path":"/api/test","level":2},{"handler":"render.handler","path":"/","level":1}]; + return runtime.asyncEvent(async (ctx) => { + let handler = null; + let ctxPath = ctx && ctx.path || ''; + if (ctxPath) { + handler = allHandlers.find(handler => { + return ctxPath.indexOf(handler.path) != -1; + }); + } + + if (!handler) { + handler = allHandlers[allHandlers.length - 1]; + } + + if (handler) { + return starter.handleInvokeWrapper(handler.hanlder)(ctx); + } + return 'unhandler path: ' + ctxPath + '; handlerInfo: ' + JSON.stringify(allHandlers); + })(...args); + +}); diff --git a/packages/serverless-spec-builder/test/fixtures/wrapper/index.js b/packages/serverless-spec-builder/test/fixtures/wrapper/index.js new file mode 100644 index 00000000..01b64761 --- /dev/null +++ b/packages/serverless-spec-builder/test/fixtures/wrapper/index.js @@ -0,0 +1,30 @@ +const { FaaSStarter } = require('@midwayjs/faas'); +const { asyncWrapper, start } = require('testStarter'); + + +let starter; +let runtime; +let inited = false; + +const initializeMethod = async (config = {}) => { + runtime = await start({ + layers: [] + }); + starter = new FaaSStarter({ config, baseDir: __dirname }); + await starter.start(); + inited = true; +}; + +exports.initializer = asyncWrapper(async ({config} = {}) => { + await initializeMethod(config); +}); + + +exports.handler = asyncWrapper(async (...args) => { + if (!inited) { + await initializeMethod(); + } + + return runtime.asyncEvent(starter.handleInvokeWrapper('index.handler'))(...args); + +}); diff --git a/packages/serverless-spec-builder/test/fixtures/wrapper/render.js b/packages/serverless-spec-builder/test/fixtures/wrapper/render.js new file mode 100644 index 00000000..989affff --- /dev/null +++ b/packages/serverless-spec-builder/test/fixtures/wrapper/render.js @@ -0,0 +1,30 @@ +const { FaaSStarter } = require('@midwayjs/faas'); +const { asyncWrapper, start } = require('testStarter'); + + +let starter; +let runtime; +let inited = false; + +const initializeMethod = async (config = {}) => { + runtime = await start({ + layers: [] + }); + starter = new FaaSStarter({ config, baseDir: __dirname }); + await starter.start(); + inited = true; +}; + +exports.initializer = asyncWrapper(async ({config} = {}) => { + await initializeMethod(config); +}); + + +exports.handler = asyncWrapper(async (...args) => { + if (!inited) { + await initializeMethod(); + } + + return runtime.asyncEvent(starter.handleInvokeWrapper('render.handler'))(...args); + +}); diff --git a/packages/serverless-spec-builder/test/wrapper.test.ts b/packages/serverless-spec-builder/test/wrapper.test.ts new file mode 100644 index 00000000..93b1daf2 --- /dev/null +++ b/packages/serverless-spec-builder/test/wrapper.test.ts @@ -0,0 +1,36 @@ +import { writeWrapper } from '../src/wrapper'; +import * as path from 'path'; +import * as assert from 'assert'; + +describe('/test/wrapper.test.ts', () => { + describe('test all format', () => { + it('writeWrapper', () => { + writeWrapper({ + cover: true, + service: { + functions: { + aggregation: { + handler: 'aggre.handler', + _isAggregation: true, + functions: [ 'index' ], + _handlers: [ + { path: '/api/test', handler: 'index.handler' }, + { path: '/*', handler: 'render.handler' }, + ] + }, + index: { + handler: 'index.handler' + }, + render: { + handler: 'render.handler' + } + } + }, + baseDir: path.join(__dirname, './fixtures/wrapper'), + distDir: path.join(__dirname, './fixtures/wrapper'), + starter: 'testStarter', + }); + assert(true); + }); + }); +}); diff --git a/packages/simple-lock/package.json b/packages/simple-lock/package.json index 864c06e7..c09225b6 100644 --- a/packages/simple-lock/package.json +++ b/packages/simple-lock/package.json @@ -7,7 +7,7 @@ "dist" ], "devDependencies": { - "midway-bin": "1" + "midway-bin": "beta" }, "repository": { "type": "git",