feat: 简化工程启动方式,优化部分交互内容

This commit is contained in:
sudoooooo 2023-11-14 04:21:18 +08:00
parent 739cfece3b
commit fa2908dd74
20 changed files with 147 additions and 7073 deletions

View File

@ -81,11 +81,12 @@ git clone http://github.com/didi/xiaoju-survey
### 安装依赖
```shell
cd server
sh init.sh
```
### 启动
```shell
npm run local // 无需安装mongo
npm run dev
```

View File

@ -4,15 +4,16 @@
"description": "survey server template",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"copy": "cp -rf ./src/ ./build/",
"build": "tsc",
"launch": "npm run build && SERVER_ENV=local node ./build/index.js",
"start:stable": "SERVER_ENV=stable node ./build/index.js",
"start:preonline": "SERVER_ENV=preonline node ./build/index.js",
"start:online": "SERVER_ENV=online node ./build/index.js",
"start": "npm run copy && npm run launch",
"dev": "npm run copy && nodemon -e js,mjs,json,ts --exec 'npm run launch' --watch ./src"
"launch:local": "npm run build && SERVER_ENV=local node ./build/index.js",
"launch:dev": "npm run build && SERVER_ENV=dev node ./build/index.js",
"start:stable": "npm run copy && npm run build && SERVER_ENV=stable node ./build/index.js",
"start:preonline": "npm run copy && npm run build && SERVER_ENV=preonline node ./build/index.js",
"start:online": "npm run copy && npm run build && SERVER_ENV=online node ./build/index.js",
"start": "npm run start:online",
"local": "npm run copy && nodemon -e js,mjs,json,ts --exec 'npm run launch:local' --watch ./src",
"dev": "npm run copy && nodemon -e js,mjs,json,ts --exec 'npm run launch:dev' --watch ./src"
},
"devDependencies": {
"nodemon": "^2.0.20",
@ -22,13 +23,19 @@
"@types/koa": "^2.13.8",
"@types/koa-bodyparser": "^4.3.10",
"@types/koa-router": "^7.4.4",
"joi": "^17.9.2",
"jsonwebtoken": "^9.0.1",
"koa": "^2.14.2",
"koa-bodyparser": "^4.4.1",
"koa-pino-logger": "^4.0.0",
"koa-router": "^12.0.0"
"koa-router": "^12.0.0",
"lodash": "^4.17.21",
"moment": "^2.29.4",
"mongodb": "^5.7.0",
"mongodb-memory-server": "^9.0.1"
},
"engines": {
"node": ">=14.15.4",
"npm": ">=6.14.10"
"node": ">=14.21.0",
"npm": ">=6.14.17"
}
}

View File

@ -1,5 +1,6 @@
import { Collection, MongoClient, ObjectId } from 'mongodb'
import { getConfig } from '../config/index'
import { getMongoMemoryUri } from '../../../getMongoMemoryUri'
const config = getConfig()
@ -9,7 +10,12 @@ class mongoService {
constructor() {
this.client = new MongoClient(config.mongo.url);
}
async getCollection({ collectionName }): Promise<Collection> {
if (process.env.SERVER_ENV === 'local') {
const uri = await getMongoMemoryUri()
this.client = new MongoClient(uri);
}
await this.client.connect()
return this.client.db(config.mongo.dbName).collection(collectionName)
}

View File

@ -1,10 +0,0 @@
{
"name": "sceurity",
"version": "1.0.0",
"description": "",
"main": "index.js",
"dependencies": {
"mongodb": "^5.7.0"
},
"devDependencies": {}
}

View File

@ -1,5 +1,6 @@
import { Collection, MongoClient, ObjectId } from 'mongodb'
import { getConfig } from '../config/index'
import { getMongoMemoryUri } from '../../../getMongoMemoryUri'
const config = getConfig()
@ -9,7 +10,12 @@ class mongoService {
constructor() {
this.client = new MongoClient(config.mongo.url);
}
async getCollection({ collectionName }): Promise<Collection> {
if (process.env.SERVER_ENV === 'local') {
const uri = await getMongoMemoryUri()
this.client = new MongoClient(uri);
}
await this.client.connect()
return this.client.db(config.mongo.dbName).collection(collectionName)
}

View File

@ -1,13 +0,0 @@
{
"name": "survey_manage",
"version": "1.0.0",
"description": "",
"main": "index.js",
"dependencies": {
"joi": "^17.9.2",
"lodash": "^4.17.21",
"moment": "^2.29.4",
"mongodb": "^5.7.0"
},
"devDependencies": {}
}

View File

@ -1,5 +1,6 @@
import { Collection, MongoClient, ObjectId } from 'mongodb'
import { getConfig } from '../config/index'
import { getMongoMemoryUri } from '../../../getMongoMemoryUri'
const config = getConfig()
@ -9,7 +10,12 @@ class mongoService {
constructor() {
this.client = new MongoClient(config.mongo.url);
}
async getCollection({collectionName}):Promise<Collection> {
async getCollection({ collectionName }): Promise<Collection> {
if (process.env.SERVER_ENV === 'local') {
const uri = await getMongoMemoryUri()
this.client = new MongoClient(uri);
}
await this.client.connect()
return this.client.db(config.mongo.dbName).collection(collectionName)
}

View File

@ -1,13 +0,0 @@
{
"name": "survey_publish",
"version": "1.0.0",
"description": "",
"main": "index.js",
"dependencies": {
"joi": "^17.9.2",
"lodash": "^4.17.21",
"moment": "^2.29.4",
"mongodb": "^5.7.0"
},
"devDependencies": {}
}

View File

@ -1,7 +0,0 @@
{
"name": "ui",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"dependencies": {}
}

View File

@ -1,31 +1,37 @@
import { Collection, MongoClient, ObjectId } from 'mongodb'
import { getConfig } from '../config/index'
import { getMongoMemoryUri } from '../../../getMongoMemoryUri'
const config = getConfig()
class mongoService {
isInit:boolean
client:MongoClient
isInit: boolean
client: MongoClient
constructor() {
this.client = new MongoClient(config.mongo.url);
}
async getCollection({collectionName}):Promise<Collection> {
async getCollection({ collectionName }): Promise<Collection> {
if (process.env.SERVER_ENV === 'local') {
const uri = await getMongoMemoryUri()
this.client = new MongoClient(uri);
}
await this.client.connect()
return this.client.db(config.mongo.dbName).collection(collectionName)
}
convertId2StringByDoc(doc:any):any {
convertId2StringByDoc(doc: any): any {
doc._id = doc._id.toString()
return doc;
}
convertId2StringByList(list:Array<any>):Array<any> {
return list.map(e=>{
convertId2StringByList(list: Array<any>): Array<any> {
return list.map(e => {
return this.convertId2StringByDoc(e);
})
}
getObjectIdByStr(str:string) {
getObjectIdByStr(str: string) {
return new ObjectId(str)
}
}

View File

@ -1,13 +0,0 @@
{
"name": "user",
"version": "1.0.0",
"description": "",
"main": "index.js",
"dependencies": {
"joi": "^17.9.2",
"jsonwebtoken": "^9.0.1",
"lodash": "^4.17.21",
"mongodb": "^5.7.0"
},
"devDependencies": {}
}

View File

@ -1,9 +1,9 @@
import {
verify as jwtVerify,
sign as jwtSign
import {
verify as jwtVerify,
sign as jwtSign
} from 'jsonwebtoken';
import {
createHash
import {
createHash
} from 'crypto';
import { mongo } from '../db/mongo'
import { getStatusObject } from '../utils/index'
@ -23,55 +23,55 @@ class UserService {
return jwtSign(userInfo, config.jwt.secret, { expiresIn: config.jwt.expiresIn });
}
async register(userInfo:{username:string, password:string}) {
const user = await mongo.getCollection({collectionName:'user'});
async register(userInfo: { username: string, password: string }) {
const user = await mongo.getCollection({ collectionName: 'user' });
const userRes = await user.findOne({
username:userInfo.username,
username: userInfo.username,
})
if(userRes) {
if (userRes) {
throw new CommonError('该用户已存在')
}
const userInsertRes = await user.insertOne({
username:userInfo.username,
password:this.hash256(userInfo.password),
curStatus:getStatusObject({status:SURVEY_STATUS.new}),
createDate:Date.now()
username: userInfo.username,
password: this.hash256(userInfo.password),
curStatus: getStatusObject({ status: SURVEY_STATUS.new }),
createDate: Date.now()
})
const token = this.getToken({
const token = this.getToken({
_id: userInsertRes.insertedId.toString(),
username:userInfo.username
});
return {userInsertRes, token, username:userInfo.username}
username: userInfo.username
});
return { userInsertRes, token, username: userInfo.username }
}
async login(userInfo:{username:string, password:string}) {
const user = await mongo.getCollection({collectionName:'user'});
async login(userInfo: { username: string, password: string }) {
const user = await mongo.getCollection({ collectionName: 'user' });
const userRes = await user.findOne({
username:userInfo.username,
password:this.hash256(userInfo.password),
username: userInfo.username,
password: this.hash256(userInfo.password),
})
if(!userRes) {
if (!userRes) {
throw new CommonError('用户名或密码错误')
}
const token = this.getToken({
const token = this.getToken({
_id: userRes._id.toString(),
username:userInfo.username
});
return {token, username:userInfo.username}
username: userInfo.username
});
return { token, username: userInfo.username }
}
async getUserByToken(tokenInfo:{token:string}) {
async getUserByToken(tokenInfo: { token: string }) {
let userInfo;
try {
userInfo = jwtVerify(tokenInfo.token, config.jwt.secret)
} catch(err) {
throw new CommonError('用户凭证无效或已过期',403)
} catch (err) {
throw new CommonError('用户凭证无效或已过期', 403)
}
const user = await mongo.getCollection({collectionName:'user'});
const user = await mongo.getCollection({ collectionName: 'user' });
const userRes = await user.findOne({
_id:mongo.getObjectIdByStr(userInfo._id),
_id: mongo.getObjectIdByStr(userInfo._id),
})
if(!userRes) {
if (!userRes) {
throw new CommonError('用户已不存在')
}
return mongo.convertId2StringByDoc(userRes);

View File

@ -0,0 +1,10 @@
import { MongoMemoryServer } from 'mongodb-memory-server'
let mongoMemeryInstance
export async function getMongoMemoryUri () {
if (!mongoMemeryInstance) {
mongoMemeryInstance = await MongoMemoryServer.create()
}
return mongoMemeryInstance.getUri()
}

View File

@ -16,6 +16,6 @@ app.use(KoaBodyparser({
}))
app.use(getRouter().routes())
const port = 8080
const port = process.env.PORT || 3000
app.listen(port)
process.stdout.write(`${os.EOL}server run: http://127.0.0.1:${port} ${os.EOL}`)

View File

@ -1,10 +1,10 @@
export function outputCatch({showErrorStack}:{showErrorStack:boolean}) {
return async function (ctx, next) {
try{
export function outputCatch({ showErrorStack }: { showErrorStack: boolean }) {
return async function (ctx, next) {
try {
await next()
} catch(err) {
const outputData = {...err}
if(showErrorStack) {
} catch (err) {
const outputData = { ...err }
if (showErrorStack) {
outputData.stack = err.stack;
}
return ctx.body = outputData

View File

@ -21,7 +21,6 @@
"moment": "^2.29.4",
"qrcode": "^1.5.3",
"vue": "^2.7.14",
"vue-demi": "^0.14.5",
"vue-router": "^3.5.1",
"vuedraggable": "^2.24.3",
"vuex": "^3.6.2",
@ -50,7 +49,7 @@
"vue-template-compiler": "^2.7.14"
},
"engines": {
"node": ">=16.11.1",
"npm": ">=8.0.0"
"node": ">=14.21.0",
"npm": ">=6.14.17"
}
}

View File

@ -2,26 +2,33 @@ import axios from 'axios';
import store from '@/management/store/index';
import router from '@/management/router/index';
import _get from 'lodash/get';
import { Message } from 'element-ui';
const instance = axios.create({
baseURL: '/api',
timeout: 3000,
});
instance.interceptors.response.use((response) => {
if (response.status !== 200) {
throw new Error('http请求出错');
instance.interceptors.response.use(
(response) => {
if (response.status !== 200) {
throw new Error('http请求出错');
}
const res = response.data;
if (res.code === 403) {
router.replace({
name: 'login',
});
return res;
} else {
return res;
}
},
(err) => {
Message.error(err || 'http请求出错');
throw new Error(err);
}
const res = response.data;
if (res.code === 403) {
router.replace({
name: 'login',
});
return res;
} else {
return res;
}
});
);
instance.interceptors.request.use((config) => {
const hasLogined = _get(store, 'state.user.hasLogined');

View File

@ -3,7 +3,7 @@
class="login-page"
:style="{
background: `url('/imgs/create/background.jpg') no-repeat bottom right`,
'background-size': 'cover'
'background-size': 'cover',
}"
>
<div class="login-top">
@ -29,13 +29,18 @@
<el-form-item class="button-group">
<el-button
:loading="loginPending"
size="small"
type="primary"
class="button"
@click="submitForm('ruleForm', 'login')"
>登录</el-button
>
<el-button size="small" class="button register-button" @click="submitForm('ruleForm', 'register')"
<el-button
:loading="registerPending"
size="small"
class="button register-button"
@click="submitForm('ruleForm', 'register')"
>注册</el-button
>
</el-form-item>
@ -74,6 +79,8 @@ export default {
},
],
},
loginPending: false,
registerPending: false,
};
},
methods: {
@ -85,10 +92,12 @@ export default {
login,
register,
};
this[`${type}Pending`] = true;
const res = await submitTypes[type]({
username: this.ruleForm.name,
password: this.ruleForm.password,
});
this[`${type}Pending`] = false;
if (res.code !== CODE_MAP.SUCCESS) {
this.$message.error(res.errmsg);
throw new Error('登录/注册失败' + res.errmsg);
@ -105,6 +114,7 @@ export default {
}
this.$router.replace(redirect);
} catch (error) {
this[`${type}Pending`] = false;
console.log(error);
}
return true;
@ -145,7 +155,7 @@ export default {
width: 500px;
height: 300px;
background: #fff;
box-shadow: 4px 0 20px 0 rgba(82, 82, 102, 0.15);
box-shadow: 4px 0 20px 0 rgba(82, 82, 102, 0.15);
margin-top: -150px;
.button-group {
margin-top: 40px;

View File

@ -27,10 +27,21 @@ module.exports = defineConfig({
devServer: {
proxy: {
'/api': {
target: 'http://localhost:8080',
target: 'http://localhost:3000',
changeOrigin: true,
pathRewrite: false,
},
},
setupMiddlewares(middlewares, devServer) {
if (!devServer) {
throw new Error('webpack-dev-server is not defined');
}
devServer.app.get('/', function (req, res) {
res.redirect('/management');
});
return middlewares;
},
open: true,
},
chainWebpack: (config) => {
config.module

File diff suppressed because it is too large Load Diff