Created
May 23, 2020 00:55
-
-
Save doried-a-a/c50f674deb14dce1af549babbf7b4cbe to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const express = require('express'); | |
const urlJoin = require('url-join'); | |
const path = require('path'); | |
// you can uncomment those two lines, and create a .env file to store following configs in. | |
//const readConfig = require('@oufok/env-reader').readEnv; | |
//let configDir = path.join(__dirname, './config'); | |
const REDIS_HOST="localhost"; | |
const REDIS_IMAGE_SERVICE_HOST="http://localhost"; | |
const REDIS_IMAGE_SERVICE_PORT=8008; | |
const REDIS_PORT=6379; | |
const app = express(); | |
const redis = require('redis'); | |
const redisClient = redis.createClient(REDIS_PORT, REDIS_HOST); | |
const type = "image/jpeg"; | |
const PORT = REDIS_IMAGE_SERVICE_PORT; | |
app.get('/get/:imageId', (req, res) => { | |
let imageId = "" + req.params.imageId; | |
redisClient.get(imageId + "_content", (error, imgData) => { | |
if(error) res.status(500); | |
if (imgData === null) { | |
// Try to find if this image has a redirect ( this can be written by symfony-message-handler when moving the content of the img to permanent storage) | |
redisClient.get(imageId + "_redirect", (error, redirectPath) => { | |
if(error) res.status(500); | |
else{ | |
res.redirect(301, isAbsoluteUrl(redirectPath)? redirectPath : urlJoin(WEBSITE_ROOT_URL, redirectPath)); | |
console.log("Got redirect path " + redirectPath); | |
} | |
}); | |
} else { | |
try { | |
var buff = Buffer.from(imgData, 'base64'); | |
let imgContent = buff.toString('binary'); | |
res.set('Content-Type', type); | |
res.header('Cache-Control', 'max-age=2592000000'); | |
res.end(imgContent, 'binary'); | |
} catch (e) { | |
res.status(500); | |
res.send(); | |
} | |
} | |
}); | |
}); | |
app.listen(PORT, () => { | |
console.log('Redis image server is running on port ' + PORT); | |
}); | |
function isAbsoluteUrl(urlString) { | |
const pat = /^https?:\/\//i; | |
return pat.test(urlString); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment