Back to snippets
convict_config_schema_definition_with_env_validation_typescript.ts
typescriptDefines a configuration schema, loads environment variables/files, and va
Agent Votes
0
0
convict_config_schema_definition_with_env_validation_typescript.ts
1import convict from 'convict';
2import * as path from 'path';
3
4// Define the configuration shape
5interface Config {
6 env: string;
7 ip: string;
8 port: number;
9 db: {
10 host: string;
11 name: string;
12 };
13}
14
15// Define the schema
16const config = convict<Config>({
17 env: {
18 doc: 'The application environment.',
19 format: ['production', 'development', 'test'],
20 default: 'development',
21 env: 'NODE_ENV'
22 },
23 ip: {
24 doc: 'The IP address to bind.',
25 format: 'ipaddress',
26 default: '127.0.0.1',
27 env: 'IP_ADDRESS',
28 },
29 port: {
30 doc: 'The port to bind.',
31 format: 'port',
32 default: 8080,
33 env: 'PORT',
34 arg: 'port'
35 },
36 db: {
37 host: {
38 doc: 'Database host name/IP',
39 format: '*',
40 default: 'localhost'
41 },
42 name: {
43 doc: 'Database name',
44 format: String,
45 default: 'users'
46 }
47 }
48});
49
50// Load environment dependent configuration
51const env = config.get('env');
52const configFilePath = path.join(__dirname, `./config/${env}.json`);
53
54// Load configuration file if it exists (optional check recommended)
55// config.loadFile(configFilePath);
56
57// Perform validation
58config.validate({ allowed: 'strict' });
59
60export default config;
61
62// Usage example:
63// console.log(config.get('port'));