Skip to content

Commit

Permalink
feat(invoke): support keep-alive
Browse files Browse the repository at this point in the history
  • Loading branch information
lou1swu committed Nov 14, 2019
1 parent 807537b commit 23fabbd
Show file tree
Hide file tree
Showing 16 changed files with 235 additions and 65 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@ package-lock.json
yarn.lock
coverage
secret.json
.vscode
.vscode
*.log
3 changes: 2 additions & 1 deletion .npmignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@ package-lock.json
yarn.lock
coverage
secret.json
.vscode
.vscode
*.log
20 changes: 19 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,13 @@ sdk.invoke({
```

## API Reference
- [Init](#Init)
- [Init](#Init)
- [Invoke](#Invoke)

### Init

**init(Params, ExtraParams)**

使用SDK前,可以选择初始化SDK,这个并不是强制要求的操作,只是为了方便调用API接口时,复用初始化的配置。参数中undefined的值会被忽略。

**Params:**
Expand All @@ -47,7 +50,16 @@ sdk.invoke({
| secretKey || string | 默认会取process.env.TENCENTCLOUD_SECRETKEY |
| token || string | 默认会取process.env.TENCENTCLOUD_SESSIONTOKEN |

**ExtraParams:**
| 参数名 | 是否必填 | 类型 | 描述 |
| :-------- | :------: | :----: | -----------------------------------------: |
| forever || boolean | 是否开启keep-alive |
| time || boolean | 是否打印请求耗时统计 |

### Invoke

**invoke(Params, ExtraParams)**

调用函数。暂时只支持同步调用。参数中undefined的值会被忽略。

**Params:**
Expand All @@ -63,6 +75,12 @@ sdk.invoke({
| secretKey || string | 默认会取process.env.TENCENTCLOUD_SECRETKEY |
| token || string | 默认会取process.env.TENCENTCLOUD_SESSIONTOKEN |

**ExtraParams:**
| 参数名 | 是否必填 | 类型 | 描述 |
| :-------- | :------: | :----: | -----------------------------------------: |
| forever || boolean | 是否开启keep-alive |
| time || boolean | 是否打印请求耗时统计 |

**Return:**

正常调用的返回结果为**被调用**的云函数的返回值。
Expand Down
95 changes: 58 additions & 37 deletions __tests__/invoke.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,12 @@ const LabelResourceNotFound = String('ResourceNotFound.FunctionName')

const sdk = require('../dist/index')

const extraParams = {
forever: true,
time: true,
strictSSL: false
}

let secret = {
secretId: process.env.TENCENTCLOUD_SECRETID,
secretKey: process.env.TENCENTCLOUD_SECRETKEY
Expand Down Expand Up @@ -36,11 +42,14 @@ const functionReturnError = {
}

describe('Test Api With Init', () => {
sdk.init({
region,
secretId: secret.secretId,
secretKey: secret.secretKey
})
sdk.init(
{
region,
secretId: secret.secretId,
secretKey: secret.secretKey
},
extraParams
)
test(
'Test Invoke Correct',
async () => {
Expand Down Expand Up @@ -78,29 +87,35 @@ describe('Test Api Without Init', () => {
test(
'Test Invoke Correct With secret dominantly',
async () => {
const res = await sdk.invoke({
region,
secretId: secret.secretId,
secretKey: secret.secretKey,
token: undefined,
functionName: functionReturnCorrect.functionName,
version: functionReturnCorrect.version,
data: JSON.stringify(functionReturnCorrect.clientContext),
namespace: functionReturnCorrect.namespace
})
const res = await sdk.invoke(
{
region,
secretId: secret.secretId,
secretKey: secret.secretKey,
token: undefined,
functionName: functionReturnCorrect.functionName,
version: functionReturnCorrect.version,
data: JSON.stringify(functionReturnCorrect.clientContext),
namespace: functionReturnCorrect.namespace
},
extraParams
)
expect(res).toBe(JSON.stringify('test'))
},
10 * 1000
)
test(
'Test Invoke Correct With secret implicitly',
async () => {
const res = await sdk.invoke({
functionName: functionReturnCorrect.functionName,
version: functionReturnCorrect.version,
data: JSON.stringify(functionReturnCorrect.clientContext),
namespace: functionReturnCorrect.namespace
})
const res = await sdk.invoke(
{
functionName: functionReturnCorrect.functionName,
version: functionReturnCorrect.version,
data: JSON.stringify(functionReturnCorrect.clientContext),
namespace: functionReturnCorrect.namespace
},
extraParams
)
expect(res).toBe(JSON.stringify('test'))
},
10 * 1000
Expand All @@ -109,29 +124,35 @@ describe('Test Api Without Init', () => {
test(
'Test Invoke Error With secret dominantly',
async () => {
const res = await sdk.invoke({
region,
secretId: secret.secretId,
secretKey: secret.secretKey,
token: undefined,
functionName: functionReturnError.functionName,
version: functionReturnError.version,
data: JSON.stringify(functionReturnError.clientContext),
namespace: functionReturnError.namespace
})
const res = await sdk.invoke(
{
region,
secretId: secret.secretId,
secretKey: secret.secretKey,
token: undefined,
functionName: functionReturnError.functionName,
version: functionReturnError.version,
data: JSON.stringify(functionReturnError.clientContext),
namespace: functionReturnError.namespace
},
extraParams
)
expect(res.error.code).toBe(LabelResourceNotFound)
},
10 * 1000
)
test(
'Test Invoke Error With secret implicitly',
async () => {
const res = await sdk.invoke({
functionName: functionReturnError.functionName,
version: functionReturnError.version,
data: JSON.stringify(functionReturnError.clientContext),
namespace: functionReturnError.namespace
})
const res = await sdk.invoke(
{
functionName: functionReturnError.functionName,
version: functionReturnError.version,
data: JSON.stringify(functionReturnError.clientContext),
namespace: functionReturnError.namespace
},
extraParams
)
expect(res.error.code).toBe(LabelResourceNotFound)
},
10 * 1000
Expand Down
3 changes: 3 additions & 0 deletions dist/helper/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,6 @@ export interface InitConfig {
token?: string;
region?: string;
}
export interface ExtraParams {
forever?: boolean;
}
1 change: 1 addition & 0 deletions dist/helper/utils.d.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export declare const emptyOp: () => void;
export declare const clone: (obj: object) => object;
export declare const isType: (type: string) => (obj: any) => boolean;
export declare const caseFormat: (type: 'lower' | 'upper') => (string: string) => string;
Expand Down
1 change: 1 addition & 0 deletions dist/helper/utils.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.emptyOp = () => { };
exports.clone = function (obj) {
try {
return JSON.parse(JSON.stringify(obj, (key, value) => {
Expand Down
5 changes: 3 additions & 2 deletions dist/index.d.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import * as services from './services';
import { InitConfig } from './helper/types';
import { InitConfig, ExtraParams } from './helper/types';
declare class SDK {
config: InitConfig;
requestHelper: any;
init(config?: InitConfig): void;
extraParams: ExtraParams;
init(config?: InitConfig, extraParams?: ExtraParams): void;
_reset(): void;
invoke: typeof services.invoke;
}
Expand Down
48 changes: 45 additions & 3 deletions dist/index.js
Original file line number Diff line number Diff line change
@@ -1,23 +1,55 @@
"use strict";
const services = require("./services");
const Capi = require("qcloudapi-sdk");
const util = require("util");
const error_1 = require("./helper/error");
const assign = require("object-assign");
const qs = require("querystring");
const request = require("request");
const _ = require("lodash");
Capi.prototype.request = function (data, opts, callback, extra) {
if (typeof opts === 'function') {
callback = opts;
opts = this.defaults;
}
opts = opts || this.defaults;
callback = callback || Function.prototype;
var url = this.generateUrl(opts);
var method = (opts.method || this.defaults.method).toUpperCase();
var dataStr = this.generateQueryString(data, opts);
var option = { url: url, method: method, json: true, strictSSL: false };
var maxKeys = opts.maxKeys === undefined ? this.defaults.maxKeys : opts.maxKeys;
if (method === 'POST') {
option['form'] = qs.parse(dataStr, null, null, {
maxKeys: maxKeys
});
}
else {
option.url += '?' + dataStr;
}
assign(option, extra);
request(option, function (error, response, body) {
callback(error, response, body);
});
};
class SDK {
constructor() {
this.invoke = services.invoke;
}
init(config) {
init(config, extraParams) {
const defaultConfig = {
secretId: process.env.TENCENTCLOUD_SECRETID,
secretKey: process.env.TENCENTCLOUD_SECRETKEY,
token: process.env.TENCENTCLOUD_SESSIONTOKEN,
region: 'ap-guangzhou'
};
const defaultExtraParams = {
forever: true
};
const __config = _.omitBy(_.merge({}, defaultConfig, config), _.isUndefined);
const __extraParams = _.omitBy(_.merge({}, defaultExtraParams, extraParams), _.isUndefined);
if (!__config.secretId || !__config.secretKey)
return console.warn(error_1.ERR_MISSING_SECRET);
this.extraParams = __extraParams;
this.config = __config;
const capi = new Capi({
SecretId: __config.secretId,
Expand All @@ -27,7 +59,17 @@ class SDK {
baseHost: 'tencentcloudapi.com',
protocol: 'https'
});
this.requestHelper = util.promisify(capi.request.bind(capi));
this.requestHelper = (data, opts, extra) => {
return new Promise((res, rej) => {
capi.request(data, opts, (err, response, body) => {
if (err)
return rej(err);
if (__extraParams.time && response)
console.log(response.timingPhases);
res(body);
}, extra);
});
};
}
_reset() {
this.config = null;
Expand Down
4 changes: 2 additions & 2 deletions dist/services/invoke.d.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { APIV3Res, APIV3Error, InitConfig } from '../helper/types';
import { APIV3Res, APIV3Error, InitConfig, ExtraParams } from '../helper/types';
interface Params {
functionName: string;
qualifier?: string;
Expand All @@ -17,5 +17,5 @@ declare type Res = APIV3Res<{
Log: string;
};
}> & APIV3Error;
export default function (params: Params & InitConfig): Promise<Res>;
export default function (params: Params & InitConfig, extraParams?: ExtraParams): Promise<Res>;
export {};
7 changes: 4 additions & 3 deletions dist/services/invoke.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@
Object.defineProperty(exports, "__esModule", { value: true });
const utils_1 = require("../helper/utils");
const _ = require("lodash");
async function default_1(params) {
async function default_1(params, extraParams) {
if (!this.config)
this.init({
secretId: params.secretId,
secretKey: params.secretKey,
token: params.token,
region: params.region
});
}, extraParams);
const requestHelper = this.requestHelper;
const region = this.config.region;
let __params = _.omitBy(_.merge({
Expand All @@ -35,7 +35,8 @@ async function default_1(params) {
{
serviceType: 'scf',
secretKey: params.secretKey || this.config.secretKey
}
},
this.extraParams || extraParams
], 'Response.Result.RetMsg');
}
exports.default = default_1;
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@
"dependencies": {
"lodash": "^4.17.15",
"lodash.merge": "^4.6.2",
"qcloudapi-sdk": "^0.2.1"
"object-assign": "3.0.0",
"qcloudapi-sdk": "^0.2.1",
"request": "^2.88.0"
}
}
5 changes: 5 additions & 0 deletions src/helper/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,8 @@ export interface InitConfig {
token?: string
region?: string
}

export interface ExtraParams {
forever?: boolean
time?: boolean
}
3 changes: 2 additions & 1 deletion src/helper/utils.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
export const emptyOp = () => {}

/**
* 复制一个对象,会抛弃继承属性
* @param obj
Expand Down Expand Up @@ -134,7 +136,6 @@ export async function uniteRes(fn, scope, args, returnKey) {
if (res.Response.Error) {
throw res.Response
}

return caseForObject(getValue(res)(returnKey), 'lower') as any
} catch (e) {
return caseForObject(e, 'lower') as {
Expand Down
Loading

0 comments on commit 23fabbd

Please sign in to comment.