icynet-auth-server/src/modules/config/config.providers.ts

81 lines
2.2 KiB
TypeScript
Raw Normal View History

import * as toml from 'toml';
import { resolve } from 'path';
import { readFile } from 'fs/promises';
import { Configuration } from './config.interfaces';
2023-01-11 16:23:08 +00:00
import { FactoryProvider, Logger, ValueProvider } from '@nestjs/common';
const CONFIG_ENV = process.env.NODE_ENV === 'production' ? 'prod' : 'dev';
const CONFIG_FILENAME = process.env.CONFIG || `config.${CONFIG_ENV}.toml`;
2022-09-18 07:22:57 +00:00
export const configProviders = [
{
provide: 'CONFIG_PATH',
useValue: resolve(__dirname, '..', '..', '..', CONFIG_FILENAME),
2022-09-18 07:22:57 +00:00
} as ValueProvider<string>,
{
provide: 'DEFAULT_CONFIG',
useValue: {
app: {
base_url: 'http://localhost:3000',
host: '0.0.0.0',
port: 3000,
session_name: '__sid',
2022-08-18 07:12:02 +00:00
// generate the following with crypto.randomBytes(256 / 8).toString('hex')
session_secret: 'change me!',
challenge_secret: 'change me!',
2022-08-22 17:39:31 +00:00
registrations: false,
},
email: {
from: 'no-reply@localhost',
smtp: {
host: 'localhost',
port: 587,
secure: false,
auth: {
user: 'root',
pass: 'root',
},
},
},
jwt: {
algorithm: 'RS256',
2022-09-16 15:11:36 +00:00
issuer: 'http://localhost',
expiration: 604800,
},
2022-08-18 07:12:02 +00:00
database: {
type: 'mysql',
host: 'localhost',
port: 3306,
username: 'root',
password: 'root',
database: 'icyauth',
entities: ['dist/**/*.entity.js'],
2022-08-18 07:12:02 +00:00
synchronize: true,
migrations: ['dist/migration/*.js'],
2022-08-18 07:12:02 +00:00
cli: {
migrationsDir: 'src/migration',
2022-08-18 07:12:02 +00:00
},
},
} as Configuration,
2022-09-18 07:22:57 +00:00
} as ValueProvider<Configuration>,
{
provide: 'CONFIGURATION',
useFactory: async (
2022-08-18 07:12:02 +00:00
configPath: string,
defaultConfig: Configuration,
): Promise<Configuration> => {
try {
2022-08-18 07:12:02 +00:00
const file = await readFile(configPath, { encoding: 'utf-8' });
return {
2022-08-18 07:12:02 +00:00
...defaultConfig,
2022-08-17 18:56:47 +00:00
...JSON.parse(JSON.stringify(toml.parse(file))),
};
2022-09-18 07:22:57 +00:00
} catch (e: unknown) {
2023-01-11 16:23:08 +00:00
Logger.error('Failed to load configuration:', (e as Error).message);
2022-08-18 07:12:02 +00:00
return defaultConfig;
}
},
inject: ['CONFIG_PATH', 'DEFAULT_CONFIG'],
2022-09-18 07:22:57 +00:00
} as FactoryProvider<Configuration>,
];