custom http res

This commit is contained in:
King Wang 2021-06-29 23:48:07 +08:00
parent ebccb16d6d
commit ddc8ecdf49
16 changed files with 403 additions and 0 deletions

3
examples/custom-http-res/.gitignore vendored Normal file
View File

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

View File

@ -0,0 +1,8 @@
module.exports = {
require: [
'ts-node/register',
],
timeout: 999999,
exit: true,
'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,39 @@
# TSRPC Server
## Run
### Local Dev Server
```
npm run dev
```
### Unit Test
Execute `npm run dev` first, then execute:
```
npm run test
```
### 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,26 @@
{
"name": "custom-http-res-.",
"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\"",
"test": "mocha test/**/*.test.ts",
"build": "tsrpc build"
},
"devDependencies": {
"@types/mocha": "^8.2.2",
"@types/node": "^15.12.5",
"mocha": "^9.0.1",
"onchange": "^7.1.0",
"ts-node": "^10.0.0",
"tsrpc-cli": "^2.0.3",
"typescript": "^4.3.4"
},
"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,45 @@
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: '*'
});
// Custom HTTP Reponse
server.flows.preRecvBufferFlow.push(v => {
let conn = v.conn as HttpConnection;
if (conn.httpReq.method === 'GET') {
// 特定 URL: /test
if (conn.httpReq.url === '/test') {
conn.httpRes.end('test test')
return undefined;
}
// 默认 GET 响应
conn.httpRes.end('Hello World');
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,30 @@
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('ApiAddData', function () {
let client = new HttpClient(serviceProto, {
server: 'http://127.0.0.1:3000',
logger: console
});
it('Success', async function () {
let ret = await client.callApi('AddData', {
content: 'TEST'
});
assert.strictEqual(ret.isSucc, true);
});
it('Error', 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,26 @@
import assert from 'assert';
import { HttpClient } 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('Add & Get', async function () {
let ret1 = await client.callApi('GetData', {});
assert.strictEqual(ret1.isSucc, true);
let ret2 = await client.callApi('AddData', { content: 'AABBCC' });
assert.strictEqual(ret2.isSucc, true);
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');
});
})

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"
]
}