A simple Node.js REST server simulator for Testing
You are developing a client application (Angular / React etc.) and you need to receive the data from a REST API service.
Often you don’t have the access to the remote service or it doesn’t have the required data for your tests (dynamically generated data).
A direct access to a test .json file is not possible from the client because of security restrictions of the browser (the browser should not be able to play with the filesystem).
Solution – Concept
A client app can request (GET) a predefined page to a local server and receive the JSON file for the test.
The server can be implemented in Node.js and it serves static files content as response to http requests.
Solution – Implementation
The code and the installation procedure are here: https://github.com/marco76/node_rest_server/
The structure of the code is very simple:
Here an example of response:
Solution – Details
The file server.js create a new http server and waits for http requests.
It instantiates a loaderModule that contain the class that will retrieve the JSON data.
// import the function from the module
var loaderModule = require('./ResponseLoader.js');
// create an instance of the prototype
var loader = new loaderModule("loader");
function requestService(request, response){
// url == filename without extension
var url = request.url;
// home page called
if (url=="/"){
url = "/index";
}
// call the method that load the static page
loader.load(url);
// prepare the http response
response.statusCode = 200;
response.setHeader('Content-Type', 'application/json');
// add the JSON content
response.end(loader.getJson());
}
The second important JavaScript file is the function that receives the request to load a file and retrieves the content:
function ResponseLoader (name){
// the content of the file is stored in this variable
var json;
// method that load the file on the base of the URL
ResponseLoader.prototype.load = function(url){
console.log("requested file: " + url);
// url: hello -> file: [current directory]/json/hello.json
fs.readFile( __dirname + '/json' +url+'.json', function (err, data) {
if (err) {
console.log('error');
throw err;
}
// the content of the file is assigned to the variable
json = data;
console.log(name + " : " +data.toString());
})
};
// give me the json content
ResponseLoader.prototype.getJson = function (){
console.log(name + " : return json");
return json;
};
The features are very basic but they can be easily extended. The code is modularized using the ‚module‘ feature of node.js.
If you come from Java / .NET : the import of modules is not standard in JavaScript until ECMAScript 6.