Unverified Commit ed59ad52 authored by Wyatt Johnson's avatar Wyatt Johnson Committed by GitHub

Change `NextInstance.fetch` Signature (#44575)

Co-authored-by: 's avatarkodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
parent 5fb56312
......@@ -2,6 +2,7 @@
import { createNextDescribe, FileRef } from 'e2e-utils'
import cheerio from 'cheerio'
import path from 'path'
import { withQuery } from 'next-test-utils'
createNextDescribe(
'app-dir with middleware',
......@@ -31,7 +32,7 @@ createNextDescribe(
},
])('Mutate request headers for $title', ({ path, toJson }) => {
it(`Adds new headers`, async () => {
const res = await next.fetch(path, null, {
const res = await next.fetch(path, {
headers: {
'x-from-client': 'hello-from-client',
},
......@@ -44,10 +45,9 @@ createNextDescribe(
it(`Deletes headers`, async () => {
const res = await next.fetch(
path,
{
withQuery(path, {
'remove-headers': 'x-from-client1,x-from-client2',
},
}),
{
headers: {
'x-from-client1': 'hello-from-client',
......@@ -78,11 +78,10 @@ createNextDescribe(
it(`Updates headers`, async () => {
const res = await next.fetch(
path,
{
withQuery(path, {
'update-headers':
'x-from-client1=new-value1,x-from-client2=new-value2',
},
}),
{
headers: {
'x-from-client1': 'old-value1',
......
......@@ -234,7 +234,7 @@ createNextDescribe(
})
it('should force SSR correctly for headers usage', async () => {
const res = await next.fetch('/force-static', undefined, {
const res = await next.fetch('/force-static', {
headers: {
Cookie: 'myCookie=cookieValue',
another: 'header',
......@@ -315,7 +315,7 @@ createNextDescribe(
const validParams = ['tim', 'seb', 'styfle']
for (const param of validParams) {
const res = await next.fetch(`/blog/${param}`, undefined, {
const res = await next.fetch(`/blog/${param}`, {
redirect: 'manual',
})
expect(res.status).toBe(200)
......@@ -330,7 +330,7 @@ createNextDescribe(
const invalidParams = ['timm', 'non-existent']
for (const param of invalidParams) {
const invalidRes = await next.fetch(`/blog/${param}`, undefined, {
const invalidRes = await next.fetch(`/blog/${param}`, {
redirect: 'manual',
})
expect(invalidRes.status).toBe(404)
......@@ -340,11 +340,9 @@ createNextDescribe(
it('should work with forced dynamic path', async () => {
for (const slug of ['first', 'second']) {
const res = await next.fetch(
`/dynamic-no-gen-params-ssr/${slug}`,
undefined,
{ redirect: 'manual' }
)
const res = await next.fetch(`/dynamic-no-gen-params-ssr/${slug}`, {
redirect: 'manual',
})
expect(res.status).toBe(200)
expect(await res.text()).toContain(`${slug}`)
}
......@@ -352,11 +350,9 @@ createNextDescribe(
it('should work with dynamic path no generateStaticParams', async () => {
for (const slug of ['first', 'second']) {
const res = await next.fetch(
`/dynamic-no-gen-params/${slug}`,
undefined,
{ redirect: 'manual' }
)
const res = await next.fetch(`/dynamic-no-gen-params/${slug}`, {
redirect: 'manual',
})
expect(res.status).toBe(200)
expect(await res.text()).toContain(`${slug}`)
}
......@@ -383,13 +379,9 @@ createNextDescribe(
]
for (const params of paramsToCheck) {
const res = await next.fetch(
`/blog/${params.author}/${params.slug}`,
undefined,
{
redirect: 'manual',
}
)
const res = await next.fetch(`/blog/${params.author}/${params.slug}`, {
redirect: 'manual',
})
expect(res.status).toBe(200)
const html = await res.text()
const $ = cheerio.load(html)
......@@ -436,7 +428,7 @@ createNextDescribe(
it('should ssr dynamically when detected automatically with fetch cache option', async () => {
const pathname = '/ssr-auto/cache-no-store'
const initialRes = await next.fetch(pathname, undefined, {
const initialRes = await next.fetch(pathname, {
redirect: 'manual',
})
expect(initialRes.status).toBe(200)
......@@ -449,7 +441,7 @@ createNextDescribe(
expect(initialHtml).toContain('Example Domain')
const secondRes = await next.fetch(pathname, undefined, {
const secondRes = await next.fetch(pathname, {
redirect: 'manual',
})
expect(secondRes.status).toBe(200)
......@@ -465,7 +457,7 @@ createNextDescribe(
})
it('should render not found pages correctly and fallback to the default one', async () => {
const res = await next.fetch(`/blog/shu/hi`, undefined, {
const res = await next.fetch(`/blog/shu/hi`, {
redirect: 'manual',
})
expect(res.status).toBe(404)
......@@ -477,7 +469,7 @@ createNextDescribe(
// TODO-APP: support fetch revalidate case for dynamic rendering
it.skip('should ssr dynamically when detected automatically with fetch revalidate option', async () => {
const pathname = '/ssr-auto/fetch-revalidate-zero'
const initialRes = await next.fetch(pathname, undefined, {
const initialRes = await next.fetch(pathname, {
redirect: 'manual',
})
expect(initialRes.status).toBe(200)
......@@ -490,7 +482,7 @@ createNextDescribe(
expect(initialHtml).toContain('Example Domain')
const secondRes = await next.fetch(pathname, undefined, {
const secondRes = await next.fetch(pathname, {
redirect: 'manual',
})
expect(secondRes.status).toBe(200)
......@@ -506,7 +498,7 @@ createNextDescribe(
})
it('should ssr dynamically when forced via config', async () => {
const initialRes = await next.fetch('/ssr-forced', undefined, {
const initialRes = await next.fetch('/ssr-forced', {
redirect: 'manual',
})
expect(initialRes.status).toBe(200)
......@@ -517,7 +509,7 @@ createNextDescribe(
expect(initial$('#page').text()).toBe('/ssr-forced')
const initialDate = initial$('#date').text()
const secondRes = await next.fetch('/ssr-forced', undefined, {
const secondRes = await next.fetch('/ssr-forced', {
redirect: 'manual',
})
expect(secondRes.status).toBe(200)
......
......@@ -20,12 +20,12 @@ createNextDescribe(
const controller1 = new AbortController()
const controller2 = new AbortController()
next
.fetch('/slow-page-no-loading', undefined, {
.fetch('/slow-page-no-loading', {
signal: controller1.signal,
})
.catch(() => {})
next
.fetch('/slow-page-no-loading', undefined, {
.fetch('/slow-page-no-loading', {
signal: controller2.signal,
})
.catch(() => {})
......@@ -35,7 +35,7 @@ createNextDescribe(
const controller3 = new AbortController()
next
.fetch('/slow-page-no-loading', undefined, {
.fetch('/slow-page-no-loading', {
signal: controller3.signal,
})
.catch(() => {})
......@@ -66,28 +66,20 @@ createNextDescribe(
}
it('should use application/octet-stream for flight', async () => {
const res = await next.fetch(
'/dashboard/deployments/123',
{},
{
headers: {
['RSC'.toString()]: '1',
},
}
)
const res = await next.fetch('/dashboard/deployments/123', {
headers: {
['RSC'.toString()]: '1',
},
})
expect(res.headers.get('Content-Type')).toBe('application/octet-stream')
})
it('should use application/octet-stream for flight with edge runtime', async () => {
const res = await next.fetch(
'/dashboard',
{},
{
headers: {
['RSC'.toString()]: '1',
},
}
)
const res = await next.fetch('/dashboard', {
headers: {
['RSC'.toString()]: '1',
},
})
expect(res.headers.get('Content-Type')).toBe('application/octet-stream')
})
......@@ -1895,7 +1887,7 @@ createNextDescribe(
})
;(isDev ? describe.skip : describe)('Subresource Integrity', () => {
function fetchWithPolicy(policy: string | null) {
return next.fetch('/dashboard', undefined, {
return next.fetch('/dashboard', {
headers: policy
? {
'Content-Security-Policy': policy,
......@@ -2405,7 +2397,7 @@ createNextDescribe(
describe('bots', () => {
if (!isNextDeploy) {
it('should block rendering for bots and return 404 status', async () => {
const res = await next.fetch('/not-found/servercomponent', '', {
const res = await next.fetch('/not-found/servercomponent', {
headers: {
'User-Agent': 'Googlebot',
},
......
......@@ -8,13 +8,9 @@ createNextDescribe(
},
({ next }) => {
it('should redirect route when requesting it directly', async () => {
const res = await next.fetch(
'/a/',
{},
{
redirect: 'manual',
}
)
const res = await next.fetch('/a/', {
redirect: 'manual',
})
expect(res.status).toBe(308)
expect(res.headers.get('location')).toBe(next.url + '/a')
})
......
......@@ -331,7 +331,7 @@ describe('app dir - rsc basics', () => {
})
it('should render css-in-js suspense boundary correctly', async () => {
await next.fetch('/css-in-js/suspense', null, {}).then(async (response) => {
await next.fetch('/css-in-js/suspense').then(async (response) => {
const results = []
await resolveStreamResponse(response, (chunk: string) => {
......@@ -393,15 +393,11 @@ describe('app dir - rsc basics', () => {
it('should support streaming for flight response', async () => {
await next
.fetch(
'/',
{},
{
headers: {
['RSC'.toString()]: '1',
},
}
)
.fetch('/', {
headers: {
['RSC'.toString()]: '1',
},
})
.then(async (response) => {
const result = await resolveStreamResponse(response)
expect(result).toContain('component:index.server')
......@@ -409,7 +405,7 @@ describe('app dir - rsc basics', () => {
})
it('should support partial hydration with inlined server data', async () => {
await next.fetch('/partial-hydration', null, {}).then(async (response) => {
await next.fetch('/partial-hydration').then(async (response) => {
let gotFallback = false
let gotData = false
let gotInlinedData = false
......
......@@ -8,13 +8,9 @@ createNextDescribe(
},
({ next }) => {
it('should redirect route when requesting it directly', async () => {
const res = await next.fetch(
'/a',
{},
{
redirect: 'manual',
}
)
const res = await next.fetch('/a', {
redirect: 'manual',
})
expect(res.status).toBe(308)
expect(res.headers.get('location')).toBe(next.url + '/a/')
})
......
......@@ -2,7 +2,7 @@ import os from 'os'
import path from 'path'
import fs from 'fs-extra'
import treeKill from 'tree-kill'
import { NextConfig } from 'next'
import type { NextConfig } from 'next'
import { FileRef } from '../e2e-utils'
import { ChildProcess } from 'child_process'
import { createNextInstall } from '../create-next-install'
......@@ -414,12 +414,17 @@ export class NextInstance {
}
/**
* Fetch the HTML for the provided page.
* Performs a fetch request to the NextInstance with the options provided.
*
* @param pathname the pathname on the NextInstance to fetch
* @param opts the optional options to pass to the underlying fetch
* @returns the fetch response
*/
public async fetch(
...args: Parameters<OmitFirstArgument<typeof fetchViaHTTP>>
pathname: string,
opts?: import('node-fetch').RequestInit
) {
return fetchViaHTTP(this.url, ...args)
return fetchViaHTTP(this.url, pathname, null, opts)
}
public on(event: Event, cb: (...args: any[]) => any) {
......
......@@ -111,8 +111,30 @@ export function getFullUrl(appPortOrUrl, url, hostname) {
return fullUrl
}
/**
* Appends the querystring to the url
*
* @param {string} pathname the pathname
* @param {Record<string,any> | string} query the query object to add to the pathname
* @returns the pathname with the query
*/
export function withQuery(pathname, query) {
const querystring = typeof query === 'string' ? query : qs.stringify(query)
if (querystring.length === 0) {
return pathname
}
// If there's a `?` between the pathname and the querystring already, then
// don't add another one.
if (querystring.startsWith('?') || pathname.endsWith('?')) {
return `${pathname}${querystring}`
}
return `${pathname}?${querystring}`
}
export function renderViaAPI(app, pathname, query) {
const url = `${pathname}${query ? `?${qs.stringify(query)}` : ''}`
const url = query ? withQuery(pathname, query) : pathname
return app.renderToHTML({ url }, {}, pathname, query)
}
......@@ -130,14 +152,12 @@ export function renderViaHTTP(appPort, pathname, query, opts) {
/**
* @param {string | number} appPort
* @param {string} pathname
* @param {Record<string, any> | string | undefined} [query]
* @param {Record<string, any> | string | null | undefined} [query]
* @param {import('node-fetch').RequestInit} [opts]
* @returns {Promise<Response & {buffer: any} & {headers: any}>}
*/
export function fetchViaHTTP(appPort, pathname, query, opts) {
const url = `${pathname}${
typeof query === 'string' ? query : query ? `?${qs.stringify(query)}` : ''
}`
const url = query ? withQuery(pathname, query) : pathname
return fetch(getFullUrl(appPort, url), {
// in node.js v17 fetch favors IPv6 but Next.js is
// listening on IPv4 by default so force IPv4 DNS resolving
......
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