Node Routes with Functional Programming

Today’s post is a little short and a little late as I’m pretty busy at work!

I’m going to do a quick functional programming example that I do in my routing of my application, now there probably is an easier way, but as allways programming is a process.

Here’s the code:

_boolHandle = (_f) -> (req, res) ->
  _testExists req.params.ticketID, res, -></pre>
    _f req, res, (err, results) -> if err then res.status(500).json err else res.status(200).json results or true
app.post '/api/ticket/:ticketID/metadata', _boolHandle (req, res, cb) -> $tickets.metadata req.params.ticketID, req.body, cb

This is essentially a post handler in express 4 that calls a function that returns a function to call a function to call a standard response!

If we break it down, when we register the handler, normally this would be written as follows:


app.post '/api/ticket/:ticketID/metadata', (req, res) -> res.status(200).json true

My first step was figuring out that every call I made to the $ticket object calls it’s callback with (err, result) and returned the results, so my code then looks like this:


app.post '/api/ticket/:ticketID/metadata', (req, res) -> $ticket.metadata req.params.ticketID, (err, result) -> if err then res.status(500).json err else res.status(200).json result

Because I’m lazy I decided I didn’t want to write out the callback every time, it’s always the same so why bother? So my first functional programming block was this:

_boolHandle = (_f) -> (req, res) ->
  _f req, res, (err, results) -> if err then res.status(500).json err else res.status(200).json results or true
app.post '/api/ticket/:ticketID/metadata', _boolHandle (req, res, cb) -> $tickets.metadata req.params.ticketID, cb

As you can see I abstracted out the response by creating a wrapper around it. The other part I have in the code is the function that tests whether the ticketID actually exists (_testExists), if it exists it calls the callback else it returns a “ticket not found” error.

I hope this explanation helps someone out, if you have a better way of doing this – I’m all ears!!

About Simeon Cheeseman

I enjoy a wide variety of computer and board games, have a BSc in Computer Science and have played percussion for 18 years.

Posted on August 14, 2014, in CoffeeScript, Development, Javascript, Node.js and tagged , , , , , . Bookmark the permalink. Leave a comment.

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

%d bloggers like this: