云函数 examples

This commit is contained in:
k8w
2021-12-23 23:36:33 +08:00
parent ed409795d9
commit 82663162b7
35 changed files with 5767 additions and 0 deletions

View File

@@ -0,0 +1,3 @@
node_modules
dist
.DS_STORE

View File

@@ -0,0 +1,11 @@
module.exports = {
require: [
'ts-node/register',
],
timeout: 999999,
exit: true,
spec: [
'./test/**/*.test.ts'
],
'preserve-symlinks': true
}

View File

@@ -0,0 +1,30 @@
{
"configurations": [
{
"type": "node",
"request": "launch",
"name": "mocha current file",
"program": "${workspaceFolder}/node_modules/mocha/bin/_mocha",
"args": [
"${file}"
],
"internalConsoleOptions": "openOnSessionStart",
"cwd": "${workspaceFolder}"
},
{
"type": "node",
"request": "launch",
"name": "ts-node current file",
"protocol": "inspector",
"args": [
"${relativeFile}"
],
"cwd": "${workspaceRoot}",
"runtimeArgs": [
"-r",
"ts-node/register"
],
"internalConsoleOptions": "openOnSessionStart"
}
]
}

View File

@@ -0,0 +1,3 @@
{
"typescript.tsdk": "node_modules\\typescript\\lib"
}

View File

@@ -0,0 +1,30 @@
FROM node
# 使用淘宝 NPM 镜像(国内机器构建推荐启用)
# RUN npm config set registry https://registry.npm.taobao.org/
# npm install
ADD package*.json /src/
WORKDIR /src
RUN npm i
# build
ADD . /src
RUN npm run build
# clean
RUN npm prune --production
# move
RUN rm -rf /app \
&& mv dist /app \
&& mv node_modules /app/ \
&& rm -rf /src
# ENV
ENV NODE_ENV production
EXPOSE 3000
WORKDIR /app
CMD node index.js

View File

@@ -0,0 +1,31 @@
# TSRPC Server
## Usage
### Local dev server
Dev server would restart automatically when code changed.
```
npm run dev
```
### Build
```
npm run build
```
### Generate API document
Generate API document in swagger/openapi and markdown format.
```shell
npm run doc
```
### Run unit Test
Execute `npm run dev` first, then execute:
```
npm run test
```
---

View File

@@ -0,0 +1,24 @@
{
"name": "serverless-faas-backend",
"version": "0.1.0",
"main": "index.js",
"private": true,
"scripts": {
"dev": "tsrpc-cli dev",
"build": "tsrpc-cli build",
"doc": "tsrpc-cli doc",
"test": "mocha test/**/*.test.ts"
},
"devDependencies": {
"@types/mocha": "^8.2.3",
"@types/node": "^15.14.9",
"mocha": "^9.1.3",
"onchange": "^7.1.0",
"ts-node": "^10.4.0",
"tsrpc-cli": "^2.3.0",
"typescript": "^4.5.4"
},
"dependencies": {
"tsrpc": "^3.1.4"
}
}

View File

@@ -0,0 +1,26 @@
// 阿里云 - 函数计算FC
// https://cloud.tencent.com/product/scf
import { init, server } from "./models/server";
// 阿里云函数计算 - HTTP函数
export async function handler(req: any, res: any, context: any) {
// JSON 请求
if (req.headers['content-type']?.includes('application/json')) {
let apiName = req.path.slice(1); // 去除开头的 "/"
let ret = await server.inputJSON(apiName, JSON.parse(req.body));
res.setStatusCode(ret.isSucc ? 200 : 500);
res.send(JSON.stringify(ret));
}
// 二进制请求
else {
let output = await server.inputBuffer(req.body);
res.send(Buffer.from(output));
}
}
// 阿里云函数计算 - 初始化
export async function initializer(context: unknown, callback: Function) {
await init();
callback();
}

View File

@@ -0,0 +1,26 @@
import { ApiCall } from "tsrpc";
import { ReqAddData, ResAddData } from "../shared/protocols/PtlAddData";
import { AllData } from "./ApiGetData";
// This is a demo code file
// Feel free to delete it
export async function ApiAddData(call: ApiCall<ReqAddData, ResAddData>) {
// Error
if (call.req.content === '') {
call.error('Content is empty');
return;
}
let time = new Date();
AllData.unshift({
content: call.req.content,
time: time
})
console.log('AllData', AllData)
// Success
call.succ({
time: time
});
}

View File

@@ -0,0 +1,13 @@
import { ApiCall } from "tsrpc";
import { ReqGetData, ResGetData } from "../shared/protocols/PtlGetData";
// This is a demo code file
// Feel free to delete it
export async function ApiGetData(call: ApiCall<ReqGetData, ResGetData>) {
call.succ({
data: AllData
})
}
export const AllData: { content: string, time: Date }[] = [];

View File

@@ -0,0 +1,8 @@
import { init, server } from "./models/server";
// 普通 NodeJS 环境入口点
async function main() {
await init();
await server.start();
};
main();

View File

@@ -0,0 +1,19 @@
import path from "path";
import { HttpServer } from "tsrpc";
import { serviceProto } from "../shared/protocols/serviceProto";
// Create the Server
export const server = new HttpServer(serviceProto, {
port: 3000,
// Remove this to use binary mode (remove from the client too)
json: true
});
// Initialize before server start
export async function init(delay?: boolean) {
// Auto implement APIs
await server.autoImplementApi(path.resolve(__dirname, '../api/'), delay);
// TODO
// Prepare something... (e.g. connect the db)
};

View File

@@ -0,0 +1,16 @@
// This is a demo code file
// Feel free to delete it
/**
* 增加数据
* 此处的注释将会自动附带到生成的 API 文档中
*/
export interface ReqAddData {
/** 要增加的消息内容 */
content: string;
}
export interface ResAddData {
/** 服务端内容创建时间 */
time: Date
}

View File

@@ -0,0 +1,19 @@
// This is a demo code file
// Feel free to delete it
/**
* 获取数据
*/
export interface ReqGetData {
}
export interface ResGetData {
/** 返回所有数据列表 */
data: {
/** 消息内容 */
content: string,
/** 创建时间 */
time: Date
}[]
}

View File

@@ -0,0 +1,11 @@
export interface BaseRequest {
}
export interface BaseResponse {
}
export interface BaseConf {
}

View File

@@ -0,0 +1,98 @@
import { ServiceProto } from 'tsrpc-proto';
import { ReqAddData, ResAddData } from './PtlAddData';
import { ReqGetData, ResGetData } from './PtlGetData';
// This is a demo service proto file (auto generated)
// Feel free to delete it
export interface ServiceType {
api: {
"AddData": {
req: ReqAddData,
res: ResAddData
},
"GetData": {
req: ReqGetData,
res: ResGetData
}
},
msg: {
}
}
export const serviceProto: ServiceProto<ServiceType> = {
"version": 1,
"services": [
{
"id": 0,
"name": "AddData",
"type": "api"
},
{
"id": 1,
"name": "GetData",
"type": "api"
}
],
"types": {
"PtlAddData/ReqAddData": {
"type": "Interface",
"properties": [
{
"id": 0,
"name": "content",
"type": {
"type": "String"
}
}
]
},
"PtlAddData/ResAddData": {
"type": "Interface",
"properties": [
{
"id": 0,
"name": "time",
"type": {
"type": "Date"
}
}
]
},
"PtlGetData/ReqGetData": {
"type": "Interface"
},
"PtlGetData/ResGetData": {
"type": "Interface",
"properties": [
{
"id": 0,
"name": "data",
"type": {
"type": "Array",
"elementType": {
"type": "Interface",
"properties": [
{
"id": 0,
"name": "content",
"type": {
"type": "String"
}
},
{
"id": 1,
"name": "time",
"type": {
"type": "Date"
}
}
]
}
}
}
]
}
}
};

View File

@@ -0,0 +1,26 @@
// 腾讯云 - 云函数SCF
// https://cloud.tencent.com/product/scf
import { init, server } from "./models/server";
export async function handler(event: any, context: any) {
// init
await ensureInit();
let apiName = event.path.slice(event.requestContext.path.length + 1); // 从 URL 中提取 ApiName
let ret = await server.inputJSON(apiName, JSON.parse(event.body));
return {
"statusCode": ret.isSucc ? 200 : 500,
"headers": { "Content-Type": "application/json" },
"body": JSON.stringify(ret)
}
}
let promiseInit: Promise<void> | undefined;
async function ensureInit() {
if (!promiseInit) {
promiseInit = init(true);
}
return promiseInit;
}

View File

@@ -0,0 +1,39 @@
import assert from 'assert';
import { HttpClient, TsrpcError } from 'tsrpc';
import { serviceProto } from '../../src/shared/protocols/serviceProto';
// 1. EXECUTE `npm run dev` TO START A LOCAL DEV SERVER
// 2. EXECUTE `npm test` TO START UNIT TEST
describe('ApiGetData', function () {
let client = new HttpClient(serviceProto, {
server: 'http://127.0.0.1:3000',
logger: console
});
it('AddData & GetData', async function () {
// Get data before add
let ret1 = await client.callApi('GetData', {});
assert.strictEqual(ret1.isSucc, true);
// AddData
let ret2 = await client.callApi('AddData', { content: 'AABBCC' });
assert.strictEqual(ret2.isSucc, true);
// Get data again, the new data should appear
let ret3 = await client.callApi('GetData', {});
assert.strictEqual(ret3.isSucc, true);
assert.strictEqual(ret3.res!.data.length, ret1.res!.data.length + 1);
assert.strictEqual(ret3.res!.data[0].content, 'AABBCC');
});
it('AddData: Check content is empty', async function () {
let ret = await client.callApi('AddData', {
content: ''
});
assert.deepStrictEqual(ret, {
isSucc: false,
err: new TsrpcError('Content is empty')
});
})
})

View File

@@ -0,0 +1,15 @@
{
"compilerOptions": {
"lib": [
"es2018"
],
"module": "commonjs",
"target": "es2018",
"outDir": "dist",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"moduleResolution": "node"
}
}

View File

@@ -0,0 +1,18 @@
{
"compilerOptions": {
"lib": [
"es2018"
],
"module": "commonjs",
"target": "es2018",
"outDir": "dist",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"moduleResolution": "node"
},
"include": [
"src"
]
}

View File

@@ -0,0 +1,39 @@
import { CodeTemplate, TsrpcConfig } from 'tsrpc-cli';
const tsrpcConf: TsrpcConfig = {
// Generate ServiceProto
proto: [
{
ptlDir: 'src/shared/protocols', // Protocol dir
output: 'src/shared/protocols/serviceProto.ts', // Path for generated ServiceProto
apiDir: 'src/api', // API dir
docDir: 'docs', // API documents dir
ptlTemplate: CodeTemplate.getExtendedPtl(),
// msgTemplate: CodeTemplate.getExtendedMsg(),
}
],
// Sync shared code
sync: [
{
from: 'src/shared',
to: '../frontend/src/shared',
type: 'symlink' // Change this to 'copy' if your environment not support symlink
}
],
// Dev server
dev: {
autoProto: true, // Auto regenerate proto
autoSync: true, // Auto sync when file changed
autoApi: true, // Auto create API when ServiceProto updated
watch: 'src', // Restart dev server when these files changed
entry: 'src/index.ts', // Dev server command: node -r ts-node/register {entry}
},
// Build config
build: {
autoProto: true, // Auto generate proto before build
autoSync: true, // Auto sync before build
autoApi: true, // Auto generate API before build
outDir: 'dist', // Clean this dir before build
}
}
export default tsrpcConf;

File diff suppressed because it is too large Load Diff