apiController.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. var debug = require('debug')('ylt:server');
  2. var runsQueue = require('../datastores/runsQueue');
  3. var runsDatastore = require('../datastores/runsDatastore');
  4. function ApiController(app) {
  5. 'use strict';
  6. // Retrieve the list of all runs
  7. /*app.get('/runs', function(req, res) {
  8. // NOT YET
  9. });*/
  10. // Create a new run
  11. app.post('/runs', function(req, res) {
  12. // Grab the test parameters
  13. var run = {
  14. // Generate a random run ID
  15. _id: (Date.now()*1000 + Math.round(Math.random()*1000)).toString(36),
  16. params: {
  17. url: req.body.url,
  18. waitForResponse: req.body.waitForResponse || true
  19. }
  20. };
  21. // Add test to the testQueue
  22. debug('Adding test %s to the queue', run._id);
  23. var queuing = runsQueue.push(run._id);
  24. // Save the run to the datastore
  25. var position = runsQueue.getPosition(run._id);
  26. run.status = {
  27. statusCode: (position === 0) ? STATUS_RUNNING : STATUS_AWAITING,
  28. position: position
  29. };
  30. runsDatastore.add(run);
  31. // Listening for position updates
  32. queuing.progress(function(position) {
  33. var savedRun = runsDatastore.get(run._id);
  34. savedRun.status = {
  35. statusCode: STATUS_AWAITING,
  36. position: position
  37. };
  38. runsDatastore.update(savedRun);
  39. });
  40. queuing.then(function() {
  41. });
  42. // The user doesn't not want to wait for the response
  43. if (!params.waitForResponse) {
  44. // Sending just the test id
  45. res.setHeader('Content-Type', 'application/javascript');
  46. res.send(JSON.stringify({
  47. testId: testId
  48. }));
  49. }
  50. });
  51. // Retrive one run by id
  52. app.get('/run/:id', function(req, res) {
  53. });
  54. // Delete one run by id
  55. /*app.delete('/run/:id', function(req, res) {
  56. // NOT YET
  57. });*/
  58. var STATUS_AWAITING = 'awaiting';
  59. var STATUS_RUNNING = 'running';
  60. var STATUS_DONE = 'done';
  61. var STATUS_FAILED = 'failed';
  62. }
  63. module.exports = ApiController;