From f4337d3072c42c70ec39e3a856d6c30162c03140 Mon Sep 17 00:00:00 2001 From: Arunoda Susiripala Date: Fri, 17 Feb 2017 09:42:32 +0530 Subject: [PATCH] Make sure reading the body of same JSON page request safe. (#1185) * Make sure reading the body of same JSON page request safe. It's not possible to read the body twice from fetch()'s response So, we've to clone the response before doing anything. * Fix tests. --- lib/router/router.js | 8 ++++++-- test/unit/router.test.js | 7 ++++--- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/lib/router/router.js b/lib/router/router.js index 74706f78..30f7ab5f 100644 --- a/lib/router/router.js +++ b/lib/router/router.js @@ -279,12 +279,16 @@ export default class Router extends EventEmitter { return props } - fetchRoute (route) { + async fetchRoute (route) { let promise = this.fetchingRoutes[route] if (!promise) { promise = this.fetchingRoutes[route] = this.doFetchRoute(route) } - return promise + + const res = await promise + // We need to clone this to prevent reading the body twice + // Becuase it's possible only once to read res.json() or a similar method. + return res.clone() } doFetchRoute (route) { diff --git a/test/unit/router.test.js b/test/unit/router.test.js index 4d53b6a5..9a76ed04 100644 --- a/test/unit/router.test.js +++ b/test/unit/router.test.js @@ -2,10 +2,11 @@ import Router from '../../dist/lib/router/router' describe('Router', () => { + const request = { clone: () => null } describe('.prefetch()', () => { it('should prefetch a given page', async () => { const router = new Router('/', {}) - const promise = Promise.resolve() + const promise = Promise.resolve(request) const route = 'routex' router.doFetchRoute = (r) => { expect(r).toBe(route) @@ -19,7 +20,7 @@ describe('Router', () => { it('should stop if it\'s prefetching already', async () => { const router = new Router('/', {}) const route = 'routex' - router.fetchingRoutes[route] = Promise.resolve() + router.fetchingRoutes[route] = Promise.resolve(request) router.doFetchRoute = () => { throw new Error('Should not happen') } await router.prefetch(route) }) @@ -48,7 +49,7 @@ describe('Router', () => { const router = new Router('/', {}) const routes = ['route1', 'route2', 'route3', 'route4'] - router.doFetchRoute = () => Promise.resolve() + router.doFetchRoute = () => Promise.resolve(request) await router.prefetch(routes[0]) await router.prefetch(routes[1])