Unverified Commit 8e51c78e authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Add test for AMP in serverless mode (#6894)

* Add amp request header and check for amp
query in serverless mode

* Add serverless test for an AMP page

* Update to handle querystring weirdness

* Update serverless test config
parent 1d45d84f
...@@ -266,19 +266,13 @@ export default class Server { ...@@ -266,19 +266,13 @@ export default class Server {
return this.handleRequest(req, res, parsedUrl) return this.handleRequest(req, res, parsedUrl)
} }
const isDataRequest = ENDING_IN_JSON_REGEX.test(pathname)
if (isDataRequest) {
pathname = pathname.replace(ENDING_IN_JSON_REGEX, '')
}
if (isBlockedPage(pathname)) { if (isBlockedPage(pathname)) {
return this.render404(req, res, parsedUrl) return this.render404(req, res, parsedUrl)
} }
const html = await this.renderToHTML(req, res, pathname, query, { const html = await this.renderToHTML(req, res, pathname, query, {
amphtml: query.amp && this.nextConfig.experimental.amp, amphtml: query.amp && this.nextConfig.experimental.amp,
dataOnly: isDataRequest, dataOnly: req.headers && (req.headers.accept || '').indexOf('application/amp.bind+json') !== -1,
}) })
// Request was ended by the user // Request was ended by the user
if (html === null) { if (html === null) {
......
...@@ -43,6 +43,7 @@ export function createEntrypoints(pages: PagesMapping, target: 'server'|'serverl ...@@ -43,6 +43,7 @@ export function createEntrypoints(pages: PagesMapping, target: 'server'|'serverl
distDir: DOT_NEXT_ALIAS, distDir: DOT_NEXT_ALIAS,
assetPrefix: config.assetPrefix, assetPrefix: config.assetPrefix,
generateEtags: config.generateEtags, generateEtags: config.generateEtags,
ampEnabled: config.experimental.amp,
ampBindInitData: config.experimental.ampBindInitData ampBindInitData: config.experimental.ampBindInitData
} }
......
...@@ -11,7 +11,8 @@ export type ServerlessLoaderQuery = { ...@@ -11,7 +11,8 @@ export type ServerlessLoaderQuery = {
absoluteDocumentPath: string, absoluteDocumentPath: string,
absoluteErrorPath: string, absoluteErrorPath: string,
assetPrefix: string, assetPrefix: string,
ampBindInitData: boolean, ampEnabled: boolean | string,
ampBindInitData: boolean | string,
generateEtags: string generateEtags: string
} }
...@@ -21,6 +22,7 @@ const nextServerlessLoader: loader.Loader = function () { ...@@ -21,6 +22,7 @@ const nextServerlessLoader: loader.Loader = function () {
absolutePagePath, absolutePagePath,
page, page,
assetPrefix, assetPrefix,
ampEnabled,
ampBindInitData, ampBindInitData,
absoluteAppPath, absoluteAppPath,
absoluteDocumentPath, absoluteDocumentPath,
...@@ -47,19 +49,19 @@ const nextServerlessLoader: loader.Loader = function () { ...@@ -47,19 +49,19 @@ const nextServerlessLoader: loader.Loader = function () {
reactLoadableManifest, reactLoadableManifest,
buildId: "__NEXT_REPLACE__BUILD_ID__", buildId: "__NEXT_REPLACE__BUILD_ID__",
assetPrefix: "${assetPrefix}", assetPrefix: "${assetPrefix}",
ampBindInitData: ${Boolean(ampBindInitData)} ampEnabled: ${ampEnabled === true || ampEnabled === 'true'},
ampBindInitData: ${ampBindInitData === true || ampBindInitData === 'true'}
} }
const parsedUrl = parse(req.url, true) const parsedUrl = parse(req.url, true)
const isDataRequest = (
options.ampBindInitData &&
parsedUrl.pathname.endsWith('.json')
)
try { try {
${page === '/_error' ? `res.statusCode = 404` : ''} ${page === '/_error' ? `res.statusCode = 404` : ''}
const result = await renderToHTML(req, res, "${page}", parsedUrl.query, Object.assign( const result = await renderToHTML(req, res, "${page}", parsedUrl.query, Object.assign(
{}, {
Component,
amphtml: options.ampEnabled && (parsedUrl.query.amp || ${page.endsWith('.amp')}),
dataOnly: req.headers && (req.headers.accept || '').indexOf('application/amp.bind+json') !== -1,
},
options, options,
{ Component, dataOnly: isDataRequest }
)) ))
return result return result
} catch (err) { } catch (err) {
......
...@@ -33,7 +33,11 @@ export function createHook(fetcher: (...args: Args[]) => Promise<any>, options: ...@@ -33,7 +33,11 @@ export function createHook(fetcher: (...args: Args[]) => Promise<any>, options:
// @ts-ignore webpack optimization // @ts-ignore webpack optimization
if (process.browser) { if (process.browser) {
const res = fetch(router.route === '/' ? 'index.json' : router.route + '.json?' + stringify(router.query)).then((res: any) => res.json()).then((result: any) => { const res = fetch(router.route + '?' + stringify(router.query), {
headers: {
accept: 'application/amp.bind+json',
},
}).then((res: any) => res.json()).then((result: any) => {
dataManager.overwrite(result) dataManager.overwrite(result)
}) })
throw res throw res
......
...@@ -6,6 +6,7 @@ import { ...@@ -6,6 +6,7 @@ import {
killApp, killApp,
findPort, findPort,
launchApp, launchApp,
fetchViaHTTP,
renderViaHTTP renderViaHTTP
} from 'next-test-utils' } from 'next-test-utils'
...@@ -21,8 +22,13 @@ describe('AMP Bind Initial Data', () => { ...@@ -21,8 +22,13 @@ describe('AMP Bind Initial Data', () => {
}) })
afterAll(() => killApp(server)) afterAll(() => killApp(server))
it('responds with json with .json extension on page', async () => { it('responds with json with accept header on page', async () => {
const data = await renderViaHTTP(appPort, '/index.json') const data = await fetchViaHTTP(appPort, '/', null, {
headers: {
accept: 'application/amp.bind+json'
}
}).then(res => res.ok && res.text())
let isJSON = false let isJSON = false
try { try {
JSON.parse(data) JSON.parse(data)
......
...@@ -4,5 +4,8 @@ module.exports = { ...@@ -4,5 +4,8 @@ module.exports = {
// Make sure entries are not getting disposed. // Make sure entries are not getting disposed.
maxInactiveAge: 1000 * 60 * 60 maxInactiveAge: 1000 * 60 * 60
}, },
experimental: {
amp: true
},
lambdas: true lambdas: true
} }
export default () => `Hi Im an AMP page!`
...@@ -22,6 +22,9 @@ module.exports = function start (port = 0) { ...@@ -22,6 +22,9 @@ module.exports = function start (port = 0) {
app.get('/dynamic-two', (req, res) => { app.get('/dynamic-two', (req, res) => {
require('./.next/serverless/pages/dynamic-two.js').render(req, res) require('./.next/serverless/pages/dynamic-two.js').render(req, res)
}) })
app.get('/amp', (req, res) => {
require('./.next/serverless/pages/some.amp.js').render(req, res)
})
app.get('/404', (req, res) => { app.get('/404', (req, res) => {
require('./.next/serverless/pages/_error.js').render(req, res) require('./.next/serverless/pages/_error.js').render(req, res)
}) })
......
...@@ -44,6 +44,12 @@ describe('Serverless', () => { ...@@ -44,6 +44,12 @@ describe('Serverless', () => {
expect(html).toMatch(/This page could not be found/) expect(html).toMatch(/This page could not be found/)
}) })
it('should render an AMP page', async () => {
const html = await renderViaHTTP(appPort, '/amp')
expect(html).toMatch(/Hi Im an AMP page/)
expect(html).toMatch(/ampproject\.org/)
})
it('should render correctly when importing isomorphic-unfetch', async () => { it('should render correctly when importing isomorphic-unfetch', async () => {
const url = `http://localhost:${appPort}/fetch` const url = `http://localhost:${appPort}/fetch`
const res = await fetch(url) const res = await fetch(url)
......
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