Skip to content

Commit

Permalink
✨ feat(config.ts): add caching mechanism to reduce file I/O operations
Browse files Browse the repository at this point in the history
A caching mechanism has been added to the getConfig function to improve performance by reducing the number of file I/O operations. The function now checks if the configCache variable is enabled and returns the cached value if it is. If the cache is not enabled, the function reads the configuration file and returns the value. After reading the configuration file, the function stores the value in the cache for future use.
  • Loading branch information
takuya-o committed May 29, 2023
1 parent 32f3e17 commit 9062c5d
Showing 1 changed file with 10 additions and 1 deletion.
11 changes: 10 additions & 1 deletion src/commands/config.ts
Original file line number Diff line number Diff line change
@@ -11,6 +11,7 @@ import { getI18nLocal } from '../i18n';
import * as dotenv from 'dotenv';

dotenv.config();
let configCache:ConfigType | null = null;

export enum CONFIG_KEYS {
OCO_OPENAI_API_KEY = 'OCO_OPENAI_API_KEY',
@@ -134,6 +135,9 @@ export type ConfigType = {
const configPath = pathJoin(homedir(), '.opencommit');

export const getConfig = (): ConfigType | null => {
// If it is enable, use configCache
if (configCache) return configCache;

const configFromEnv = {
OCO_OPENAI_API_KEY: process.env.OCO_OPENAI_API_KEY,
OCO_OPENAI_MAX_TOKENS: process.env.OCO_OPENAI_MAX_TOKENS ? Number(process.env.OCO_OPENAI_MAX_TOKENS) : undefined,
@@ -145,7 +149,10 @@ export const getConfig = (): ConfigType | null => {
};

const configExists = existsSync(configPath);
if (!configExists) return configFromEnv;
if (!configExists) {
configCache = configFromEnv;
return configFromEnv;
}

const configFile = readFileSync(configPath, 'utf8');
const config = iniParse(configFile);
@@ -173,6 +180,8 @@ export const getConfig = (): ConfigType | null => {
}
}

// Store configCache
configCache = config
return config;
};

0 comments on commit 9062c5d

Please sign in to comment.