first-api & file-upload

This commit is contained in:
King Wang 2021-06-09 22:38:55 +08:00
parent 6c0c206b05
commit 1e3bfeb987
37 changed files with 491 additions and 3 deletions

View File

@ -6,14 +6,14 @@ Examples for [TSRPC](https://github.com/k8w/tsrpc).
Start local backend server: Start local backend server:
``` ```
cd <project-dir>/backend cd <example-dir>/backend
npm install npm install
npm run dev npm run dev
``` ```
Start local frontend server: Start local frontend server:
``` ```
cd <project-dir>/frontend cd <example-dir>/frontend
npm install npm install
npm run dev npm run dev
``` ```

View File

@ -0,0 +1,4 @@
node_modules
dist
.DS_STORE
uploads

View File

@ -0,0 +1,12 @@
import fs from "fs/promises";
import { ApiCall } from "tsrpc";
import { ReqUpload, ResUpload } from "../shared/protocols/PtlUpload";
export async function ApiUpload(call: ApiCall<ReqUpload, ResUpload>) {
// Write to file, or push to remote OSS...
await fs.writeFile('uploads/' + call.req.fileName, call.req.fileData);
call.succ({
url: 'http://127.0.0.1:3000/uploads/' + call.req.fileName
});
}

View File

@ -0,0 +1,47 @@
import fs from "fs/promises";
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: '*'
});
// Flow: Serve static files
server.flows.preRecvBufferFlow.push(async v => {
let conn = v.conn as HttpConnection;
if (conn.httpReq.method === 'GET') {
if (conn.httpReq.url?.startsWith('/uploads/')) {
let file = await fs.readFile(decodeURIComponent(conn.httpReq.url.replace(/^\//, ''))).catch(e => { });
if (file) {
server.logger.log('GET', conn.httpReq.url);
conn.httpRes.end(file);
return undefined;
}
}
conn.httpRes.end('404 Not Found')
return undefined;
}
return v;
})
// Entry function
async function main() {
// Auto implement APIs
await server.autoImplementApi(path.resolve(__dirname, 'api'));
// Ensure "uploads" dir is exists
await fs.mkdir('uploads').catch(e => { });
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,8 @@
export interface ReqUpload {
fileName: string,
fileData: Uint8Array
}
export interface ResUpload {
url: string;
}

View File

@ -0,0 +1,59 @@
import { ServiceProto } from 'tsrpc-proto';
import { ReqUpload, ResUpload } from './PtlUpload';
export interface ServiceType {
api: {
"Upload": {
req: ReqUpload,
res: ResUpload
}
},
msg: {
}
}
export const serviceProto: ServiceProto<ServiceType> = {
"version": 2,
"services": [
{
"id": 0,
"name": "Upload",
"type": "api"
}
],
"types": {
"PtlUpload/ReqUpload": {
"type": "Interface",
"properties": [
{
"id": 0,
"name": "fileName",
"type": {
"type": "String"
}
},
{
"id": 1,
"name": "fileData",
"type": {
"type": "Buffer",
"arrayType": "Uint8Array"
}
}
]
},
"PtlUpload/ResUpload": {
"type": "Interface",
"properties": [
{
"id": 2,
"name": "url",
"type": {
"type": "String"
}
}
]
}
}
};

View File

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

View File

@ -0,0 +1,24 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TSRPC Example</title>
</head>
<body>
<h1>File Upload</h1>
<div style="background: #f2f2f2; padding: 20px;">
<p><input type="file" /></p>
<p><button>Click to Upload</button></p>
</div>
<ol>
<!-- <li><a href="XXX" target="_blank">XXX</a></li> -->
</ol>
</body>
</html>

View File

@ -0,0 +1,46 @@
import { HttpClient } from 'tsrpc-browser';
import { serviceProto } from './shared/protocols/serviceProto';
let client = new HttpClient(serviceProto, {
server: 'http://127.0.0.1:3000',
logger: console
});
async function upload() {
// Load File
let file = document.querySelector('input[type=file]') as HTMLInputElement;
if (!file.files || !file.files[0]) {
alert('Please select a file')
return;
}
let fileData = await loadFile(file.files[0]);
// Upload
let ret = await client.callApi('Upload', {
fileData: fileData,
fileName: file.files[0].name
});
// Error
if (!ret.isSucc) {
alert(ret.err.message);
return;
}
// Succ
document.querySelector('ol')!.innerHTML += `<li><a href="${ret.res.url}" target="_blank">${ret.res.url}</a></li>\n`;
file.value = '';
alert('Upload successfully!')
}
function loadFile(file: File): Promise<Uint8Array> {
return new Promise(rs => {
let reader = new FileReader();
reader.onload = e => {
rs(new Uint8Array(e.target!.result as ArrayBuffer))
}
reader.readAsArrayBuffer(file);
})
}
document.querySelector('button')!.onclick = upload;

View File

@ -0,0 +1,8 @@
export interface ReqUpload {
fileName: string,
fileData: Uint8Array
}
export interface ResUpload {
url: string;
}

View File

@ -0,0 +1,59 @@
import { ServiceProto } from 'tsrpc-proto';
import { ReqUpload, ResUpload } from './PtlUpload';
export interface ServiceType {
api: {
"Upload": {
req: ReqUpload,
res: ResUpload
}
},
msg: {
}
}
export const serviceProto: ServiceProto<ServiceType> = {
"version": 2,
"services": [
{
"id": 0,
"name": "Upload",
"type": "api"
}
],
"types": {
"PtlUpload/ReqUpload": {
"type": "Interface",
"properties": [
{
"id": 0,
"name": "fileName",
"type": {
"type": "String"
}
},
{
"id": 1,
"name": "fileData",
"type": {
"type": "Buffer",
"arrayType": "Uint8Array"
}
}
]
},
"PtlUpload/ResUpload": {
"type": "Interface",
"properties": [
{
"id": 2,
"name": "url",
"type": {
"type": "String"
}
}
]
}
}
};

3
examples/first-api/backend/.gitignore vendored Normal file
View File

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

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": "first-api-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.12.2",
"onchange": "^7.1.0",
"ts-node": "^9.1.1",
"tsrpc-cli": "^2.0.1-dev.11",
"typescript": "^4.3.2"
},
"dependencies": {
"tsrpc": "^3.0.0-dev.17"
}
}

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,3 @@
node_modules
dist
.DS_STORE

View File

@ -0,0 +1,21 @@
{
"name": "first-api-frontend",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "webpack serve --mode=development --open",
"build": "webpack --mode=production"
},
"devDependencies": {
"copy-webpack-plugin": "^9.0.0",
"html-webpack-plugin": "^5.3.1",
"ts-loader": "^9.2.3",
"typescript": "^4.3.2",
"webpack": "^5.38.1",
"webpack-cli": "^4.7.2",
"webpack-dev-server": "^3.11.2"
},
"dependencies": {
"tsrpc-browser": "^3.0.0-dev.15"
}
}

View File

@ -1,13 +1,14 @@
import { HttpClient } from 'tsrpc-browser'; import { HttpClient } from 'tsrpc-browser';
import { serviceProto } from './shared/protocols/serviceProto'; import { serviceProto } from './shared/protocols/serviceProto';
// 创建一个 TSRPC Client // Create the Client
let client = new HttpClient(serviceProto, { let client = new HttpClient(serviceProto, {
server: 'http://127.0.0.1:3000', server: 'http://127.0.0.1:3000',
logger: console logger: console
}); });
async function test() { async function test() {
// callApi
let ret = await client.callApi('Hello', { let ret = await client.callApi('Hello', {
name: 'World' name: 'World'
}); });

View File

@ -0,0 +1,23 @@
{
"compilerOptions": {
"lib": [
"dom",
"es2018"
],
"module": "esnext",
"target": "es2018",
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"moduleResolution": "node",
"outDir": "dist",
"skipLibCheck": true,
"strict": true,
"jsx": "react-jsx",
"sourceMap": true,
"isolatedModules": true
},
"include": [
"src"
]
}

View File

@ -0,0 +1,58 @@
const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const isProduction = process.argv.indexOf('--mode=production') > -1;
module.exports = {
entry: './src/index.ts',
output: {
filename: 'bundle.[contenthash].js',
path: path.resolve(__dirname, 'dist'),
clean: true
},
resolve: {
extensions: ['.ts', '.tsx', '.js']
},
module: {
rules: [
{
test: /\.tsx?$/,
use: [{
loader: 'ts-loader',
options: {
compilerOptions: isProduction ? {
"lib": [
"dom",
"es2015.promise"
],
"target": "es5",
} : undefined
}
}],
exclude: /node_modules/
},
]
},
plugins: [
// Copy "public" to "dist"
new CopyWebpackPlugin({
patterns: [{
from: 'public',
to: '.',
toType: 'dir',
globOptions: {
gitignore: true,
ignore: [path.resolve(__dirname, 'public/index.html').replace(/\\/g, '/')]
},
noErrorOnMissing: true
}]
}),
// Auto add <script> to "index.html"
new HtmlWebpackPlugin({
template: 'public/index.html'
}),
],
devtool: isProduction ? false : 'inline-source-map'
}