Commit f4337d30 authored by Arunoda Susiripala's avatar Arunoda Susiripala Committed by Guillermo Rauch

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.
parent 9f3e61b0
......@@ -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) {
......
......@@ -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])
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment