Skip to content

Instantly share code, notes, and snippets.

@tomekc
Created July 4, 2013 21:59
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save tomekc/5930477 to your computer and use it in GitHub Desktop.
Save tomekc/5930477 to your computer and use it in GitHub Desktop.
Before running, install express by running npm install express and run with: node absurd_rest_service.js in this script's directory. Then: To submit calculation to curl -i -H "Content-Type: application/json" -d '{ "operation" : "+", "operands" : [ 2,3] }' http://localhost:3000/calculations To see results, use link from response: curl http://loca…
/*
Before running, install express by running
npm install express
and run with:
node absurd_rest_service.js
in this script's directory.
Then:
To submit calculation to
curl -i -H "Content-Type: application/json" -d '{ "operation" : "+", "operands" : [ 2,3] }' http://localhost:3000/calculations
curl http://localhost:3000/results/1
*/
var express = require('express');
var events = require('events');
var app = express();
app.use(express.bodyParser());
var sequence = 0; // poor man's sequence
var results = [];
function execute(operation) {
if (operation.operation === '+') {
return operation.operands[0] + operation.operands[1];
} else if (operation.operation === '*') {
return operation.operands[0] * operation.operands[1];
}
}
app.post('/calculations', function (req, res) {
res.setHeader('Content-Type', 'application/json');
sequence++;
results[sequence] = execute(req.body);
res.status(202);
res.json({ outcome: "success", links: { result: "http://localhost:3000/results/" + sequence } });
});
app.get('/results/:id', function (req, res) {
res.setHeader('Content-Type', 'application/json');
res.json({ result: results[req.params['id']] });
});
app.listen(3000);
console.log("App listening on port 3000");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment