Skip to content

Commit

Permalink
timeout support + bugfixes
Browse files Browse the repository at this point in the history
  • Loading branch information
CezaryDanielNowak committed Nov 30, 2015
1 parent c878025 commit 6ffc456
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 26 deletions.
16 changes: 10 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,12 @@ API
- when `true` is returned, request will be saved and ready to use
- when `false` is returned, request won't be saved and cache entry will be
served instead (if available)
- `timeout` {object}: Milliseconds, helps terminating requests for really
slow backends.

`requestEnvelope` sample:

`requestEnvelope` format:
------
```
{
reqURL: 'http://my-api.local/method/route?action=sth',
Expand All @@ -86,9 +90,9 @@ var apiCache = new APICacheProxy({...})
var app = express()
app.use('/api', function(req, res, next) {
apiCacheProxy(req, res, next).catch(function(envelope) {
res.status(envelope.statusCode).send(
'<pre>' + envelope.body + '</pre>'
apiCacheProxy(req, res, next).catch(function(requestEnvelope) {
res.status(requestEnvelope.statusCode).send(
'<pre>' + requestEnvelope.body + '</pre>'
)
})
})
Expand All @@ -101,9 +105,9 @@ var apiCache = new APICacheProxy({...})
var app = express()
app.use('/api', function(req, res, next) {
apiCacheProxy(req, res, next).then(function(status, envelope) {
apiCacheProxy(req, res, next).then(function(status) {
if (status.dataSource === 'Cache') {
console.warn('[' + envelope.method + '] ' + envelope.reqURL)
console.warn('[' + status.envelope.reqMethod + '] ' + status.envelope.reqURL)
console.warn(' API failure. Served: ' + status.filePath)
}
})
Expand Down
46 changes: 27 additions & 19 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,8 @@ var defaultConfig = {
},
localURLReplace: function(url) {
return url
}
},
timeout: false
}

APICache.prototype._createEnvelope = function(response, responseBody, requestBody) {
Expand Down Expand Up @@ -97,26 +98,26 @@ APICache.prototype.sendCachedResponse = function(res, envelope, resolve, reject)
var data = fs.readFileSync(filePath, 'utf-8')
} catch(e) {
reject(envelope)
if (res.headersSent) { // in case of custom error handling in promise.catch
this.sendResponse(res, envelope.statusCode, envelope.headers, envelope.body)
}
this.sendResponse(res, envelope.statusCode, envelope.headers, envelope.body)
return false
}
var cachedEnvelope = JSON.parse(data)
var headers = cachedEnvelope.headers
headers[MODULE_NAME + '-hit-date'] = cachedEnvelope.cacheDate

this.sendResponse(res, cachedEnvelope.statusCode, headers, cachedEnvelope.body)
resolve({
dataSource: "Cache",
sourceFile: filePath,
filePath: filePath,
envelope: cachedEnvelope
})
this.sendResponse(res, cachedEnvelope.statusCode, headers, cachedEnvelope.body)
}

APICache.prototype.sendResponse = function(res, statusCode, headers, body) {
res.writeHead(statusCode ? statusCode : 500, headers);
res.end(body)
if (!res.headersSent) { // in case of custom error handling in promise.catch
res.writeHead(statusCode ? statusCode : 500, headers);
res.end(body)
}
}

/**
Expand Down Expand Up @@ -171,7 +172,7 @@ APICache.prototype.onError = function(err, apiReq, res, requestBody, resolve, re
reqBody: requestBody
}

this.sendCachedResponse(res, envelope, reject, resolve)
this.sendCachedResponse(res, envelope, resolve, reject)
}
/**
* POST, PUT methods' payload need to be taken out from request object.
Expand Down Expand Up @@ -223,16 +224,23 @@ function APICache(config) {
var promise = new Promise(function(resolve, reject) {
var apiReq = request(url)

req.pipe(apiReq)
.on('response', function(response) {
this.onResponse(response, res, reqBodyRef.requestBody, resolve, reject)
}.bind(this))
.on('error', function(err) {
this.onError(err, apiReq, res, reqBodyRef.requestBody, resolve, reject)
promise.catch(function() {
log('API Error', url, err)
})
}.bind(this))
req
.pipe(apiReq)
.on('response', function(response) {
this.onResponse(response, res, reqBodyRef.requestBody, resolve, reject)
}.bind(this))
.on('error', function(err) {
this.onError(err, apiReq, res, reqBodyRef.requestBody, resolve, reject)
promise.catch(function() {
log('API Error', url, err)
})
}.bind(this))

if (this.config.timeout) {
setTimeout(function (argument) {
apiReq.abort()
}, this.config.timeout)
}
}.bind(this))

return promise
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "node-api-cache-proxy",
"version": "0.5.0",
"version": "0.6.0",
"description": "Cache requests in nodejs",
"main": "index.js",
"scripts": {
Expand Down

0 comments on commit 6ffc456

Please sign in to comment.