From 206d6784d1520bddcc99e92f7fa873467278407d Mon Sep 17 00:00:00 2001 From: Randall Schmidt Date: Sat, 28 Nov 2020 11:25:23 -0500 Subject: [PATCH] handle fs read streams --- index.js | 8 ++++++-- test/tests.js | 22 ++++++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/index.js b/index.js index e2f1ce0..8749a15 100644 --- a/index.js +++ b/index.js @@ -11,13 +11,17 @@ function md5(str) { } function getBodyCacheKeyJson(body) { - if (typeof body === 'string') { + if (!body) { + return body; + } if (typeof body === 'string') { return body; } if (body instanceof URLSearchParams) { return body.toString(); + } if (body instanceof fs.ReadStream) { + return body.path; } - return body; + throw new Error('Unsupported body type'); } function getCacheKey(requestArguments) { diff --git a/test/tests.js b/test/tests.js index 7e882d3..acca098 100644 --- a/test/tests.js +++ b/test/tests.js @@ -1,3 +1,4 @@ +const fs = require('fs'); const assert = require('assert'); const rimraf = require('rimraf'); const path = require('path'); @@ -141,6 +142,27 @@ describe('Cache tests', function() { res = await fetch(TWO_HUNDRED_URL, post(new URLSearchParams('a=a'))); assert.strictEqual(res.fromCache, true); }); + + it('Gives different read streams different cache keys', async function() { + const s1 = fs.createReadStream(__filename); + const s2 = fs.createReadStream(path.join(__dirname, '..', 'index.js')); + + res = await fetch(TWO_HUNDRED_URL, post(s1)); + assert.strictEqual(res.fromCache, false); + + res = await fetch(TWO_HUNDRED_URL, post(s2)); + assert.strictEqual(res.fromCache, false); + }); + + it('Gives the same read streams the same cache key', async function() { + const s1 = fs.createReadStream(__filename); + + res = await fetch(TWO_HUNDRED_URL, post(s1)); + assert.strictEqual(res.fromCache, false); + + res = await fetch(TWO_HUNDRED_URL, post(s1)); + assert.strictEqual(res.fromCache, true); + }); }).timeout(10000); describe('Data tests', function() {