diff --git a/app.js b/app.js index 7f21d05..2aaefbb 100644 --- a/app.js +++ b/app.js @@ -12,41 +12,7 @@ const pug = require('pug'); const compression = require('compression'); const express = require('express'); const cookieParser = require('cookie-parser'); -const r = require('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 { redis } = require('./inc/redis'); const nodeFetch = require('node-fetch'); 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'); cacheControl.removeCacheFiles(); diff --git a/inc/redis.js b/inc/redis.js new file mode 100644 index 0000000..0918d9d --- /dev/null +++ b/inc/redis.js @@ -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, +};