Aula: NoSQL - Redis e MongoDB
const express = require("express");
const redis = require("redis");
const { MongoClient } = require("mongodb");
const app = express();
const redisClient = redis.createClient();
const mongoClient = new MongoClient("mongodb://localhost:27017");
redisClient.connect();
async function cache(req, res, next) {
const chave = `req:${req.originalUrl}`;
const cached = await redisClient.get(chave);
if (cached) {
return res.json(JSON.parse(cached));
}
res.json = (function (json) {
return function (dados) {
redisClient.setEx(chave, 300, JSON.stringify(dados));
return json.call(this, dados);
};
})(res.json);
next();
}
app.get("/posts", cache, async (req, res) => {
const db = mongoClient.db("meu_app");
const posts = await db.collection("posts").find({}).limit(20).toArray();
res.json(posts);
});
app.get("/trending", async (req, res) => {
const trending = await redisClient.zrevrange(
"trending_posts",
0,
9,
"WITHSCORES",
);
res.json(trending);
});
app.post("/posts/:id/view", async (req, res) => {
const { id } = req.params;
await redisClient.incr(`post:${id}:views`);
const views = await redisClient.get(`post:${id}:views`);
await redisClient.zadd("trending_posts", views, id);
const db = mongoClient.db("meu_app");
await db.collection("eventos").insertOne({
tipo: "visualizacao",
post_id: parseInt(id),
timestamp: new Date(),
});
res.json({ sucesso: true });
});
app.listen(3000, () => {
console.log("Servidor rodando em http://localhost:3000");
});