Skip to main content

Building mock web service in node.js instead of Web API

I needed to build a mock back-end web service this week because the middle-ware team wasn't ready (they're useless standard Java 'enterprise' developers) and @Jason challenged me to write it in node.js. He showed me an example of how this was done before and said it shouldn't take more than 5 minutes to have something up and running, I've done this kind of requirement previously in Web API and thought it would be interesting to finally do 'something' in node.

All coding contexts have been changed to protect the innocents :)

The requirement was for a web service returning JSON defined resources and the idea was to map the request URL to the local the file system, where the actual content to be returned is contained in a *.json file and the actual file-name represent the HTTP code to be returned, some examples are show below:

'http://localhost:1008/examples/user/1' maps to 'd:\work\node\resources\user\1\200.json'

'http://localhost:1008/examples/user/2' maps to 'd:\work\node\resources\user\2\404.json'

'http://localhost:1008/examples/user/3' maps to 'd:\work\node\resources\user\3\302.json'

So the above example User '1' maps onto a valid response (200 HTTP code) and returns a User JSON object contained in the 200.json file, user '2' maps onto a unknown resource (404 HTTP code) and will return the message contained in the 404.json file and finally user '3' cause a URL redirect to another User resource as defined in the 302 file.

This could very easily be done using Web API or node.js, either implementations allow me to dynamically add resources as I require - I can modify the types & number of the resources without having to recompile & restart anything for the new resources to work. Having built mock service in Web API before I was interested to find out how much & how quick it would be to build it with node.

First, download and install node from here, I went for the standard install using the MSI installer:
Second, download Web Storm evaluation version from here, I decided to try out Web Storm and esque my usual choice of Visual Studio:
After going with the standard install node needs to be configured in Web Storm. This can be done by going to File -> Default Settings and selecting 'node' - and installed the pre-requisties and configure the executable path for the node executable:
Once configured ready to do some node development:)

I created an emtpy project and add a 'server.js' file:
Next was to configure debugging to use node, this is simple, just selected the node configuration and add the 'server.js' to application server path:
The project is ready to go, okay it does nothing, but I can at least start the debugger and see the output in the Web Storm console window:
I used express.js to handle the HTTP requests & responses and node-fs to access the local file system. These are 'added' using node package manager - this is similar to nuGet, except that it is more mature and reliable IMO. These and other modules are referenced in the 'server.js' file as 'require' statements, you can see this in the following screenshot:
Loading ....
Hopefully what should be obvious from the above, there are two handlers for HTTP requests, one is for resources under the 'examples' sub path and the other is a wildcard for everything else which will return a 404 HTTP code. The other thing to note is the use of the options module, this is for parsing command line parameters and this give the ability to specify a port for HTTP server (defaults to port 1008 if not specified).

The service is going to map HTTP requests to file system locations, the project viewer in Web Storm give a good idea of what I mean, the screenshot below shows the file structure of not only the javascript files but also the mock resources I'm going to use:
The resource is going to be a 'User', and as you can see there will be three available, id = 7, id =8 & id = 9. Each will return a different HTTP code and possible data as described:

    Id = 7 - this will return HTTP code 200, with the contents (json) of the 200.json file,

    Id = 8 - this will return HTTP code 404, with the content (message) of the 404.json file,

    Id = 9 - this will return HTTP code 302, with the header (location) of the 302.json file,

So this pattern allows me to mock out any response scenario from the service - any HTTP code can be mocked.

The other thing to note about the above screenshot is the 'statusCodes.js' file - this is a locally defined npm module. It's responiblity is to dynamically load the other local modules in the 'status_code_handlers' folder, these modules provide the specific logic for full-filling a HTTP code, e.g. the '200.js' file is shown below:
The completed 'server.js' file looks like this:
Loading ....
Running the server up I get the following responses in Fiddler:

Requesting User resource Id = 7 return a 200 code with the specific data (json):
Requesting User resource for Id = 8 returns a 404 with the specific error message:
Requesting User resource for Id = 9 redirects to User Resource Id = 7, hence the two requests seen in Fiddler:
That pretty much covers it, it's been a much quicker refactoring loop using Web Storm and node instead of Visual Studio and Web API - Web Storm is a much more responsive development environment, quicker to load, quicker to start a debugger etc...

The code is available for download:

Comments

Popular posts from this blog

WPF tips & tricks: Dispatcher thread performance

Not blogged for an age, and I received an email last week which provoked me back to life. It was a job spec for a WPF contract where they want help sorting out the performance of their app especially around grids and tabular data. I thought I'd shared some tips & tricks I've picked up along the way, these aren't probably going to solve any issues you might be having directly, but they might point you in the right direction when trying to find and resolve performance issues with a WPF app. First off, performance is something you shouldn't try and improve without evidence, and this means having evidence proving you've improved the performance - before & after metrics for example. Without this you're basically pissing into the wind, which can be fun from a developer point of view but bad for a project :) So, what do I mean by ' Dispatcher thread performance '? The 'dispatcher thread' or the 'UI thread' is probably the most

Showing a message box from a ViewModel in MVVM

I was doing a code review with a client last week for a WPF app using MVVM and they asked ' How can I show a message from the ViewModel? '. What follows is how I would (and have) solved the problem in the past. When I hear the words ' show a message... ' I instantly think you mean show a transient modal message box that requires the user input before continuing ' with something else ' - once the user has interacted with the message box it will disappear. The following solution only applies to this scenario. The first solution is the easiest but is very wrong from a separation perspective. It violates the ideas behind the Model-View-Controller pattern because it places View concerns inside the ViewModel - the ViewModel now knows about the type of the View and specifically it knows how to show a message box window: The second approach addresses this concern by introducing the idea of messaging\events between the ViewModel and the View. In the example below

Implementing a busy indicator using a visual overlay in MVVM

This is a technique we use at work to lock the UI whilst some long running process is happening - preventing the user clicking on stuff whilst it's retrieving or rendering data. Now we could have done this by launching a child dialog window but that feels rather out of date and clumsy, we wanted a more modern pattern similar to the way <div> overlays are done on the web. Imagine we have the following simple WPF app and when 'Click' is pressed a busy waiting overlay is shown for the duration entered into the text box. What I'm interested in here is not the actual UI element of the busy indicator but how I go about getting this to show & hide from when using MVVM. The actual UI elements are the standard Busy Indicator coming from the WPF Toolkit : The XAML behind this window is very simple, the important part is the ViewHost. As you can see the ViewHost uses a ContentPresenter element which is bound to the view model, IMainViewModel, it contains 3 child v