Skip to content

Instantly share code, notes, and snippets.

@Siedrix
Created May 13, 2016 15:45
Show Gist options
  • Save Siedrix/a46a1f37238139adbe07fc04e9468f5b to your computer and use it in GitHub Desktop.
Save Siedrix/a46a1f37238139adbe07fc04e9468f5b to your computer and use it in GitHub Desktop.
Koa cache server
const koa = require('koa')
const Router = require('koa-router')
const request = require('request-promise')
const app = koa()
const router = new Router()
router.get('/', function *(next) {
var body = yield request({
uri: 'https://www.reddit.com/.json',
json: true
})
this.body = body
})
router.get('/r/:subreddit', function *(next) {
var body = yield request({
uri: 'https://www.reddit.com/r/'+this.params.subreddit+'.json',
json: true
})
this.body = body
})
app.use(router.routes())
app.listen(3000)
{
"name": "koa-cache",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"bluebird": "^3.3.5",
"koa": "^1.2.0",
"koa-router": "^5.4.0",
"redis": "^2.6.0-2",
"request-promise": "^3.0.0"
}
}
const koa = require('koa')
const Router = require('koa-router')
const request = require('request-promise')
const redis = require("redis")
const Bluebird = require('bluebird')
Bluebird.promisifyAll(redis.RedisClient.prototype);
Bluebird.promisifyAll(redis.Multi.prototype);
const app = koa()
const client = redis.createClient()
const router = new Router()
const timeToLive = 60
const cacheMiddleware = function *(next){
var cacheBody = yield client.getAsync(this.request.path)
if(cacheBody){
console.log('Using cache body', this.request.path)
return this.body = JSON.parse(cacheBody)
}else{
console.log('Requesting to reddit', this.request.path)
}
yield next
client.setexAsync(this.request.path, timeToLive, JSON.stringify(this.body) )
}
router.get('/', cacheMiddleware, function *(next) {
var body = yield request({
uri: 'https://www.reddit.com/.json',
json: true
})
this.body = body
})
router.get('/r/:subreddit', cacheMiddleware, function *(next) {
var body = yield request({
uri: 'https://www.reddit.com/r/'+this.params.subreddit+'.json',
json: true
})
this.body = body
})
app.use(router.routes())
app.listen(3000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment