Skip to content

Commit

Permalink
Add caching addressing #1
Browse files Browse the repository at this point in the history
  • Loading branch information
addi00000 committed Jan 18, 2023
1 parent 94b4138 commit c993aab
Showing 1 changed file with 11 additions and 0 deletions.
11 changes: 11 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
const express = require('express')
const request = require('request')
const imageType = require('image-type')
const LRU = require("lru-cache")

const app = express()
const port = process.env.PORT || 3000
const cache = new LRU({ max: 500, maxAge: 1000 * 60 * 60 })

app.get('/', (req, res) => {
res.send('Hello World!')
Expand All @@ -20,6 +22,13 @@ app.get('/image', (req, res) => {
return res.status(400).send('Invalid url')
}

const cachedImage = cache.get(url)
if (cachedImage) {
res.set('Content-Type', cachedImage.type)
res.send(cachedImage.data)
return
}

request.get({ url, encoding: null }, (error, response, body) => {
if (error) {
if (error.code === 'ENOTFOUND') {
Expand All @@ -41,6 +50,8 @@ app.get('/image', (req, res) => {

res.set('Content-Type', type.mime)
res.send(body)

cache.set(url, { data: body, type: type.mime })
})
})
})
Expand Down

0 comments on commit c993aab

Please sign in to comment.