diff --git a/capitulo_5/5.5.3/package.json b/capitulo_5/5.5.3/package.json index 9f56fc3..d4051e5 100644 --- a/capitulo_5/5.5.3/package.json +++ b/capitulo_5/5.5.3/package.json @@ -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" } } diff --git a/capitulo_5/5.5.3/server/config/redis.js b/capitulo_5/5.5.3/server/config/redis.js new file mode 100644 index 0000000..1ce016e --- /dev/null +++ b/capitulo_5/5.5.3/server/config/redis.js @@ -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) diff --git a/capitulo_5/5.5.3/server/repository/Stormtrooper.js b/capitulo_5/5.5.3/server/repository/Stormtrooper.js index 656391e..8e5e6bf 100644 --- a/capitulo_5/5.5.3/server/repository/Stormtrooper.js +++ b/capitulo_5/5.5.3/server/repository/Stormtrooper.js @@ -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, @@ -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) diff --git a/capitulo_5/5.5.3/server/routes/trooper.js b/capitulo_5/5.5.3/server/routes/trooper.js index a80c201..8d75756 100644 --- a/capitulo_5/5.5.3/server/routes/trooper.js +++ b/capitulo_5/5.5.3/server/routes/trooper.js @@ -1,8 +1,8 @@ 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)) { @@ -10,11 +10,17 @@ const verifyId = (request, response, next) => { } 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