Skip to content

Commit

Permalink
chore(next): cleans up initPage through initReq overrides and consoli…
Browse files Browse the repository at this point in the history
…dated return types (#10449)

The `req` object returned from `initReq` does not include the `user`
property, and instead returned `user` and `i18n` _alongside_ the req
(and in the case of `i18n`, duplicately, as it was _also_ on the req).
Now, these properties exist directly on the req itself as expected. The
`initPage` function was also unnecessary instantiating a new local req
object just to override the `headers`, `url`, and `query` properties.
Instead of doing this, we now support overriding properties upon
instantiating a new req, bypassing the need to create an entirely new
object.
  • Loading branch information
jacobsfletch authored Jan 11, 2025
1 parent d20dc58 commit c850bd4
Show file tree
Hide file tree
Showing 4 changed files with 37 additions and 48 deletions.
18 changes: 8 additions & 10 deletions packages/next/src/layouts/Root/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ export const RootLayout = async ({

const payload = await getPayload({ config, importMap })

const { i18n, permissions, req, user } = await initReq(config)
const { permissions, req } = await initReq(config)

const dir = (rtlLanguages as unknown as AcceptedLanguages[]).includes(languageCode)
? 'RTL'
Expand Down Expand Up @@ -84,16 +84,14 @@ export const RootLayout = async ({
})
}

const navPrefs = await getNavPrefs({ payload, user })
const navPrefs = await getNavPrefs({ payload, user: req.user })

const clientConfig = getClientConfig({
config,
i18n,
i18n: req.i18n,
importMap,
})

req.user = user

const locale = await getRequestLocale({
req,
})
Expand All @@ -111,7 +109,7 @@ export const RootLayout = async ({
<body>
<RootProvider
config={clientConfig}
dateFNSKey={i18n.dateFNSKey}
dateFNSKey={req.i18n.dateFNSKey}
fallbackLang={config.i18n.fallbackLanguage}
isNavOpen={navPrefs?.open ?? true}
languageCode={languageCode}
Expand All @@ -121,19 +119,19 @@ export const RootLayout = async ({
serverFunction={serverFunction}
switchLanguageServerAction={switchLanguageServerAction}
theme={theme}
translations={i18n.translations}
user={user}
translations={req.i18n.translations}
user={req.user}
>
{Array.isArray(config.admin?.components?.providers) &&
config.admin?.components?.providers.length > 0 ? (
<NestProviders
importMap={payload.importMap}
providers={config.admin?.components?.providers}
serverProps={{
i18n,
i18n: req.i18n,
payload,
permissions,
user,
user: req.user,
}}
>
{children}
Expand Down
49 changes: 19 additions & 30 deletions packages/next/src/utilities/initPage/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import type { I18n } from '@payloadcms/translations'
import type { InitPageResult, VisibleEntities } from 'payload'

import { headers as getHeaders } from 'next/headers.js'
import { notFound } from 'next/navigation.js'
import { createLocalReq, getPayload, isEntityHidden, parseCookies } from 'payload'
import { getPayload, isEntityHidden, parseCookies } from 'payload'
import * as qs from 'qs-esm'

import type { Args } from './types.js'
Expand Down Expand Up @@ -33,29 +32,17 @@ export const initPage = async ({

const cookies = parseCookies(headers)

const { i18n, permissions, user } = await initReq(payload.config)

// Ideally, we should not need to recreate the req, because
// we can get it from the above initReq.

// We just need to -overwrite- the url and query of the req
// we get above. Clone the req? We'll look into that eventually.
const req = await createLocalReq(
{
fallbackLocale: false,
req: {
headers,
host: headers.get('host'),
i18n: i18n as I18n,
query: qs.parse(queryString, {
depth: 10,
ignoreQueryPrefix: true,
}),
url: `${payload.config.serverURL}${route}${searchParams ? queryString : ''}`,
},
const { permissions, req } = await initReq(payload.config, {
fallbackLocale: false,
req: {
headers,
query: qs.parse(queryString, {
depth: 10,
ignoreQueryPrefix: true,
}),
url: `${payload.config.serverURL}${route}${searchParams ? queryString : ''}`,
},
payload,
)
})

const languageOptions = Object.entries(payload.config.i18n.supportedLanguages || {}).reduce(
(acc, [language, languageConfig]) => {
Expand All @@ -71,8 +58,6 @@ export const initPage = async ({
[],
)

req.user = user

const locale = await getRequestLocale({
req,
})
Expand All @@ -81,10 +66,14 @@ export const initPage = async ({

const visibleEntities: VisibleEntities = {
collections: collections
.map(({ slug, admin: { hidden } }) => (!isEntityHidden({ hidden, user }) ? slug : null))
.map(({ slug, admin: { hidden } }) =>
!isEntityHidden({ hidden, user: req.user }) ? slug : null,
)
.filter(Boolean),
globals: globals
.map(({ slug, admin: { hidden } }) => (!isEntityHidden({ hidden, user }) ? slug : null))
.map(({ slug, admin: { hidden } }) =>
!isEntityHidden({ hidden, user: req.user }) ? slug : null,
)
.filter(Boolean),
}

Expand All @@ -99,7 +88,7 @@ export const initPage = async ({
config: payload.config,
route,
searchParams,
user,
user: req.user,
})
}

Expand All @@ -125,7 +114,7 @@ export const initPage = async ({
permissions,
redirectTo,
req,
translations: i18n.translations,
translations: req.i18n.translations,
visibleEntities,
}
}
16 changes: 9 additions & 7 deletions packages/next/src/utilities/initReq.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,19 @@
import type { I18n, I18nClient } from '@payloadcms/translations'
import type { PayloadRequest, SanitizedConfig, SanitizedPermissions, User } from 'payload'
import type { PayloadRequest, SanitizedConfig, SanitizedPermissions } from 'payload'

import { initI18n } from '@payloadcms/translations'
import { headers as getHeaders } from 'next/headers.js'
import { createLocalReq, getPayload, getRequestLanguage, parseCookies } from 'payload'
import { cache } from 'react'

type Result = {
i18n: I18nClient
permissions: SanitizedPermissions
req: PayloadRequest
user: User
}

export const initReq = cache(async function (
configPromise: Promise<SanitizedConfig> | SanitizedConfig,
overrides?: Parameters<typeof createLocalReq>[0],
): Promise<Result> {
const config = await configPromise
const payload = await getPayload({ config })
Expand All @@ -34,24 +33,27 @@ export const initReq = cache(async function (
language: languageCode,
})

const { permissions, user } = await payload.auth({ headers })

const { req: reqOverrides, ...optionsOverrides } = overrides || {}

const req = await createLocalReq(
{
req: {
headers,
host: headers.get('host'),
i18n: i18n as I18n,
url: `${payload.config.serverURL}`,
user,
...(reqOverrides || {}),
},
...(optionsOverrides || {}),
},
payload,
)

const { permissions, user } = await payload.auth({ headers, req })

return {
i18n,
permissions,
req,
user,
}
})
2 changes: 1 addition & 1 deletion tsconfig.base.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
}
],
"paths": {
"@payload-config": ["./test/localization/config.ts"],
"@payload-config": ["./test/_community/config.ts"],
"@payloadcms/live-preview": ["./packages/live-preview/src"],
"@payloadcms/live-preview-react": ["./packages/live-preview-react/src/index.ts"],
"@payloadcms/live-preview-vue": ["./packages/live-preview-vue/src/index.ts"],
Expand Down

0 comments on commit c850bd4

Please sign in to comment.