Skip to content

Commit 631b92e

Browse files
feat: change env loader
1 parent c66bce8 commit 631b92e

15 files changed

Lines changed: 198 additions & 144 deletions

.env.default

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1+
# FIXME: deprecated, suggest use config.json only
12

23
REDIS_HOST=
3-
# parseInt(process.env.REDIS_PORT, 10)
44
REDIS_PORT=
55
REDIS_PWD=
66
REDIS_DB=
@@ -15,8 +15,6 @@ AWS_REGION=
1515

1616
COOKIE_SIGN_KEY=
1717

18-
REDIS_HOST=
19-
2018
LOKALISE_TOKEN=
2119
LOKALISE_PROJECT_ID=
2220

.eslintrc.js

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
const isDev = process.env.NODE_ENV !== 'production';
21
const jsRules = {
32
// eslint-disable-next-line global-require
43
'prettier/prettier': ['error', require('./.prettierrc.js')],
@@ -25,7 +24,7 @@ const tsRules = {
2524
'@typescript-eslint/default-param-last': 'off',
2625
'@typescript-eslint/consistent-type-imports': 'off',
2726
'@typescript-eslint/no-var-requires': 'off',
28-
'@typescript-eslint/no-unused-vars': [isDev ? 'warn' : 'error'],
27+
'@typescript-eslint/no-unused-vars': ['error'],
2928
'@typescript-eslint/no-use-before-define': ['error'],
3029
'@typescript-eslint/no-shadow': ['error'],
3130
'@typescript-eslint/explicit-module-boundary-types': 'off',

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ run/
1313
.tsbuildinfo
1414
.tsbuildinfo.*
1515
.env
16+
config.json
1617
junit.xml
1718
test-report.html
1819
jest-stare/

Dockerfile

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,6 @@ RUN yarn run prepare-env\
2828

2929
ENV TZ="Asia/Shanghai"
3030

31-
EXPOSE 7001
31+
EXPOSE 80
3232

3333
CMD ["yarn", "run", "start"]

config.default.json

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
{
2+
"COOKIE_SIGN_KEY": "0000000000000_000",
3+
"PORT": "80",
4+
"GLOBAL_PREFIX": "",
5+
"REDIS_HOST": "localhost",
6+
"REDIS_PORT": "6379",
7+
"REDIS_PWD": "",
8+
"REDIS_DB": "0",
9+
"MONGODB_URI": "mongodb://localhost:27017/test",
10+
"MONGODB_USER": "",
11+
"MONGODB_PASSWORD": "",
12+
"AWS_ACCESS_KEY_ID": "",
13+
"AWS_SECRET_KEY": "",
14+
"AWS_REGION": "",
15+
"LOKALISE_TOKEN": "",
16+
"LOKALISE_PROJECT_ID": ""
17+
}

src/config/config.default.ts

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,7 @@
22

33
import localeConfig from '../locales';
44

5-
const getRedisConfig = (db = 0, options: Record<string, unknown> = {}) => ({
6-
host: process.env.REDIS_HOST,
7-
port: parseInt(process.env.REDIS_PORT, 10),
8-
password: process.env.REDIS_PWD,
9-
db,
10-
...options,
11-
});
5+
import type { MidwayConfig } from '@midwayjs/core';
126

137
/*
148
default中的配置项,会被config.xxxx.ts中相同配置项覆盖
@@ -24,7 +18,12 @@ export default {
2418
enableConsole: false,
2519
},
2620
},
27-
redis: getRedisConfig(parseInt(process.env.REDIS_DB, 10)),
21+
redis: {
22+
host: process.env.REDIS_HOST,
23+
port: parseInt(process.env.REDIS_PORT, 10),
24+
password: process.env.REDIS_PWD,
25+
db: parseInt(process.env.REDIS_DB, 10),
26+
},
2827
mongoose: {
2928
dataSource: {
3029
default: {
@@ -52,4 +51,4 @@ export default {
5251
writeCookie: false,
5352
resolver: false,
5453
},
55-
};
54+
} as MidwayConfig;

src/config/config.jest.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
import { MidwayConfig } from '@midwayjs/core';
2+
3+
export default {} as MidwayConfig;

src/config/config.local.ts

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,12 @@
11
import { MidwayConfig } from '@midwayjs/core';
22

3-
export default {} as MidwayConfig;
3+
export default {
4+
midwayLogger: {
5+
default: {
6+
fileLevel: 'info',
7+
enableFile: false,
8+
consoleLevel: 'debug',
9+
enableConsole: true,
10+
},
11+
},
12+
} as MidwayConfig;

src/configuration.ts

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
import './init';
1+
// eslint-disable-next-line import/order
2+
import './init'; // XXX: must run before all code
23

34
import { hostname } from 'os';
45
import path, { join } from 'path';
@@ -23,10 +24,11 @@ import { sync } from 'read-pkg';
2324
import { DefaultErrorFilter } from './filter/default.filter';
2425
import { LocaleMiddleware } from './middleware/locale.middleware';
2526
import { ResponseWrapperMiddleware } from './middleware/response-wrapper.middleware';
26-
import { RUNTIME_ENV_MAP, ServerEnv } from './types/config/config.dto';
27-
import { validateBy } from './utils/common';
27+
import { NODE_ENV, ConfigDTO } from './types/config.dto';
28+
import { validateBy } from './utils';
2829
import { CloudwatchTransport } from './utils/logger';
2930
import { registerModel } from './utils/register-model';
31+
3032
@Configuration({
3133
imports: [
3234
koa,
@@ -64,7 +66,7 @@ export class MainConfiguration {
6466
async onConfigLoad() {
6567
const config = this.app.getConfig();
6668

67-
return validateBy(config, ServerEnv, {
69+
return validateBy(config, ConfigDTO, {
6870
allowUnknown: true,
6971
});
7072
}
@@ -73,7 +75,7 @@ export class MainConfiguration {
7375
this.app.useMiddleware([LocaleMiddleware, ResponseWrapperMiddleware]);
7476
this.app.useFilter([DefaultErrorFilter]);
7577

76-
if (this.envConfig === RUNTIME_ENV_MAP.PRODUCTION) {
78+
if (this.envConfig === NODE_ENV.PRODUCTION) {
7779
const cloudwatchTransport = new CloudwatchTransport({
7880
app: this.app.getProjectName(),
7981
hostname: hostname(),

src/init.ts

Lines changed: 44 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,50 @@
11
/* eslint-disable no-process-env */
2-
import { join, resolve } from 'path';
2+
3+
import path from 'path';
34

45
import * as dotenv from 'dotenv';
56

6-
export const ServerSecretsPath = resolve(
7-
'/',
8-
'mnt',
9-
'secrets',
10-
`onekey-eks-dashboard-${process.env.NODE_ENV}.json`
11-
);
12-
export const ServerConfigPath = resolve('/', 'mnt', 'config', 'config.json');
13-
14-
function loadJsonConfigFile(file: string, errorMessage: string) {
15-
try {
16-
dotenv.populate(process.env, require(file));
17-
} catch (error) {
18-
console.log(errorMessage, file);
19-
}
7+
import { NODE_ENV } from './types/config.dto';
8+
9+
// ============================================================================
10+
const PROJECT_NAME = ''; // FIXME: set by your project
11+
if (!PROJECT_NAME) {
12+
console.log('Please set your own PROJECT_NAME and delete this console');
13+
}
14+
15+
// first load config as default, second load config will not cover prev load config
16+
if (
17+
[NODE_ENV.LOCAL, NODE_ENV.JEST].includes(process.env.NODE_ENV as NODE_ENV)
18+
) {
19+
// local load config
20+
dotenv.populate(
21+
process.env,
22+
require(path.resolve(__dirname, '..', 'config.json'))
23+
);
24+
25+
// FIXME: deprecated, suggest use config.json only
26+
dotenv.config({
27+
path: path.join(__dirname, '..', '.env'),
28+
});
29+
} else {
30+
// online load config
31+
dotenv.populate(
32+
process.env,
33+
require(path.resolve('/', 'mnt', 'config', 'config.json'))
34+
);
35+
36+
dotenv.populate(
37+
process.env,
38+
require(path.resolve(
39+
'/',
40+
'mnt',
41+
'secrets',
42+
`onekey-eks-${PROJECT_NAME}-${process.env.NODE_ENV}.json`
43+
))
44+
);
2045
}
2146

22-
/*
23-
加载线上配置文件
24-
*/
25-
loadJsonConfigFile(ServerConfigPath, 'No config found path:');
26-
loadJsonConfigFile(ServerSecretsPath, 'No secrets found path:');
27-
loadJsonConfigFile(
28-
join(__dirname, '..', '.config.json'),
29-
'No local json config found'
30-
);
31-
32-
/*
33-
加载本地配置文件,注意.config.json和.env只需要一个即可,两个都存在的话,.config.json会覆盖.env
34-
*/
35-
dotenv.config({
36-
path: join(__dirname, '..', '.env'),
37-
});
47+
// ============================================================================
48+
BigInt.prototype['toJSON'] = function () {
49+
return this.toString();
50+
};

0 commit comments

Comments
 (0)