feat: 优化生产环境依赖 (#15)

This commit is contained in:
luch 2023-12-04 11:02:39 +08:00 committed by GitHub
parent 851c89f593
commit 9567bbfe47
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 33 additions and 18 deletions

View File

@ -12,7 +12,7 @@
"start:preonline": "SERVER_ENV=preonline node ./build/index.js",
"start:online": "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",
"local": "ts-node scripts/run-local.ts",
"dev": "npm run copy && nodemon -e js,mjs,json,ts --exec 'npm run launch:dev' --watch ./src"
},
"devDependencies": {
@ -20,6 +20,7 @@
"@types/koa": "^2.13.8",
"@types/koa-bodyparser": "^4.3.10",
"@types/koa-router": "^7.4.4",
"mongodb-memory-server": "^9.0.1",
"nodemon": "^2.0.20",
"typescript": "^4.8.4"
},
@ -33,8 +34,7 @@
"koa-router": "^12.0.0",
"lodash": "^4.17.21",
"moment": "^2.29.4",
"mongodb": "^5.7.0",
"mongodb-memory-server": "^9.0.1"
"mongodb": "^5.7.0"
},
"engines": {
"node": ">=14.21.0",

View File

@ -0,0 +1,30 @@
import { MongoMemoryServer } from 'mongodb-memory-server';
import { exec } from 'child_process';
async function startServerAndRunScript() {
// 启动 MongoDB 内存服务器
const mongod = await MongoMemoryServer.create();
const mongoUri = mongod.getUri();
console.log('MongoDB Memory Server started:', mongoUri);
// 通过 nodemon 运行另一个脚本,并传递 MongoDB 连接 URL 作为环境变量
const nodemon = exec(`npm run copy && nodemon -e js,mjs,json,ts --exec 'xiaojuSurveyMongoUrl=${mongoUri} npm run launch:local' --watch ./src`);
nodemon.stdout?.on('data', (data) => {
console.log(data);
});
nodemon.stderr?.on('data', (data) => {
console.error(data);
});
nodemon.on('close', (code) => {
console.log(`Nodemon process exited with code ${code}`);
mongod.stop(); // 停止 MongoDB 内存服务器
});
}
startServerAndRunScript().catch((err) => {
console.error('Error starting server and script:', err);
});

View File

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

View File

@ -1,5 +1,4 @@
import { Collection, MongoClient, ObjectId } from 'mongodb'
import { getMongoMemoryUri } from './getMongoMemoryUri'
import { CommonError } from '../types'
@ -13,10 +12,6 @@ class MongoService {
}
async getCollection({ collectionName }): Promise<Collection> {
if (process.env.SERVER_ENV === 'local') {
const uri = await getMongoMemoryUri()
this.client = new MongoClient(uri);
}
try {
// 设置一个6秒的计时器
const timeoutPromise = new Promise((resolve, reject) => {