Cache config.yaml reads

This commit is contained in:
Cohee 2024-04-27 21:59:57 +03:00
parent 3b153a6c9b
commit 01ccc32274
2 changed files with 17 additions and 3 deletions

View File

@ -10,6 +10,10 @@ const { getAllUserHandles, getUserDirectories } = require('../users');
const { getConfigValue } = require('../util');
const { jsonParser } = require('../express-common');
const thumbnailsDisabled = getConfigValue('disableThumbnails', false);
const quality = getConfigValue('thumbnailsQuality', 95);
const pngFormat = getConfigValue('avatarThumbnailsPng', false);
/**
* Gets a path to thumbnail folder based on the type.
* @param {import('../users').UserDirectoryList} directories User directories
@ -115,9 +119,8 @@ async function generateThumbnail(directories, type, file) {
let buffer;
try {
const quality = getConfigValue('thumbnailsQuality', 95);
const image = await jimp.read(pathToOriginalFile);
const imgType = type == 'avatar' && getConfigValue('avatarThumbnailsPng', false) ? 'image/png' : 'image/jpeg';
const imgType = type == 'avatar' && pngFormat ? 'image/png' : 'image/jpeg';
buffer = await image.cover(mySize[0], mySize[1]).quality(quality).getBufferAsync(imgType);
}
catch (inner) {
@ -188,7 +191,6 @@ router.get('/', jsonParser, async function (request, response) {
return response.sendStatus(403);
}
const thumbnailsDisabled = getConfigValue('disableThumbnails', false);
if (thumbnailsDisabled) {
const folder = getOriginalFolder(request.user.directories, type);

View File

@ -10,11 +10,20 @@ const { Readable } = require('stream');
const { PUBLIC_DIRECTORIES } = require('./constants');
/**
* Parsed config object.
*/
let CACHED_CONFIG = null;
/**
* Returns the config object from the config.yaml file.
* @returns {object} Config object
*/
function getConfig() {
if (CACHED_CONFIG) {
return CACHED_CONFIG;
}
if (!fs.existsSync('./config.yaml')) {
console.error(color.red('No config file found. Please create a config.yaml file. The default config file can be found in the /default folder.'));
console.error(color.red('The program will now exit.'));
@ -23,6 +32,7 @@ function getConfig() {
try {
const config = yaml.parse(fs.readFileSync(path.join(process.cwd(), './config.yaml'), 'utf8'));
CACHED_CONFIG = config;
return config;
} catch (error) {
console.warn('Failed to read config.yaml');
@ -47,6 +57,8 @@ function getConfigValue(key, defaultValue = null) {
* @param {any} value Value to set
*/
function setConfigValue(key, value) {
// Reset cache so that the next getConfig call will read the updated config file
CACHED_CONFIG = null;
const config = getConfig();
_.set(config, key, value);
fs.writeFileSync('./config.yaml', yaml.stringify(config));