Skip to content

Commit

Permalink
feat: add loadIfUnloaded method to Config class
Browse files Browse the repository at this point in the history
  • Loading branch information
jlenon7 committed Dec 6, 2021
1 parent dcc2d07 commit 0aff88b
Show file tree
Hide file tree
Showing 4 changed files with 16 additions and 12 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@secjs/config",
"version": "1.1.1",
"version": "1.1.2",
"description": "",
"license": "MIT",
"author": "João Lenon",
Expand Down
14 changes: 4 additions & 10 deletions src/Config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,10 @@ export class Config {
return config
}

loadIfUnloaded(configPath = '/config') {
if (!Config.configs.size) this.loadSync(configPath)
}

loadSync(configPath = '/config') {
Config.loadEnvs()

Expand All @@ -47,8 +51,6 @@ export class Config {
const { files } = new Folder(path).loadSync({ withFileContent: true })

files.forEach(file => Config.loadOnDemand(file.path, files, 0))

return this
}

async load(configPath = '/config') {
Expand All @@ -59,14 +61,6 @@ export class Config {
const { files } = await new Folder(path).load({ withFileContent: true })

files.forEach(file => Config.loadOnDemand(file.path, files, 0))

return this
}

static verifyPath(folderName = 'dist') {
if (process.env.NODE_ENV === 'testing') return '/config'

return `/${folderName}/config`
}

private static loadEnvs() {
Expand Down
3 changes: 2 additions & 1 deletion src/utils/global.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ export {}

declare global {
class Config {
loadIfUnloaded(configPath?: string): void
loadSync(configPath?: string): void
load(configPath?: string): Promise<void>
static verifyPath(folderName?: string): string
Expand All @@ -16,6 +17,6 @@ const _global = global as any

Path.switchEnvVerify()

new ConfigInstance().loadSync()
new ConfigInstance().loadIfUnloaded()

_global.Config = ConfigInstance
9 changes: 9 additions & 0 deletions tests/config.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,4 +80,13 @@ describe('\n Config', () => {
expect(Config.get('DB_NAME')).toBe('testing')
expect(Config.get('database.dbName')).toBe('testing')
})

it('should be able to use loadIfUnloaded method to load configs if they are not loaded', async () => {
expect(Config.get('app')).toBe(undefined)

new Config().loadIfUnloaded()

expect(Config.get('DB_NAME')).toBe('testing')
expect(Config.get('database.dbName')).toBe('testing')
})
})

0 comments on commit 0aff88b

Please sign in to comment.