forked from SmartDropLabs/smartdrop-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtimeout.js
More file actions
25 lines (20 loc) · 690 Bytes
/
Copy pathtimeout.js
File metadata and controls
25 lines (20 loc) · 690 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
'use strict';
const AppError = require('../errors/AppError');
const config = require('../config');
/**
* Creates per-route timeout middleware.
* If the response does not finish within `timeoutMs`, it yields a 504 TIMEOUT error.
*/
function routeTimeout(timeoutMs = config.routeTimeoutMs || 30000) {
return (req, res, next) => {
const timer = setTimeout(() => {
if (!res.headersSent) {
return next(new AppError('TIMEOUT', 'Route execution timed out', 504, { timeout_ms: timeoutMs }));
}
}, timeoutMs);
res.on('finish', () => clearTimeout(timer));
res.on('close', () => clearTimeout(timer));
next();
};
}
module.exports = { routeTimeout };