This month, I celebrate three years in Argentina. During these three years, I've had the pleasure and pain of learning a great deal of porteƱo slang, lunfardo. I figured there was an opportunity to do a simple COVID-quarantine project to record and build on this obscure vocabulary. The first step was to build a backend.
I've called it "ismo," because that's the back-end of the word "lunfardismo."
My very simple data model defined an "Entry." Like any dictionary, you need a word, a definition, a part of speech (noun, verb, etc.). Beyond those core parts, everything else is optional, to my mind. Providing a field for a phonetic (how the word is pronounced), an example, and a language/country of origin felt like useful additions.
Tracking when a word was added and whether or not it was to be published, and generating a URL slug would be necessary for later building a UI, if I felt so inclined.
For the sake of not pasting here what you can see by visiting the repository, let's walk through a single function - to create a new Entry in the database.
I'll note that you could do this with async
/await
as well as promises:
// The async/await version:
exports.createEntry = async (req, res) => {
try {
const doc = await Models.Entry.create(req.body)
res.status(200).json(doc)
} catch (error) {
console.error(error)
res.status(500).json(error)
}
}
// The promises version:
exports.createEntry = (req, res) => {
Models.Entry.create(req.body)
.then(doc => {
res.status(200).json(doc)
})
.catch(error => {
console.error(error)
res.status(500).json(error)
})
}
Models.Entry refers to the mongoose model we exported in models/index.js
.
The create method returns a promise, meaning that when it is resolved or rejected we can return the response.
We create a new document passing the POST request body. That body might look like this:
{
"title": "Fiaca",
"definition": "Laziness.",
"part_speech": "Noun"
}
Cool. So I'll write my other functions, map endpoints to them, like so...
const router = express.Router()
router
.route("/api/entry")
.get(entry.get)
.post(entry.post)
router
.route("/api/entry/:slug")
.get(entry.slug.get)
.patch(entry.slug.patch)
.delete(entry.slug.delete)
module.exports = router
... and I'll have the world's simplest REST API for a dictionary app. Then I can fire up Postman or Insomnia and start testing.
Note [July 2020]: I've already made "big" updates to the repo but the idea is always the same: model, middleware, router.