Created
December 5, 2019 18:09
-
-
Save haimrait/25a56e4ce3c083792adff80486692584 to your computer and use it in GitHub Desktop.
node-redis-mongo - final book routes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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