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 ```shell
cd server cd server
sh init.sh
``` ```
### 启动 ### 启动
```shell ```shell
npm run local // 无需安装mongo
npm run dev npm run dev
``` ```

View File

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

View File

@ -1,5 +1,6 @@
import { Collection, MongoClient, ObjectId } from 'mongodb' import { Collection, MongoClient, ObjectId } from 'mongodb'
import { getConfig } from '../config/index' import { getConfig } from '../config/index'
import { getMongoMemoryUri } from '../../../getMongoMemoryUri'
const config = getConfig() const config = getConfig()
@ -9,7 +10,12 @@ class mongoService {
constructor() { constructor() {
this.client = new MongoClient(config.mongo.url); 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() await this.client.connect()
return this.client.db(config.mongo.dbName).collection(collectionName) 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 { Collection, MongoClient, ObjectId } from 'mongodb'
import { getConfig } from '../config/index' import { getConfig } from '../config/index'
import { getMongoMemoryUri } from '../../../getMongoMemoryUri'
const config = getConfig() const config = getConfig()
@ -9,7 +10,12 @@ class mongoService {
constructor() { constructor() {
this.client = new MongoClient(config.mongo.url); 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() await this.client.connect()
return this.client.db(config.mongo.dbName).collection(collectionName) 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 { Collection, MongoClient, ObjectId } from 'mongodb'
import { getConfig } from '../config/index' import { getConfig } from '../config/index'
import { getMongoMemoryUri } from '../../../getMongoMemoryUri'
const config = getConfig() const config = getConfig()
@ -9,7 +10,12 @@ class mongoService {
constructor() { constructor() {
this.client = new MongoClient(config.mongo.url); 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() await this.client.connect()
return this.client.db(config.mongo.dbName).collection(collectionName) 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 { Collection, MongoClient, ObjectId } from 'mongodb'
import { getConfig } from '../config/index' import { getConfig } from '../config/index'
import { getMongoMemoryUri } from '../../../getMongoMemoryUri'
const config = getConfig() const config = getConfig()
class mongoService { class mongoService {
isInit:boolean isInit: boolean
client:MongoClient client: MongoClient
constructor() { constructor() {
this.client = new MongoClient(config.mongo.url); 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() await this.client.connect()
return this.client.db(config.mongo.dbName).collection(collectionName) return this.client.db(config.mongo.dbName).collection(collectionName)
} }
convertId2StringByDoc(doc:any):any { convertId2StringByDoc(doc: any): any {
doc._id = doc._id.toString() doc._id = doc._id.toString()
return doc; return doc;
} }
convertId2StringByList(list:Array<any>):Array<any> { convertId2StringByList(list: Array<any>): Array<any> {
return list.map(e=>{ return list.map(e => {
return this.convertId2StringByDoc(e); return this.convertId2StringByDoc(e);
}) })
} }
getObjectIdByStr(str:string) { getObjectIdByStr(str: string) {
return new ObjectId(str) 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 { import {
verify as jwtVerify, verify as jwtVerify,
sign as jwtSign sign as jwtSign
} from 'jsonwebtoken'; } from 'jsonwebtoken';
import { import {
createHash createHash
} from 'crypto'; } from 'crypto';
import { mongo } from '../db/mongo' import { mongo } from '../db/mongo'
import { getStatusObject } from '../utils/index' import { getStatusObject } from '../utils/index'
@ -23,55 +23,55 @@ class UserService {
return jwtSign(userInfo, config.jwt.secret, { expiresIn: config.jwt.expiresIn }); return jwtSign(userInfo, config.jwt.secret, { expiresIn: config.jwt.expiresIn });
} }
async register(userInfo:{username:string, password:string}) { async register(userInfo: { username: string, password: string }) {
const user = await mongo.getCollection({collectionName:'user'}); const user = await mongo.getCollection({ collectionName: 'user' });
const userRes = await user.findOne({ const userRes = await user.findOne({
username:userInfo.username, username: userInfo.username,
}) })
if(userRes) { if (userRes) {
throw new CommonError('该用户已存在') throw new CommonError('该用户已存在')
} }
const userInsertRes = await user.insertOne({ const userInsertRes = await user.insertOne({
username:userInfo.username, username: userInfo.username,
password:this.hash256(userInfo.password), password: this.hash256(userInfo.password),
curStatus:getStatusObject({status:SURVEY_STATUS.new}), curStatus: getStatusObject({ status: SURVEY_STATUS.new }),
createDate:Date.now() createDate: Date.now()
}) })
const token = this.getToken({ const token = this.getToken({
_id: userInsertRes.insertedId.toString(), _id: userInsertRes.insertedId.toString(),
username:userInfo.username username: userInfo.username
}); });
return {userInsertRes, token, username:userInfo.username} return { userInsertRes, token, username: userInfo.username }
} }
async login(userInfo:{username:string, password:string}) { async login(userInfo: { username: string, password: string }) {
const user = await mongo.getCollection({collectionName:'user'}); const user = await mongo.getCollection({ collectionName: 'user' });
const userRes = await user.findOne({ const userRes = await user.findOne({
username:userInfo.username, username: userInfo.username,
password:this.hash256(userInfo.password), password: this.hash256(userInfo.password),
}) })
if(!userRes) { if (!userRes) {
throw new CommonError('用户名或密码错误') throw new CommonError('用户名或密码错误')
} }
const token = this.getToken({ const token = this.getToken({
_id: userRes._id.toString(), _id: userRes._id.toString(),
username:userInfo.username username: userInfo.username
}); });
return {token, username:userInfo.username} return { token, username: userInfo.username }
} }
async getUserByToken(tokenInfo:{token:string}) { async getUserByToken(tokenInfo: { token: string }) {
let userInfo; let userInfo;
try { try {
userInfo = jwtVerify(tokenInfo.token, config.jwt.secret) userInfo = jwtVerify(tokenInfo.token, config.jwt.secret)
} catch(err) { } catch (err) {
throw new CommonError('用户凭证无效或已过期',403) throw new CommonError('用户凭证无效或已过期', 403)
} }
const user = await mongo.getCollection({collectionName:'user'}); const user = await mongo.getCollection({ collectionName: 'user' });
const userRes = await user.findOne({ const userRes = await user.findOne({
_id:mongo.getObjectIdByStr(userInfo._id), _id: mongo.getObjectIdByStr(userInfo._id),
}) })
if(!userRes) { if (!userRes) {
throw new CommonError('用户已不存在') throw new CommonError('用户已不存在')
} }
return mongo.convertId2StringByDoc(userRes); 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()) app.use(getRouter().routes())
const port = 8080 const port = process.env.PORT || 3000
app.listen(port) app.listen(port)
process.stdout.write(`${os.EOL}server run: http://127.0.0.1:${port} ${os.EOL}`) 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}) { export function outputCatch({ showErrorStack }: { showErrorStack: boolean }) {
return async function (ctx, next) { return async function (ctx, next) {
try{ try {
await next() await next()
} catch(err) { } catch (err) {
const outputData = {...err} const outputData = { ...err }
if(showErrorStack) { if (showErrorStack) {
outputData.stack = err.stack; outputData.stack = err.stack;
} }
return ctx.body = outputData return ctx.body = outputData

View File

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

View File

@ -2,26 +2,33 @@ import axios from 'axios';
import store from '@/management/store/index'; import store from '@/management/store/index';
import router from '@/management/router/index'; import router from '@/management/router/index';
import _get from 'lodash/get'; import _get from 'lodash/get';
import { Message } from 'element-ui';
const instance = axios.create({ const instance = axios.create({
baseURL: '/api', baseURL: '/api',
timeout: 3000, timeout: 3000,
}); });
instance.interceptors.response.use((response) => { instance.interceptors.response.use(
if (response.status !== 200) { (response) => {
throw new Error('http请求出错'); 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) => { instance.interceptors.request.use((config) => {
const hasLogined = _get(store, 'state.user.hasLogined'); const hasLogined = _get(store, 'state.user.hasLogined');

View File

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

View File

@ -27,10 +27,21 @@ module.exports = defineConfig({
devServer: { devServer: {
proxy: { proxy: {
'/api': { '/api': {
target: 'http://localhost:8080', target: 'http://localhost:3000',
changeOrigin: true, 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) => { chainWebpack: (config) => {
config.module config.module

File diff suppressed because it is too large Load Diff