From d5c8f3ff52605fd76b059e780857a03d0fd6f235 Mon Sep 17 00:00:00 2001 From: iVamp Date: Tue, 24 Oct 2023 13:25:21 +0800 Subject: [PATCH] add config --- .env.example | 6 ++++++ main.ts | 15 ++++++++++++++- package.json | 2 +- src/{ => config}/data-source.ts | 2 +- src/{ => config}/index.ts | 2 +- 5 files changed, 23 insertions(+), 4 deletions(-) create mode 100644 .env.example rename src/{ => config}/data-source.ts (90%) rename src/{ => config}/index.ts (94%) diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..1402762 --- /dev/null +++ b/.env.example @@ -0,0 +1,6 @@ +DB_CONNECTION=mysql +DB_HOST=127.0.0.1 +DB_PORT=3306 +DB_DATABASE=auth +DB_USERNAME=root +DB_PASSWORD= \ No newline at end of file diff --git a/main.ts b/main.ts index 2f2d5a2..d430d7a 100644 --- a/main.ts +++ b/main.ts @@ -1,8 +1,21 @@ import express from 'express'; import logger from 'morgan' -// import path from 'path' +import path from 'path' const app = express(); +import fs from 'fs' +import dotenv from 'dotenv' +// 检测运行目录下是否有 .env 文件,如果没有,则创建 +const envPath = path.resolve(__dirname, '.env') +if (!fs.existsSync(envPath)) { + fs.writeFileSync(envPath, '') + // log + console.log('create .env file') +} + +// 加载 .env 文件 +dotenv.config() +console.log(process.env) import indexRouter from './src/routes/index' import usersRouter from './src/routes/users' diff --git a/package.json b/package.json index 687bbe4..07470a5 100644 --- a/package.json +++ b/package.json @@ -19,7 +19,7 @@ "typescript": "4.5.2" }, "scripts": { - "start": "ts-node src/index.ts", + "start": "ts-node src/config/index.ts", "typeorm": "typeorm-ts-node-commonjs" } } \ No newline at end of file diff --git a/src/data-source.ts b/src/config/data-source.ts similarity index 90% rename from src/data-source.ts rename to src/config/data-source.ts index 506fb2d..6cc19ba 100644 --- a/src/data-source.ts +++ b/src/config/data-source.ts @@ -1,6 +1,6 @@ import "reflect-metadata" import { DataSource } from "typeorm" -import { User } from "./entity/User" +import { User } from "../entity/User" export const AppDataSource = new DataSource({ type: "mysql", diff --git a/src/index.ts b/src/config/index.ts similarity index 94% rename from src/index.ts rename to src/config/index.ts index 9ffd728..52fbd22 100644 --- a/src/index.ts +++ b/src/config/index.ts @@ -1,5 +1,5 @@ import { AppDataSource } from "./data-source" -import { User } from "./entity/User" +import { User } from "../entity/User" AppDataSource.initialize().then(async () => {