Alright Day 2!
A very successful day. I spent a couple hours today removing the original boilerplate leftover from the kickstart process and set up a very basic API with CRUD operations. Then I tested the responses and worked on integrating them my mongo database.
Here’s an example of how my Create process works.
router.post('/p', function(req, res, next){
Post.create(req.body).then(function(post){
res.send(post);
}).catch(next);
});
So I am defining a route at my /api
path to listen for POST requests, if a request is sent then it passes that request body (JSON) and returns a promise with fires a callback to return a response of the original data on success, and if for some reason the actions fails it is caught and passes the error object to the next piece of middle-ware.
The rest of the file is bellow if you want to look at it.
Entire file
const express = require('express');
const router = express.Router();
const Post = require('../models/post');
// CRUD for posts
// Create
router.post('/p', function(req, res, next){
Post.create(req.body).then(function(post){
res.send(post);
}).catch(next);
});
// Retrieve
router.get('/p', function(req, res, next){
Post.find({}).then(function(posts){
res.send(posts);
});
});
// Update
router.put('/p/:id', function(req, res, next){
Post.findByIdAndUpdate({_id: req.params.id}, req.body).then(function(post){
Post.findOne({_id: req.params.id}).then(function(post){
res.send(post);
});
});
});
// Delete
router.delete('/p/:id', function(req, res, next){
Post.findByIdAndRemove({_id: req.params.id}).then(function(post){
res.send(post);
});
});
module.exports = router;
Here is what testing my api looks like with postman.
As you can see, when going to api/p
all the current documents (right now) in the post collection are returned as raw json.
Lets compare that to whats in the database
And what do you know, it is the same!
Now, lets try creating new documents by sending post requests as json data.
It failed?! Yes, of course it did. I set up a error handling middleware to catch bad requests and return a 422 (Unprocessable entity) and return the error message of the error object. Without this, we would get a status of 200, because it was processed correctly, but it wasn’t we wanted.
So now lets send it some correct data.
Much better. And as you can see, the new post object was successfully returned to us as a reply.
Lets check the database just to make sure…
Perfect. Our basic api is behaving correctly now.
Thanks for reading! Stay tuned for tomorrows update.