Skip to content

Instantly share code, notes, and snippets.

@haimrait
Created December 5, 2019 18:09
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save haimrait/25a56e4ce3c083792adff80486692584 to your computer and use it in GitHub Desktop.
Save haimrait/25a56e4ce3c083792adff80486692584 to your computer and use it in GitHub Desktop.
node-redis-mongo - final book routes
const mongoose = require("mongoose");
const { clearKey } = require("../services/cache");
const Book = mongoose.model("Book");
module.exports = app => {
app.get("/api/books", async (req, res) => {
let books;
if (req.query.author) {
books = await Book.find({ author: req.query.author }).cache();
} else {
books = await Book.find().cache({
time: 10
});
}
res.send(books);
});
app.post("/api/books", async (req, res) => {
const { title, content, author } = req.body;
const book = new Book({
title,
content,
author
});
try {
await book.save();
clearKey(Book.collection.collectionName);
res.send(book);
} catch (err) {
res.send(400, err);
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment