Skip to content

Commit

Permalink
add: redis
Browse files Browse the repository at this point in the history
  • Loading branch information
wbruno committed Jan 16, 2021
1 parent 4ba615b commit cb406d0
Show file tree
Hide file tree
Showing 4 changed files with 28 additions and 5 deletions.
3 changes: 2 additions & 1 deletion capitulo_5/5.5.3/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
"debug": "4.3.1",
"dnscache": "^1.0.2",
"express": "^4.17.1",
"pg": "8.5.1"
"pg": "8.5.1",
"redis": "3.0.2"
}
}
9 changes: 9 additions & 0 deletions capitulo_5/5.5.3/server/config/redis.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { createClient } from 'redis';
import { promisify } from 'util';
const client = createClient({
host: 'localhost',
port: 6379
})
client.on('error', (e) => console.log(e))
export const getAsync = promisify(client.get).bind(client)
export const setAsync = promisify(client.set).bind(client)
7 changes: 7 additions & 0 deletions capitulo_5/5.5.3/server/repository/Stormtrooper.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import db from '../config/pg.js'
import { setAsync } from '../config/redis.js'

const sql = `SELECT
st.id, st.name, st.nickname,
Expand All @@ -17,6 +18,12 @@ const Stormtrooper = {
byId(id) {
return db.query(`${sql} WHERE st.id = $1::int`, [id])
.then(result => result.rows && result.rows[0])
.then(result => {
const SIX_MINUTES = 60 * 6
setAsync(`trooper:${id}`, JSON.stringify(result), 'EX', SIX_MINUTES)
.catch(e => console.log(e))
return result
})
},
create(data) {
const sql = `INSERT INTO stormtroopers (name, nickname, id_patent)
Expand Down
14 changes: 10 additions & 4 deletions capitulo_5/5.5.3/server/routes/trooper.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,26 @@
import { Router } from 'express'
import createError from 'http-errors'
import controller from '../controller/Stormtrooper.js'
import { getAsync } from '../config/redis.js'
const trooperRoutes = new Router()

const verifyId = (request, response, next) => {
const id = request.params.id
if (!/^[0-9]+$/.test(id)) {
return next(createError(422, 'invalid id'))
}
next()
}

const fromCache = (request, response, next) => {
getAsync(`trooper:${request.params.id}`)
.then(result => {
if (!result) return next()
response.send(JSON.parse(result))
})
.catch(_ => next())
}
trooperRoutes.get('/', controller.list)
trooperRoutes.get('/:id', verifyId, controller.byId)
trooperRoutes.get('/:id', verifyId, fromCache, controller.byId)
trooperRoutes.post('/', controller.create)
trooperRoutes.put('/:id', verifyId, controller.updateById)
trooperRoutes.delete('/:id', verifyId, controller.deleteById)

export default trooperRoutes

0 comments on commit cb406d0

Please sign in to comment.