Skip to content
This repository has been archived by the owner on Jul 2, 2020. It is now read-only.

Commit

Permalink
fix: tencent trigger (#131)
Browse files Browse the repository at this point in the history
* fix: process

* fix: tencent-support

* fix: support timer

* fix: test
  • Loading branch information
echosoar committed Apr 15, 2020
1 parent 8b3b5e9 commit 0e93057
Show file tree
Hide file tree
Showing 25 changed files with 414 additions and 61 deletions.
6 changes: 3 additions & 3 deletions docs/guide/yml.md
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ export interface FunctionStructure {
export type EventType = 'http' | 'mq' | 'schedule';

export interface EventStructureType {
[eventName: string]: HTTPEvent | MQEvent | ScheduleEvent;
[eventName: string]: HTTPEvent | MQEvent | TimerEvent;
}

export interface HTTPEvent {
Expand All @@ -206,7 +206,7 @@ export interface MQEvent {
tag?: string;
}

export interface ScheduleEvent {
export interface TimerEvent {
type: 'cron' | 'every';
value: string;
payload?: string;
Expand Down Expand Up @@ -248,7 +248,7 @@ events 是一个由不同事件(触发器)组成的**对象数组**。这个
| topic | string | 接收 metaq 消息的 topic |
| tag | string | 接收 metaq 消息的 tag,用竖线分割 |
| | | |
| **ScheduleEvent** | | |
| **TimerEvent** | | |
| type | string | 必填,触发类型,可以选择 'cron','every' |
| value | string | 必填,对应触发的值。<br />如果是 cron类型,则填写 cron 表达式。<br />如果是 every 类型,则填写间隔时间,**带上单位** |
| payload | any | 可选,配置在网关,每次触发的内容 |
Expand Down
2 changes: 1 addition & 1 deletion packages/faas-cli-command-core/src/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -334,7 +334,7 @@ export class CommandHookCore implements ICommandHooksCore {
this.error('commandNotFound', { command, commandPath });
}
cmdObj = cmdObj.commands[command];
if (cmdObj.options) {
if (cmdObj && cmdObj.options) {
this.commandOptions(cmdObj.options, usage);
}
}
Expand Down
3 changes: 3 additions & 0 deletions packages/faas-cli-plugin-invoke/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { compileInProject } from '@midwayjs/mwcc';
import { writeWrapper } from '@midwayjs/serverless-spec-builder';
import { createRuntime } from '@midwayjs/runtime-mock';
import * as FCTrigger from '@midwayjs/serverless-fc-trigger';
import * as SCFTrigger from '@midwayjs/serverless-scf-trigger';
import { resolve, relative, join } from 'path';
import { FaaSStarterClass, cleanTarget } from './utils';
import {
Expand Down Expand Up @@ -409,6 +410,8 @@ export class FaaSInvokePlugin extends BasePlugin {
let triggerMap;
if (platform === 'aliyun') {
triggerMap = FCTrigger;
} else if (platform === 'tencent') {
triggerMap = SCFTrigger;
}
const trigger = this.getTrigger(triggerMap, args);
await runtime.start();
Expand Down
34 changes: 32 additions & 2 deletions packages/faas-cli-plugin-invoke/test/apigw.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { join } from 'path';
import * as assert from 'assert';
import { remove } from 'fs-extra';
describe('/test/apigw.test.ts', () => {
it('invoke', async () => {
it('aliyun', async () => {
const baseDir = join(__dirname, 'fixtures/http');
await remove(join(baseDir, './.faas_debug_tmp'));
const result: any = await invoke({
Expand All @@ -30,6 +30,36 @@ describe('/test/apigw.test.ts', () => {
]
});
const resultBody = JSON.parse(result.body);
assert(resultBody.headers['Content-Type'] === 'text/json' && resultBody.method === 'POST' && resultBody.path === '/test' && resultBody.body.name === 'test' && resultBody.pathParameters.id === 'id');
assert(resultBody.headers['Content-Type'] === 'text/json' && resultBody.method === 'POST' && resultBody.path === '/test' && resultBody.body.name === 'test' && resultBody.params.id === 'id');
});

it('tencent', async () => {
const baseDir = join(__dirname, 'fixtures/http-scf');
await remove(join(baseDir, './.faas_debug_tmp'));
const result: any = await invoke({
functionDir: baseDir,
functionName: 'http',
trigger: 'apigw',
data: [
{
headers: {
'Content-Type': 'text/json'
},
method: 'POST',
query: {
q: 'testq'
},
pathParameters: {
id: 'id'
},
path: '/test',
body: {
name: 'test'
}
}
]
});
const resultBody = JSON.parse(result.body);
assert(resultBody.headers['Content-Type'] === 'text/json' && resultBody.method === 'POST' && resultBody.path === '/test' && resultBody.body.name === 'test' && resultBody.params.id === 'id');
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"dependencies": {
"@midwayjs/faas": "*"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
service: serverless-midway-test

provider:
name: tencent
runtime: nodejs8

functions:
http:
handler: http.handler
events:
- apigw:
method: get
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { func, inject, provide } from '@midwayjs/faas';

@provide()
@func('http.handler')
export class HelloHttpService {

@inject()
ctx; // context

async handler() {

this.ctx.body = {
headers: this.ctx.headers,
method: this.ctx.method,
path: this.ctx.path,
body: this.ctx.request.body,
params: this.ctx.params
};
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"compileOnSave": true,
"compilerOptions": {
"target": "ES2018",
"module": "commonjs",
"moduleResolution": "node",
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"inlineSourceMap": true,
"noImplicitThis": true,
"noUnusedLocals": true,
"stripInternal": true,
"pretty": true,
"declaration": true,
"outDir": "dist",
"sourceRoot": ""
},
"exclude": [
"dist",
"node_modules",
"test"
]
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@ export class HelloHttpService {

async handler() {
return {
headers: this.ctx.request.headers,
method: this.ctx.request.method,
path: this.ctx.request.path,
headers: this.ctx.headers,
method: this.ctx.method,
path: this.ctx.path,
body: this.ctx.request.body,
pathParameters: this.ctx.request.pathParameters
params: this.ctx.params
}
}
}
33 changes: 33 additions & 0 deletions packages/faas-cli-plugin-scf/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
{
"name": "@midwayjs/fcli-plugin-scf",
"version": "0.2.74",
"main": "dist/index",
"typings": "dist/index.d.ts",
"dependencies": {
"@midwayjs/fcli-command-core": "^0.2.74",
"@midwayjs/serverless-scf-starter": "^0.2.74",
"@midwayjs/serverless-spec-builder": "^0.2.74",
"serverless-tencent-scf": "^0.1.36"
},
"devDependencies": {
"@midwayjs/fcli-plugin-package": "^0.2.74",
"fs-extra": "^8.1.0",
"midway-bin": "^2.0.0"
},
"engines": {
"node": ">= 10"
},
"files": [
"src",
"dist"
],
"scripts": {
"build": "npm run lint && midway-bin build -c",
"lint": "../../node_modules/.bin/tslint --format prose -c ../../tslint.json src/**/*.ts test/**/*.ts",
"test": "npm run lint && NODE_ENV=test midway-bin test --ts --full-trace --timeout=0",
"debug": "npm run lint && NODE_ENV=test midway-bin test --ts --full-trace --inspect-brk=9229",
"cov": "NODE_ENV=unittest midway-bin cov --ts",
"clean": "midway-bin clean",
"autod": "midway-bin autod"
}
}
139 changes: 139 additions & 0 deletions packages/faas-cli-plugin-scf/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
import { BasePlugin, ICoreInstance, CommandHookCore } from '@midwayjs/fcli-command-core';
import { join } from 'path';
import * as Tencent from 'serverless-tencent-scf';
import { writeWrapper } from '@midwayjs/serverless-spec-builder';
import { generateFunctionsSpec, generateFunctionsSpecFile } from '@midwayjs/serverless-spec-builder/scf';

export class TencentSCFPlugin extends BasePlugin {
core: ICoreInstance;
options: any;
provider = 'tencent';
servicePath = this.core.config.servicePath;
midwayBuildPath = join(this.servicePath, '.serverless');

hooks = {
'package:generateSpec': async () => {
this.core.cli.log('Generate spec file...');
await generateFunctionsSpecFile(
this.getSpecJson({
provider: {
stage: 'test',
},
}),
join(this.midwayBuildPath, 'serverless.yml')
);
},
'package:generateEntry': async () => {
this.core.cli.log('Generate entry file...');
this.setGlobalDependencies('@midwayjs/serverless-scf-starter');
writeWrapper({
baseDir: this.servicePath,
service: this.core.service,
distDir: this.midwayBuildPath,
starter: '@midwayjs/serverless-scf-starter'
});
},
'deploy:deploy': async () => {
// 执行 package 打包
if (!this.core.service.package) {
this.core.service.package = {};
}
if (!this.core.service.package.artifact) {
this.core.service.package.artifact = 'artifact.zip';
}
await this.core.invoke(['package'], true, this.options);
const tencentDeploy = await this.getTencentServerless(this.core.service.package.artifact);
await tencentDeploy.invoke();
},
};

getSpecJson(coverOptions?: any) {
const service = this.core.service;
if (coverOptions) {
Object.keys(coverOptions).forEach((key: string) => {
if (!service[key]) {
service[key] = {};
}
Object.assign(service[key], coverOptions[key]);
});
}
return {
custom: service.custom,
service: service.service,
provider: service.provider,
functions: this.getNotIgnoreFunc(),
resources: service.resources,
package: service.package,
};
}

// 获取没有忽略的方法(for 高密度部署)
getNotIgnoreFunc() {
const func = {};
for (const funcName in this.core.service.functions) {
const funcConf = this.core.service.functions[funcName];
if (funcConf._ignore) {
continue;
}
func[funcName] = funcConf;
}
return func;
}

// 设置全局依赖,在package的时候会读取
setGlobalDependencies(name: string, version?: string) {
if (!this.core.service.globalDependencies) {
this.core.service.globalDependencies = {};
}
this.core.service.globalDependencies[name] = version || '*';
}

async getTencentServerless(artifact) {
Object.assign(
this.core.service,
{
package: {},
runtimeExtensions: {},
},
await generateFunctionsSpec(
this.getSpecJson({
provider: {
stage: 'test',
},
})
)
);
const midwayServerless: any = new CommandHookCore({
config: {
servicePath: this.servicePath,
},
commands: ['deploy'],
service: {
...this.core.service,
plugins: [],
getAllFunctions: () => {
return Object.keys(this.core.service.functions);
},
getFunction: functionName => {
return this.core.service.functions[functionName];
},
package: {
artifact
}
},
provider: this.provider,
options: {
package: `.serverless/${this.core.service.package.artifact}`,
}
});
midwayServerless.cliCommands = ['deploy'];
midwayServerless.addPlugin(class DeployPlugin extends BasePlugin {
commands = {
deploy: { lifecycleEvents: ['deploy'] }
};
});
midwayServerless.addPlugin(Tencent);
await midwayServerless.ready();
return midwayServerless;
}
}
19 changes: 19 additions & 0 deletions packages/faas-cli-plugin-scf/test/fixtures/base/f.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
service: midway-test

provider:
name: tencent

functions:
index:
handler: index.handler
events:
- http:
method: get
path: /http
index2:
handler: index.handler2
events:
- apigw:
method: get
path: /apigw

6 changes: 6 additions & 0 deletions packages/faas-cli-plugin-scf/test/fixtures/base/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"dependencies": {
"@midwayjs/runtime-engine": "*",
"@midwayjs/faas": "*"
}
}
13 changes: 13 additions & 0 deletions packages/faas-cli-plugin-scf/test/fixtures/base/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { FaaSContext, func, inject, provide } from '@midwayjs/faas';

@provide()
@func('index.handler')
export class HelloService {

@inject()
ctx: FaaSContext; // context

async handler(event, obj = {}) {
return 'hello world';
}
}
Loading

0 comments on commit 0e93057

Please sign in to comment.