Back End Routes and Promises

Today I contributed to work on the back end system by working on the routes. This meant creating a file for each HTTP verb in each folder for every model we expect to have in our application. For example, we expect to log visits, so we needed a “visits” controller and we needed to fulfill the read all, read one, create, update, and delete actions (or modes). A particular combination of HTTP verb and the presence of an “id” parameter implements these:

  • Read all – GET without an id
  • Read one – GET with an id
  • Create – POST without an id
  • Update – POST with an id
  • Delete – DELETE (with a mandatory id)

Using the HTTP verbs means we can have shorter, simpler route names. We can use GET for read one, and POST for update, so that we only need a “/visits” route, instead of having two routes: “/visits/read” and “/visits/update”. We still have to make two routes, but shorter route names are always nice.

I again learned more about Node.js today as I tried to link all the routes into the application, and debug why they weren’t registering when I ran the server on our local machines. I learned about using “require” and the “module.exports” object in Node.js. I also learned about promises, and how they can help you code asynchronously without using callbacks. Thank you Mozilla Developer Network! ^_^ Instead of callbacks, you can chain JavaScript function calls:

new Promise(
    (resolve, reject) => {
        if (finishBlogPost()) // maybe this isn't successful?
            resolve();
        else
            reject();
    }
)
.then(
    // this runs if resolve() was called
    (successValue) => {
        feelGoodAbout(successValue);
        goToBed();
    }
)
.catch(
    // this runs if reject() was called
    (failureReason) => {
        worryAbout(failureReason);
        stayUpAllNight();
    }
);
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s