1
0
Fork 0
mirror of https://github.com/terribleplan/next.js.git synced 2024-01-19 02:48:18 +00:00

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.
This commit is contained in:
Arunoda Susiripala 2017-02-17 09:42:32 +05:30 committed by Guillermo Rauch
parent 9f3e61b0fe
commit f4337d3072
2 changed files with 10 additions and 5 deletions

View file

@ -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) {

View file

@ -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])