layaair-example

This commit is contained in:
King Wang
2021-07-21 23:11:13 +08:00
parent c3aa1f918e
commit 4bfe797a89
203 changed files with 257823 additions and 0 deletions

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,35 @@
# TSRPC Server
## Run
### Local Dev Server
```
npm run dev
```
### Build
```
npm run build
```
---
## Files
### Generate ServiceProto
```
npm run proto
```
### Generate API templates
```
npm run api
```
### Sync shared code to client
```
npm run sync
```
> If you chose symlink when using `create-tsrpc-app`, it would re-create the symlink instead of copy files.

View File

@@ -0,0 +1,23 @@
{
"name": "tsrpc-app-backend",
"version": "0.1.0",
"main": "index.js",
"private": true,
"scripts": {
"proto": "tsrpc proto -i src/shared/protocols -o src/shared/protocols/serviceProto.ts",
"sync": "tsrpc sync --from src/shared --to ../frontend/src/shared",
"api": "tsrpc api -i src/shared/protocols/serviceProto.ts -o src/api",
"dev": "onchange \"src/**/*.ts\" -i -k -- ts-node \"src/index.ts\"",
"build": "tsrpc build"
},
"devDependencies": {
"@types/node": "^15.14.1",
"onchange": "^7.1.0",
"ts-node": "^10.0.0",
"tsrpc-cli": "^2.0.3",
"typescript": "^4.3.5"
},
"dependencies": {
"tsrpc": "^3.0.4"
}
}

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,60 @@
import { IncomingMessage } from "http";
import * as path from "path";
import { Counter, HttpConnection, HttpServer } from "tsrpc";
import { serviceProto, ServiceType } from "./shared/protocols/serviceProto";
// Create the Server
const server = new HttpServer(serviceProto, {
port: 3000,
cors: '*'
});
// Init
export async function init(context: any, callback: (err: Error | null, data: any) => void) {
// Auto implement APIs
await server.autoImplementApi(path.resolve(__dirname, 'api'));
callback(null, '');
}
const connCounter = new Counter(1);
// Handler
export function handler(httpReq: IncomingMessage, httpRes: {
setStatusCode: (code: number) => void,
setHeader: (key: string, value: string) => void,
deleteHeader: (key: string) => void,
send: (body: Buffer | string) => void
}, context: any) {
httpRes.setStatusCode(200);
httpRes.setHeader('X-Powered-By', `TSRPC`);
httpRes.setHeader('Access-Control-Allow-Origin', '*');
httpRes.setHeader('Access-Control-Allow-Headers', 'Content-Type,*');
if (httpReq.method === 'OPTIONS') {
httpRes.send('');
return;
}
let chunks: Buffer[] = [];
httpReq.on('data', data => {
chunks.push(data);
});
let conn: HttpConnection<ServiceType> | undefined;
httpReq.on('end', async () => {
let isJSON = false;
conn = new HttpConnection({
server: 'FAAS' as any,
id: '' + connCounter.getNext(),
ip: '???',
httpReq: httpReq,
httpRes: { end: httpRes.send.bind(httpRes) } as any,
isJSON: isJSON
});
await server.flows.postConnectFlow.exec(conn, conn.logger);
let buf = chunks.length === 1 ? chunks[0] : Buffer.concat(chunks);
server['_onRecvBuffer'](conn, buf);
});
}

View File

@@ -0,0 +1,38 @@
import * as path from "path";
import { HttpConnection, HttpServer } from "tsrpc";
import { serviceProto } from "./shared/protocols/serviceProto";
// Create the Server
const server = new HttpServer(serviceProto, {
port: 3000,
cors: '*',
socketTimeout: 0,
keepAliveTimeout: 0
});
server.flows.preRecvBufferFlow.push(v => {
let conn = v.conn as HttpConnection;
if (conn.httpReq.method === 'GET') {
conn.httpRes.end('TSRPC Server');
return undefined;
}
return v;
})
// Entry function
async function main() {
// Auto implement APIs
await server.autoImplementApi(path.resolve(__dirname, 'api'));
// TODO
// Prepare something... (e.g. connect the db)
await server.start();
};
main().catch(e => {
// Exit if any error during the startup
server.logger.error(e);
process.exit(-1);
});

View File

@@ -0,0 +1,10 @@
// This is a demo code file
// Feel free to delete it
export interface ReqAddData {
content: string;
}
export interface ResAddData {
time: Date
}

View File

@@ -0,0 +1,13 @@
// 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,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,18 @@
{
"compilerOptions": {
"lib": [
"es2018"
],
"module": "commonjs",
"target": "es2018",
"outDir": "dist",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"moduleResolution": "node"
},
"include": [
"src"
]
}