提交 a96cb250 作者: Vben

refactor(test-server): improve test service code

上级 8b6e07b7
...@@ -6,7 +6,7 @@ VITE_PUBLIC_PATH = / ...@@ -6,7 +6,7 @@ VITE_PUBLIC_PATH = /
# Cross-domain proxy, you can configure multiple # Cross-domain proxy, you can configure multiple
# Please note that no line breaks # Please note that no line breaks
VITE_PROXY = [["/basic-api","http://localhost:3000"],["/upload","http://localhost:3001/upload"]] VITE_PROXY = [["/basic-api","http://localhost:3000"],["/upload","http://localhost:3300/upload"]]
# VITE_PROXY=[["/api","https://vvbin.cn/test"]] # VITE_PROXY=[["/api","https://vvbin.cn/test"]]
# Delete console # Delete console
......
...@@ -4,7 +4,7 @@ dist ...@@ -4,7 +4,7 @@ dist
.npmrc .npmrc
.cache .cache
test/upload-server/static test/server/static
.local .local
# local env files # local env files
......
{ {
"cSpell.words": ["vben", "windi"],
"typescript.tsdk": "./node_modules/typescript/lib", "typescript.tsdk": "./node_modules/typescript/lib",
"volar.tsPlugin": true, "volar.tsPlugin": true,
"volar.tsPluginStatus": false, "volar.tsPluginStatus": false,
...@@ -26,6 +27,7 @@ ...@@ -26,6 +27,7 @@
"files.trimTrailingWhitespace": true, "files.trimTrailingWhitespace": true,
"files.insertFinalNewline": true, "files.insertFinalNewline": true,
"files.trimFinalNewlines": true, "files.trimFinalNewlines": true,
"files.eol": "\n",
"search.exclude": { "search.exclude": {
"**/node_modules": true, "**/node_modules": true,
"**/*.log": true, "**/*.log": true,
......
...@@ -121,7 +121,7 @@ ...@@ -121,7 +121,7 @@
"vite-plugin-style-import": "^0.10.1", "vite-plugin-style-import": "^0.10.1",
"vite-plugin-svg-icons": "^0.7.0", "vite-plugin-svg-icons": "^0.7.0",
"vite-plugin-theme": "^0.8.1", "vite-plugin-theme": "^0.8.1",
"vite-plugin-windicss": "^0.17.0", "vite-plugin-windicss": "^1.0.1",
"vue-eslint-parser": "^7.6.0", "vue-eslint-parser": "^7.6.0",
"vue-tsc": "^0.1.7" "vue-tsc": "^0.1.7"
}, },
......
...@@ -35,6 +35,7 @@ export default defineComponent({ ...@@ -35,6 +35,7 @@ export default defineComponent({
if (e.ctrlKey || e.button === 2) { if (e.ctrlKey || e.button === 2) {
return; return;
} }
window.getSelection()?.removeAllRanges();
startDrag(e); startDrag(e);
barStore.value[bar.value.axis] = barStore.value[bar.value.axis] =
e.currentTarget[bar.value.offset] - e.currentTarget[bar.value.offset] -
......
...@@ -70,7 +70,7 @@ ...@@ -70,7 +70,7 @@
}, },
setup() { setup() {
const state = reactive({ const state = reactive({
server: 'ws://localhost:3380/test', server: 'ws://localhost:3300/test',
sendValue: '', sendValue: '',
recordList: [] as { id: number; time: number; res: string }[], recordList: [] as { id: number; time: number; res: string }[],
}); });
......
# Test Server
It is used to start the test interface service, which can test the upload, websocket, login and other interfaces.
## Usage
```bash
cd ./test/server
yarn
yarn start
```
const Koa = require('koa');
const router = require('koa-router')();
const cors = require('koa2-cors');
const bodyParser = require('koa-bodyparser');
const app = new Koa();
app.use(cors());
app.use(bodyParser());
router.get('/getTest', (ctx) => {
ctx.body = {
name: 'test',
};
});
router.post('/login', (ctx) => {
ctx.body = {
code: 0,
success: true,
result: {
userId: '1',
username: 'vben',
realName: 'Vben Admin',
desc: 'manager',
password: '123456',
token: 'fakeToken1',
roles: [
{
roleName: 'Super Admin',
value: 'super',
},
],
},
};
});
router.get('/getUserInfoById', (ctx) => {
ctx.body = {
code: 0,
success: true,
result: {
userId: '1',
username: 'vben',
realName: 'Vben Admin',
desc: 'manager',
password: '123456',
token: 'fakeToken1',
roles: [
{
roleName: 'Super Admin',
value: 'super',
},
],
},
};
});
app.use(router.routes()).use(router.allowedMethods());
app.listen(3002, () => {
console.log('server is listen in 3002');
});
{
"name": "upload-server",
"version": "1.0.0",
"main": "app.js",
"license": "MIT",
"scripts": {
"start": "node app.js"
},
"dependencies": {
"fs-extra": "^9.1.0",
"koa": "^2.13.1",
"koa-body": "^4.2.0",
"koa-bodyparser": "^4.3.0",
"koa-router": "^10.0.0",
"koa-static": "^5.0.0",
"koa2-cors": "^2.0.6"
}
}
import FileService from '../service/FileService';
class FileController {
private service: FileService = new FileService();
upload = async (ctx) => {
const files = ctx.request.files.file;
console.log(files);
if (files.length === undefined) {
this.service.upload(ctx, files, false);
} else {
this.service.upload(ctx, files, true);
}
};
}
export default new FileController();
import UserService from '../service/UserService';
class UserController {
private service: UserService = new UserService();
login = async (ctx) => {
ctx.body = await this.service.login();
};
getUserInfoById = async (ctx) => {
ctx.body = await this.service.getUserInfoById();
};
}
export default new UserController();
const { name } = require('./package.json');
const path = require('path');
module.exports = {
apps: [
{
name,
script: path.resolve(__dirname, './dist/index.js'),
instances: require('os').cpus().length,
autorestart: true,
watch: true,
env_production: {
NODE_ENV: 'production',
PORT: 8080,
},
},
],
};
const Koa = require('koa'); import Koa from 'koa';
const route = require('koa-route'); import path from 'path';
const websockify = require('koa-websocket'); import Router from 'koa-router';
import body from 'koa-body';
import cors from 'koa2-cors';
import koaStatic from 'koa-static';
import websockify from 'koa-websocket';
import route from 'koa-route';
import AppRoutes from './routes';
const PORT = 3300;
const app = websockify(new Koa()); const app = websockify(new Koa());
...@@ -16,7 +25,7 @@ app.ws.use( ...@@ -16,7 +25,7 @@ app.ws.use(
// do something with the message from client // do something with the message from client
if (message !== 'ping') { if (message !== 'ping') {
let data = JSON.stringify({ const data = JSON.stringify({
id: Math.ceil(Math.random() * 1000), id: Math.ceil(Math.random() * 1000),
time: new Date().getTime(), time: new Date().getTime(),
res: `${message}`, res: `${message}`,
...@@ -28,6 +37,27 @@ app.ws.use( ...@@ -28,6 +37,27 @@ app.ws.use(
}) })
); );
app.listen(3380, () => { const router = new Router();
console.log('websocket server is listen in: ' + 3380);
// router
AppRoutes.forEach((route) => router[route.method](route.path, route.action));
app.use(cors());
app.use(
body({
encoding: 'gzip',
multipart: true,
formidable: {
// uploadDir: path.join(__dirname, '/upload/'), // 设置文件上传目录
keepExtensions: true,
maxFieldsSize: 20 * 1024 * 1024,
},
})
);
app.use(router.routes());
app.use(router.allowedMethods());
app.use(koaStatic(path.join(__dirname)));
app.listen(PORT, () => {
console.log(`Application started successfully: http://localhost:${PORT}`);
}); });
{
"watch": ["src"],
"ext": "ts",
"exec": "ts-node -r tsconfig-paths/register index.ts",
"events": {
"restart": "clear"
}
}
{
"name": "server",
"version": "1.0.0",
"license": "MIT",
"scripts": {
"start": "nodemon",
"build": "rimraf ./dist && tsup ./index.ts --dts --format cjs,esm ",
"prod": "npx pm2 start ecosystem.config.js --env production",
"restart": "pm2 restart ecosystem.config.js --env production",
"stop": "npx pm2 stop ecosystem.config.js"
},
"dependencies": {
"fs-extra": "^10.0.0",
"koa": "^2.7.0",
"koa-body": "^4.2.0",
"koa-bodyparser": "^4.2.1",
"koa-route": "^3.2.0",
"koa-router": "^10.0.0",
"koa-static": "^5.0.0",
"koa-websocket": "^6.0.0",
"koa2-cors": "^2.0.6"
},
"devDependencies": {
"@types/koa": "^2.0.48",
"@types/koa-bodyparser": "^4.2.2",
"@types/koa-router": "^7.0.40",
"@types/node": "^15.12.1",
"nodemon": "^2.0.7",
"pm2": "^4.5.6",
"rimraf": "^3.0.2",
"ts-node": "^10.0.0",
"tsconfig-paths": "^3.8.0",
"tsup": "^4.11.2",
"typescript": "^4.2.5"
}
}
import UserController from './controller/UserController';
import FileController from './controller/FileController';
export default [
// user
{
path: '/login',
method: 'post',
action: UserController.login,
},
{
path: '/getUserInfoById',
method: 'get',
action: UserController.getUserInfoById,
},
// file
{
path: '/upload',
method: 'post',
action: FileController.upload,
},
];
const Koa = require('koa'); import path from 'path';
const path = require('path'); import fs from 'fs-extra';
const router = require('koa-router')();
const koaBody = require('koa-body'); const uploadUrl = 'http://localhost:3300/static/upload';
const static = require('koa-static'); const filePath = path.join(__dirname, '../static/upload/');
const cors = require('koa2-cors');
const fs = require('fs-extra'); fs.ensureDir(filePath);
const app = new Koa(); export default class UserService {
async upload(ctx, files, isMultiple) {
const uploadUrl = 'http://localhost:3001/static/upload'; let fileReader, fileResource, writeStream;
fs.ensureDir(path.join(__dirname, 'static/upload')); const fileFunc = function (file) {
console.log(file);
app.use(cors());
fileReader = fs.createReadStream(file.path);
app.use( fileResource = filePath + `/${file.name}`;
koaBody({ console.log(fileResource);
multipart: true,
formidable: { writeStream = fs.createWriteStream(fileResource);
maxFieldsSize: 20 * 1024 * 1024, fileReader.pipe(writeStream);
multipart: true, };
},
}) const returnFunc = function (flag) {
); if (flag) {
let url = '';
router.get('/', (ctx) => { for (let i = 0; i < files.length; i++) {
ctx.type = 'html'; url += uploadUrl + `/${files[i].name},`;
const pathUrl = path.join(__dirname, '/static/upload.html'); }
ctx.body = fs.createReadStream(pathUrl); url = url.replace(/,$/gi, '');
}); ctx.body = {
url: url,
const uploadFilePublic = function (ctx, files, flag) { code: 0,
const filePath = path.join(__dirname, '/static/upload/'); message: 'upload Success!',
let fileReader, fileResource, writeStream; };
} else {
const fileFunc = function (file) { ctx.body = {
fileReader = fs.createReadStream(file.path); url: uploadUrl + `/${files.name}`,
fileResource = filePath + `/${file.name}`; code: 0,
message: 'upload Success!',
};
}
};
console.log(isMultiple, files.length);
writeStream = fs.createWriteStream(fileResource); if (isMultiple) {
fileReader.pipe(writeStream);
};
const returnFunc = function (flag) {
console.log(flag);
console.log(files);
if (flag) {
let url = '';
for (let i = 0; i < files.length; i++) { for (let i = 0; i < files.length; i++) {
url += uploadUrl + `/${files[i].name},`; const f1 = files[i];
fileFunc(f1);
} }
url = url.replace(/,$/gi, '');
ctx.body = {
url: url,
code: 0,
message: 'upload Success!',
};
} else { } else {
ctx.body = { fileFunc(files);
url: uploadUrl + `/${files.name}`,
code: 0,
message: 'upload Success!',
};
}
};
if (flag) {
for (let i = 0; i < files.length; i++) {
const f1 = files[i];
fileFunc(f1);
} }
} else { fs.ensureDir(filePath);
fileFunc(files); returnFunc(isMultiple);
} }
}
if (!fs.existsSync(filePath)) {
fs.mkdir(filePath, (err) => {
if (err) {
throw new Error(err);
} else {
returnFunc(flag);
}
});
} else {
returnFunc(flag);
}
};
router.post('/upload', (ctx) => {
let files = ctx.request.files.file;
if (files.length === undefined) {
uploadFilePublic(ctx, files, false);
} else {
uploadFilePublic(ctx, files, true);
}
});
app.use(static(path.join(__dirname)));
app.use(router.routes()).use(router.allowedMethods());
app.listen(3001, () => {
console.log('server is listen in 3001');
});
import { Result } from '../utils';
const fakeUserInfo = {
userId: '1',
username: 'vben',
realName: 'Vben Admin',
desc: 'manager',
password: '123456',
token: 'fakeToken1',
roles: [
{
roleName: 'Super Admin',
value: 'super',
},
],
};
export default class UserService {
async login() {
return Result.success(fakeUserInfo);
}
async getUserInfoById() {
return Result.success(fakeUserInfo);
}
}
{
"compilerOptions": {
"module": "commonjs",
"declaration": false,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "es6",
"sourceMap": false,
"esModuleInterop": true,
"outDir": "./dist",
"baseUrl": "./"
},
"exclude": ["node_modules"]
}
# Upload Server
Simple file upload service for testing file upload components.
## Usage
```js
cd ./test/upload-server
yarn install
yarn start
```
{
"name": "upload-server",
"version": "1.0.0",
"main": "app.js",
"license": "MIT",
"scripts": {
"start": "node app.js"
},
"dependencies": {
"fs-extra": "^9.1.0",
"koa": "^2.13.1",
"koa-body": "^4.2.0",
"koa-router": "^10.0.0",
"koa-static": "^5.0.0",
"koa2-cors": "^2.0.6"
}
}
export class Result {
static success(data: any) {
return {
code: 0,
success: true,
result: data,
};
}
}
# Websocket Server
Simple background for testing ws interface
## Usage
```js
cd ./test/websocket-server
yarn install
yarn start
```
{
"name": "websocket-server",
"version": "1.0.0",
"main": "app.js",
"license": "MIT",
"scripts": {
"start": "node app.js"
},
"dependencies": {
"fs-extra": "^9.1.0",
"koa": "^2.13.1",
"koa-route": "^3.2.0",
"koa-websocket": "^6.0.0"
}
}
This source diff could not be displayed because it is too large. You can view the blob instead.
...@@ -2048,10 +2048,10 @@ ...@@ -2048,10 +2048,10 @@
dependencies: dependencies:
vue-demi "*" vue-demi "*"
"@windicss/plugin-utils@0.17.0": "@windicss/plugin-utils@1.0.1":
version "0.17.0" version "1.0.1"
resolved "https://registry.npmjs.org/@windicss/plugin-utils/-/plugin-utils-0.17.0.tgz#c12123d6025b0aa439932aeef01467b58c4cc6a1" resolved "https://registry.npmjs.org/@windicss/plugin-utils/-/plugin-utils-1.0.1.tgz#f6281c91a37be5ea48eb4573cb511ccb82cce16a"
integrity sha512-abRdBdA0hZKuixWq8a7bdi5KNvLEGtcQSGcE6mV83Xbjs8XWYY/S8g7Icy4g/0/SQLW2cda+jj14hkYTMlk5fw== integrity sha512-EHsGC9LGHC/3rWNiOHzkgkexwgmxfHsqvxBoh0hLJv1MPPhEsKv8dQbt34pVZgRsS/rAjiVe4bRRM5NLTy8cWA==
dependencies: dependencies:
"@antfu/utils" "^0.1.6" "@antfu/utils" "^0.1.6"
debug "^4.3.2" debug "^4.3.2"
...@@ -2059,7 +2059,7 @@ ...@@ -2059,7 +2059,7 @@
jiti "^1.10.1" jiti "^1.10.1"
magic-string "^0.25.7" magic-string "^0.25.7"
micromatch "^4.0.4" micromatch "^4.0.4"
windicss "^3.0.12" windicss "^3.1.0"
"@zxcvbn-ts/core@^0.3.0": "@zxcvbn-ts/core@^0.3.0":
version "0.3.0" version "0.3.0"
...@@ -10639,15 +10639,15 @@ vite-plugin-theme@^0.8.1: ...@@ -10639,15 +10639,15 @@ vite-plugin-theme@^0.8.1:
esbuild-plugin-alias "^0.1.2" esbuild-plugin-alias "^0.1.2"
tinycolor2 "^1.4.2" tinycolor2 "^1.4.2"
vite-plugin-windicss@^0.17.0: vite-plugin-windicss@^1.0.1:
version "0.17.0" version "1.0.1"
resolved "https://registry.npmjs.org/vite-plugin-windicss/-/vite-plugin-windicss-0.17.0.tgz#721a82e1b9be165364fbed319ce2fc5059b43866" resolved "https://registry.npmjs.org/vite-plugin-windicss/-/vite-plugin-windicss-1.0.1.tgz#6e455228b6c1cb7ad52ed8fb9408b39888d572c0"
integrity sha512-zbx4J209cqxPpJECWr8nwqDMloUvMmni+GJFvrVBboU0bb/0+mXFQj9VMVsbe7Ac00/vC0i7D0ml65x1PiXf4w== integrity sha512-+6iFKUC00G9xkR967xqbbAquaWAmgYT1rlBP7Bp6XCd9ire3b7tJTETtwSPAPAIp38OA/Xbp1MSaHhbl2LRxJg==
dependencies: dependencies:
"@windicss/plugin-utils" "0.17.0" "@windicss/plugin-utils" "1.0.1"
chalk "^4.1.1" chalk "^4.1.1"
debug "^4.3.2" debug "^4.3.2"
windicss "^3.0.12" windicss "^3.1.0"
vite@2.3.6: vite@2.3.6:
version "2.3.6" version "2.3.6"
...@@ -10939,10 +10939,10 @@ widest-line@^2.0.0: ...@@ -10939,10 +10939,10 @@ widest-line@^2.0.0:
dependencies: dependencies:
string-width "^2.1.1" string-width "^2.1.1"
windicss@^3.0.12: windicss@^3.1.0:
version "3.0.12" version "3.1.0"
resolved "https://registry.yarnpkg.com/windicss/-/windicss-3.0.12.tgz#4354aaa48faaac6fd02f3119a62587da2c46b018" resolved "https://registry.npmjs.org/windicss/-/windicss-3.1.0.tgz#bd679d51b7cabeba09077085706b48dbc1515730"
integrity sha512-pDxtFLN0xmL7bnGtnEfu9z7B5279UM2EP8wWlPH+FYb5gjHyONxRtyWtR5QIn1FRx6h1UXpm+I19GgTx5Y4TyA== integrity sha512-z49xITq4X1ltHIZyL4NwFTR2LXPJ0rbOOrhDXfLX+OfG4Au7+GAzqvNlzUfAaIbA8HSpnI04alQHUWH24KfNYA==
with@^7.0.0: with@^7.0.0:
version "7.0.2" version "7.0.2"
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论