separate redis from app.js

This commit is contained in:
json 2021-09-08 09:27:56 +01:00
parent 5f5388da6f
commit 1c7a3a8f5a
2 changed files with 52 additions and 41 deletions

42
app.js
View File

@ -12,41 +12,7 @@ const pug = require('pug');
const compression = require('compression'); const compression = require('compression');
const express = require('express'); const express = require('express');
const cookieParser = require('cookie-parser'); const cookieParser = require('cookie-parser');
const r = require('redis'); const { redis } = require('./inc/redis');
const redis = (() => {
if (!config.redis_enabled) {
// Stub Redis if disabled
return {
get: (_, callback) => callback(null, null),
setex: (_, _1, _2, callback) => callback(null),
on: () => {},
};
}
const redisOptions = {
host: '127.0.0.1',
port: 6379,
};
if (config.redis_db) {
redisOptions.db = config.redis_db;
}
if (config.redis_host) {
redisOptions.host = config.redis_host;
}
if (config.redis_port && config.redis_port > 0) {
redisOptions.port = config.redis_port;
}
if (config.redis_password) {
redisOptions.password = config.redis_password;
}
return r.createClient(redisOptions);
})();
const nodeFetch = require('node-fetch'); const nodeFetch = require('node-fetch');
const fetch = config.http_proxy const fetch = config.http_proxy
@ -162,12 +128,6 @@ if (config.redirect_http_to_https) {
}); });
} }
redis.on('error', (error) => {
if (error) {
console.error(`Redis error: ${error}`);
}
});
const cacheControl = require('./cacheControl.js'); const cacheControl = require('./cacheControl.js');
cacheControl.removeCacheFiles(); cacheControl.removeCacheFiles();

51
inc/redis.js Normal file
View File

@ -0,0 +1,51 @@
const config = require('../config');
const { promisify } = require('util');
const r = require('redis');
const redisOptions = {
host: '127.0.0.1',
port: 6379,
};
if (config.redis_db) {
redisOptions.db = config.redis_db;
}
if (config.redis_host) {
redisOptions.host = config.redis_host;
}
if (config.redis_port && config.redis_port > 0) {
redisOptions.port = config.redis_port;
}
if (config.redis_password) {
redisOptions.password = config.redis_password;
}
// Stub Redis if disabled
const stub = {
get: (_, callback) => callback(null, null),
setex: (_, _1, _2, callback) => callback(null),
on: () => {},
};
const redisDisabled = !config.redis_enabled;
const redis = redisDisabled ? stub : r.createClient(redisOptions);
const redisAsync = {
get: promisify(redis.get).bind(redis),
setex: promisify(redis.setex).bind(redis),
};
redis.on('error', (error) => {
if (error) {
console.error(`Redis error: ${error}`);
}
});
module.exports = {
redis,
redisAsync,
};