Skip to content

Commit

Permalink
Base Http for BaseServer (#32999)
Browse files Browse the repository at this point in the history
Adds base http classes, along with Node + Web (partial) implementations
Removes usage of IncomingMessage and ServerResponse from base server

Co-authored-by: Shu Ding <3676859+shuding@users.noreply.github.com>
  • Loading branch information
karaggeorge and shuding committed Jan 14, 2022
1 parent 89b8d58 commit 3e00a81
Show file tree
Hide file tree
Showing 13 changed files with 866 additions and 290 deletions.
Expand Up @@ -3,6 +3,7 @@ import { IncomingMessage, ServerResponse } from 'http'
import { apiResolver } from '../../../../server/api-utils'
import { getUtils, vercelHeader, ServerlessHandlerCtx } from './utils'
import { DecodeError } from '../../../../shared/lib/utils'
import { NodeNextResponse, NodeNextRequest } from '../../../../server/base-http'

export function getApiHandler(ctx: ServerlessHandlerCtx) {
const { pageModule, encodedPreviewProps, pageIsDynamic } = ctx
Expand All @@ -13,7 +14,15 @@ export function getApiHandler(ctx: ServerlessHandlerCtx) {
normalizeDynamicRouteParams,
} = getUtils(ctx)

return async (req: IncomingMessage, res: ServerResponse) => {
return async (
rawReq: NodeNextRequest | IncomingMessage,
rawRes: NodeNextResponse | ServerResponse
) => {
const req =
rawReq instanceof IncomingMessage ? new NodeNextRequest(rawReq) : rawReq
const res =
rawRes instanceof ServerResponse ? new NodeNextResponse(rawRes) : rawRes

try {
// We need to trust the dynamic route params from the proxy
// to ensure we are using the correct values
Expand Down Expand Up @@ -41,8 +50,8 @@ export function getApiHandler(ctx: ServerlessHandlerCtx) {
}

await apiResolver(
req,
res,
req.originalRequest,
res.originalResponse,
Object.assign({}, parsedUrl.query, params),
await pageModule,
encodedPreviewProps,
Expand All @@ -53,7 +62,7 @@ export function getApiHandler(ctx: ServerlessHandlerCtx) {

if (err instanceof DecodeError) {
res.statusCode = 400
res.end('Bad Request')
res.body('Bad Request').send()
} else {
// Throw the error to crash the serverless function
throw err
Expand Down
Expand Up @@ -25,6 +25,7 @@ import cookie from 'next/dist/compiled/cookie'
import { TEMPORARY_REDIRECT_STATUS } from '../../../../shared/lib/constants'
import { NextConfig } from '../../../../server/config'
import { addRequestMeta } from '../../../../server/request-meta'
import { BaseNextRequest } from '../../../../server/base-http'

const getCustomRouteMatcher = pathMatch(true)

Expand Down Expand Up @@ -85,7 +86,10 @@ export function getUtils({
defaultRouteMatches = dynamicRouteMatcher(page) as ParsedUrlQuery
}

function handleRewrites(req: IncomingMessage, parsedUrl: UrlWithParsedQuery) {
function handleRewrites(
req: BaseNextRequest | IncomingMessage,
parsedUrl: UrlWithParsedQuery
) {
for (const rewrite of rewrites) {
const matcher = getCustomRouteMatcher(rewrite.source)
let params = matcher(parsedUrl.pathname)
Expand Down Expand Up @@ -150,15 +154,18 @@ export function getUtils({
return parsedUrl
}

function handleBasePath(req: IncomingMessage, parsedUrl: UrlWithParsedQuery) {
function handleBasePath(
req: BaseNextRequest | IncomingMessage,
parsedUrl: UrlWithParsedQuery
) {
// always strip the basePath if configured since it is required
req.url = req.url!.replace(new RegExp(`^${basePath}`), '') || '/'
parsedUrl.pathname =
parsedUrl.pathname!.replace(new RegExp(`^${basePath}`), '') || '/'
}

function getParamsFromRouteMatches(
req: IncomingMessage,
req: BaseNextRequest | IncomingMessage,
renderOpts?: any,
detectedLocale?: string
) {
Expand Down Expand Up @@ -269,7 +276,10 @@ export function getUtils({
return pathname
}

function normalizeVercelUrl(req: IncomingMessage, trustQuery: boolean) {
function normalizeVercelUrl(
req: BaseNextRequest | IncomingMessage,
trustQuery: boolean
) {
// make sure to normalize req.url on Vercel to strip dynamic params
// from the query which are added during routing
if (pageIsDynamic && trustQuery && defaultRouteRegex) {
Expand Down Expand Up @@ -374,7 +384,7 @@ export function getUtils({
if (detectedDomain) {
defaultLocale = detectedDomain.defaultLocale
detectedLocale = defaultLocale
addRequestMeta(req, '__nextIsLocaleDomain', true)
addRequestMeta(req as any, '__nextIsLocaleDomain', true)
}

// if not domain specific locale use accept-language preferred
Expand All @@ -394,7 +404,7 @@ export function getUtils({
...parsedUrl,
pathname: localePathResult.pathname,
})
addRequestMeta(req, '__nextStrippedLocale', true)
addRequestMeta(req as any, '__nextStrippedLocale', true)
parsedUrl.pathname = localePathResult.pathname
}

Expand Down
9 changes: 5 additions & 4 deletions packages/next/server/api-utils.ts
Expand Up @@ -10,6 +10,7 @@ import { sendEtagResponse } from './send-payload'
import generateETag from 'next/dist/compiled/etag'
import isError from '../lib/is-error'
import { interopDefault } from '../lib/interop-default'
import { BaseNextRequest, BaseNextResponse } from './base-http'

export type NextApiRequestCookies = { [key: string]: string }
export type NextApiRequestQuery = { [key: string]: string | string[] }
Expand Down Expand Up @@ -141,7 +142,7 @@ export async function apiResolver(
* @param req request object
*/
export async function parseBody(
req: NextApiRequest,
req: IncomingMessage,
limit: string | number
): Promise<any> {
let contentType
Expand Down Expand Up @@ -335,11 +336,11 @@ const COOKIE_NAME_PRERENDER_BYPASS = `__prerender_bypass`
const COOKIE_NAME_PRERENDER_DATA = `__next_preview_data`

export const SYMBOL_PREVIEW_DATA = Symbol(COOKIE_NAME_PRERENDER_DATA)
const SYMBOL_CLEARED_COOKIES = Symbol(COOKIE_NAME_PRERENDER_BYPASS)
export const SYMBOL_CLEARED_COOKIES = Symbol(COOKIE_NAME_PRERENDER_BYPASS)

export function tryGetPreviewData(
req: IncomingMessage,
res: ServerResponse,
req: IncomingMessage | BaseNextRequest,
res: ServerResponse | BaseNextResponse,
options: __ApiPreviewProps
): PreviewData {
// Read cached preview data if present
Expand Down

0 comments on commit 3e00a81

Please sign in to comment.