-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
290 lines (250 loc) · 7.75 KB
/
index.js
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
/* global require, console, module, Buffer */
'use strict'
var assert = require('assert')
var extract = require('url-querystring')
var filendir = require('filendir')
var fs = require('fs')
var getRawBody = require('raw-body')
var omit = require('object.omit')
var packageJson = require('./package.json')
var path = require('path')
var request = require('@cypress/request')
var sanitize = require('sanitize-filename')
var zlib = require('zlib')
var { createHash } = require('node:crypto');
/**
* Returns an MD5 hash for the given `content`.
*
* @param {String} content
* @returns {String}
*/
function MD5(content) {
return createHash('md5').update(content).digest('hex')
}
var MODULE_NAME = 'api-cache-proxy'
var log = console.log.bind(console, '[' + MODULE_NAME + '] ')
var defaultConfig = {
apiUrl: '',
cacheEnabled: true,
cacheDir: 'api-cache/',
excludeRequestHeaders: [],
excludeRequestParams: [],
isValidResponse: function(envelope) {
if (envelope.statusCode === 200) {
return true
} else {
return false
}
},
localURLReplace: function(url) {
return url
},
timeout: false
}
Object.assign(APICache.prototype, {
_createEnvelope: function(response, responseBody, requestBody) {
var excludeRequestHeaders = [
'content-encoding', // content is unpacked, content-encoding doesn't apply anymore,
'content-length', // when content is uncpacked, content-length is different.
'connection',
'transfer-encoding'
]
excludeRequestHeaders.push.apply(excludeRequestHeaders, this.config.excludeRequestHeaders)
var headers = omit(response.headers, excludeRequestHeaders)
return {
cacheDate: new Date().toISOString().substr(0, 19).replace('T', ' '),
reqURL: this._clearURLParams(response.request.href),
reqMethod: response.request.method,
reqHeaders: response.request.headers,
reqBody: requestBody,
body: responseBody,
headers: headers,
statusCode: response.statusCode,
statusMessage: response.statusMessage,
version: packageJson.version
}
},
onResponse: function(apiResponse, res, requestBody, resolve, reject) {
var body = []
apiResponse.on('data', function(chunk) {
// Data is Buffer when gzip, text when not-gzip
body.push(chunk)
})
apiResponse.on('end', function() {
// Thanks, Nick Fishman
// http://nickfishman.com/post/49533681471/nodejs-http-requests-with-gzip-deflate-compression
var encoding = apiResponse.headers['content-encoding']
var buffer = Buffer.concat(body)
if (encoding === 'gzip') {
body = zlib.gunzipSync(buffer)
} else if (encoding == 'deflate') {
body = zlib.inflateSync(buffer)
} else {
body = buffer
}
body = body ? body.toString() : ''
var envelope = this._createEnvelope(apiResponse, body, requestBody)
if (this.config.isValidResponse(envelope)) {
this._saveRequest(envelope)
this.sendResponse(res, envelope.statusCode, envelope.headers, envelope.body)
resolve({
dataSource: 'API',
envelope: envelope
})
} else {
this.sendCachedResponse(res, envelope, resolve, reject)
}
}.bind(this))
},
sendCachedResponse: function(res, envelope, resolve, reject) {
var cachedEnvelope,
filePath = this._getFileName(envelope)
try {
var data = fs.readFileSync(filePath, 'utf-8')
cachedEnvelope = JSON.parse(data)
if (cachedEnvelope.version !== packageJson.version) {
throw new Error('Request envelope created in old plugin version.')
}
} catch(e) {
reject(envelope)
this.sendResponse(res, envelope.statusCode, envelope.headers, envelope.body)
return false
}
var headers = cachedEnvelope.headers
headers[MODULE_NAME + '-hit-date'] = cachedEnvelope.cacheDate
resolve({
dataSource: 'Cache',
filePath: filePath,
envelope: cachedEnvelope
})
this.sendResponse(res, cachedEnvelope.statusCode, headers, cachedEnvelope.body)
},
sendResponse: function(res, statusCode, headers, body) {
if (!res.headersSent) { // in case of custom error handling in promise.catch
res.writeHead(statusCode ? statusCode : 500, headers);
res.end(body)
}
},
/**
* clearURL takes url string as input and remove parameters, that are
* listed in config.excludeRequestParams
* @param {string} href
* @return {string}
*/
_clearURLParams: function(href) {
var url = extract(href)
var queryObj = omit(url.qs, this.config.excludeRequestParams)
var desiredUrlParams = Object.keys(queryObj).map(function(paramName) {
return paramName + '=' + encodeURIComponent(queryObj[paramName])
}).join('&')
return desiredUrlParams ? url.url + '?' + desiredUrlParams : url.url
},
_getFileName: function(envelope) {
var bodyHash = ''
if (envelope.reqMethod !== 'GET') {
bodyHash = ' ' + MD5(JSON.stringify(envelope.reqBody))
}
var sanitazedURL = sanitize(envelope.reqURL.replace('://', '-'), {replacement: '-'})
var fileName = envelope.reqMethod + '_' + sanitazedURL + bodyHash +'.tmp'
return path.resolve(this.config.cacheDir, fileName)
},
/**
* Save request to file
* @param {object} envelope
* @return {none}
*/
_saveRequest: function(envelope) {
var filePath = this._getFileName(envelope)
filendir.writeFile(filePath, JSON.stringify(envelope), function(err) {
if (err) {
log('File could not be saved in ' + this.config.cacheDir)
throw err
}
}.bind(this))
},
onError: function(apiReq, res, requestBody, resolve, reject) {
var envelope = { // this envelope is used just in _getFileName
reqMethod: apiReq.method,
reqURL: this._clearURLParams(apiReq.url || apiReq.href),
reqBody: requestBody
}
this.sendCachedResponse(res, envelope, resolve, reject)
},
/**
* POST, PUT methods' payload need to be taken out from request object.
* @param {object} req Request object
*/
_getRequestBody: function(req, returnReference) {
getRawBody(req).then(function(bodyBuffer) {
returnReference.requestBody = bodyBuffer.toString()
}).catch(function() {
log('Unhandled error in getRawBody', arguments)
})
},
_getApiURL: function(req) {
var url = req.url.split('/')
var newURL = this.config.apiUrl.replace(/\/+$/, '')
if (url[0] === '') {
// local path, like "/api/getToken"
url[0] = newURL
} else {
// remote address, like "http://localhost:8080/api/getToken"
url.splice(0, 3) // remove local protocol and domain part
url.unshift(newURL) // push destination api url
}
url = url.join('/')
return this.config.localURLReplace(url)
}
})
/**
* @constructor APICache
* @param {[type]} config [description]
*/
function APICache(config) {
assert(config, 'APICache requres config provided')
assert(config.apiUrl, 'APICache: provide apiUrl')
this.config = Object.assign({}, defaultConfig, config)
var handleRequest = function(req, res) {
var url = this._getApiURL(req)
var that = this
var reqBodyRef = {
requestBody: ''
}
this._getRequestBody(req, reqBodyRef)
var promise = new Promise(function(resolve, reject) {
var apiReq = request(url)
if (that.config.cacheEnabled) {
req
.pipe(apiReq)
.on('response', function(response) {
that.onResponse(response, res, reqBodyRef.requestBody, resolve, reject)
})
.on('error', function(err) {
that.onError(apiReq, res, reqBodyRef.requestBody, resolve, reject)
})
} else {
req.pipe(apiReq).pipe(res)
apiReq.on('response', function() {
resolve({dataSource: 'API'})
})
apiReq.on('error', function(err) {
reject(err)
})
}
if (that.config.timeout) {
setTimeout(function() {
that.onError(apiReq, res, reqBodyRef.requestBody, resolve, reject)
log('API Timeout', url)
apiReq.abort()
}, that.config.timeout)
}
})
return promise
}
promise.catch(function() {
log('API Error', url, err)
})
return Object.assign(handleRequest.bind(this), this)
}
module.exports = APICache
// TODO: endpoint with list of all cached entries