diff --git a/package.json b/package.json index 5859ea21dbe082ff45e4fa0cd30f33278c476317..98b96c176503f7ae41b188849b0fb9d63874ea5f 100644 --- a/package.json +++ b/package.json @@ -21,7 +21,8 @@ "morgan": "^1.6.1", "noble": "^1.1.0", "asyncawait": "^0.7.4", - "apicache": "*" + "apicache": "*", + "connect-timeout": "*" }, "repository": { "type": "git", diff --git a/server.js b/server.js index b96fe6c2a279c635f2cc8e46450b5cd44f17e0d8..41cfb74507b7f661c58c372d0079b5f22a65fabb 100755 --- a/server.js +++ b/server.js @@ -11,6 +11,7 @@ var await = require( 'asyncawait/await' ); var async = require( 'asyncawait/async' ); var apicache = require( 'apicache' ).options( { defaultDuration: 15000 } ); var cache = apicache.middleware; +var timeout = require( 'connect-timeout' ); var config = require( process.env.AUGUSTCTL_CONFIG || './config.json' ); var serverConfig = require( process.env.AUGUSTCTL_SERVER_CONFIG || './server-config.json' ); @@ -70,12 +71,21 @@ function clearCaches( lockName ) { return true; } +// Middleware to handle timeout status checks +function haltOnTimedout( req, res, next ) { + if ( req.timedout ) { + lock.disconnect(); + } else { + next(); + } +} + /** * ROUTES */ // Endpoint to check lock status -app.get( '/api/status/:lock_name', cache( '5 seconds' ), function( req, res ) { +app.get( '/api/status/:lock_name', timeout( '5 seconds' ), cache( '5 seconds' ), haltOnTimedout, function( req, res ) { // Parse allowed request arguments var lock = getLockInstance( req.params.lock_name, res ); if ( ! lock ) { @@ -102,7 +112,7 @@ app.get( '/api/status/:lock_name', cache( '5 seconds' ), function( req, res ) { } ); // Endpoint to change lock state -app.get( '/api/:lock_action(lock|unlock)/:lock_name', cache( '3 seconds' ), function( req, res ) { +app.get( '/api/:lock_action(lock|unlock)/:lock_name', timeout( '5 seconds' ), cache( '3 seconds' ), haltOnTimedout, function( req, res ) { // Parse allowed request arguments var action = req.params.lock_action, allowedActions = [ 'unlock', 'lock' ];