chore(examples/draft-preview): migrates to 2.0 (#3505)

This commit is contained in:
Jacob Fletcher
2023-10-09 14:00:23 -04:00
committed by GitHub
parent 61ea5becbb
commit 2de36550ae
25 changed files with 2066 additions and 1681 deletions

View File

@@ -1,3 +1,3 @@
NEXT_PUBLIC_CMS_URL=http://localhost:3000 NEXT_PUBLIC_PAYLOAD_URL=http://localhost:3000
NEXT_PRIVATE_DRAFT_SECRET=EXAMPLE_DRAFT_SECRET NEXT_PRIVATE_DRAFT_SECRET=EXAMPLE_DRAFT_SECRET
NEXT_PRIVATE_REVALIDATION_KEY=EXAMPLE_REVALIDATION_KEY NEXT_PRIVATE_REVALIDATION_KEY=EXAMPLE_REVALIDATION_KEY

View File

@@ -16,7 +16,7 @@ export const fetchPage = async (
const pageRes: { const pageRes: {
docs: Page[] docs: Page[]
} = await fetch( } = await fetch(
`${process.env.NEXT_PUBLIC_CMS_URL}/api/pages?where[slug][equals]=${slug}${ `${process.env.NEXT_PUBLIC_PAYLOAD_URL}/api/pages?where[slug][equals]=${slug}${
draft && payloadToken ? '&draft=true' : '' draft && payloadToken ? '&draft=true' : ''
}`, }`,
{ {

View File

@@ -3,7 +3,7 @@ import type { Page } from '../../payload-types'
export const fetchPages = async (): Promise<Page[]> => { export const fetchPages = async (): Promise<Page[]> => {
const pageRes: { const pageRes: {
docs: Page[] docs: Page[]
} = await fetch(`${process.env.NEXT_PUBLIC_CMS_URL}/api/pages?depth=0&limit=100`).then(res => } = await fetch(`${process.env.NEXT_PUBLIC_PAYLOAD_URL}/api/pages?depth=0&limit=100`).then(res =>
res.json(), res.json(),
) // eslint-disable-line function-paren-newline ) // eslint-disable-line function-paren-newline

View File

@@ -18,7 +18,7 @@ export const AdminBarClient: React.FC<PayloadAdminBarProps> = props => {
<PayloadAdminBar <PayloadAdminBar
{...props} {...props}
logo={<Title />} logo={<Title />}
cmsURL={process.env.NEXT_PUBLIC_CMS_URL} cmsURL={process.env.NEXT_PUBLIC_PAYLOAD_URL}
onPreviewExit={async () => { onPreviewExit={async () => {
await fetch(`/api/exit-preview`) await fetch(`/api/exit-preview`)
window.location.reload() window.location.reload()

View File

@@ -10,7 +10,7 @@ import classes from './index.module.scss'
export async function Header() { export async function Header() {
const mainMenu: MainMenu = await fetch( const mainMenu: MainMenu = await fetch(
`${process.env.NEXT_PUBLIC_CMS_URL}/api/globals/main-menu`, `${process.env.NEXT_PUBLIC_PAYLOAD_URL}/api/globals/main-menu`,
).then(res => res.json()) ).then(res => res.json())
const { navItems } = mainMenu const { navItems } = mainMenu

View File

@@ -24,7 +24,7 @@ export async function GET(
} }
// validate the Payload token // validate the Payload token
const userReq = await fetch(`${process.env.NEXT_PUBLIC_CMS_URL}/api/users/me`, { const userReq = await fetch(`${process.env.NEXT_PUBLIC_PAYLOAD_URL}/api/users/me`, {
headers: { headers: {
Authorization: `JWT ${payloadToken}`, Authorization: `JWT ${payloadToken}`,
}, },

View File

@@ -8,52 +8,94 @@
export interface Config { export interface Config {
collections: { collections: {
pages: Page; pages: Page
users: User; users: User
}; 'payload-preferences': PayloadPreference
'payload-migrations': PayloadMigration
}
globals: { globals: {
'main-menu': MainMenu; 'main-menu': MainMenu
}; }
} }
export interface Page { export interface Page {
id: string; id: string
title: string; title: string
slug?: string; slug?: string
richText: { richText: {
[k: string]: unknown; [k: string]: unknown
}[]; }[]
updatedAt: string; updatedAt: string
createdAt: string; createdAt: string
_status?: 'draft' | 'published'; _status?: 'draft' | 'published'
} }
export interface User { export interface User {
id: string; id: string
updatedAt: string; updatedAt: string
createdAt: string; createdAt: string
email: string; email: string
resetPasswordToken?: string; resetPasswordToken?: string
resetPasswordExpiration?: string; resetPasswordExpiration?: string
salt?: string; salt?: string
hash?: string; hash?: string
loginAttempts?: number; loginAttempts?: number
lockUntil?: string; lockUntil?: string
password?: string; password?: string
}
export interface PayloadPreference {
id: string
user: {
relationTo: 'users'
value: string | User
}
key?: string
value?:
| {
[k: string]: unknown
}
| unknown[]
| string
| number
| boolean
| null
updatedAt: string
createdAt: string
}
export interface PayloadMigration {
id: string
name?: string
batch?: number
updatedAt: string
createdAt: string
} }
export interface MainMenu { export interface MainMenu {
id: string; id: string
navItems?: { navItems?: {
link: { link: {
type?: 'reference' | 'custom'; type?: 'reference' | 'custom'
newTab?: boolean; newTab?: boolean
reference: { reference: {
value: string | Page; relationTo: 'pages'
relationTo: 'pages'; value: string | Page
}; }
url: string; url: string
label: string; label: string
}; }
id?: string; id?: string
}[]; }[]
updatedAt?: string; updatedAt?: string
createdAt?: string; createdAt?: string
}
declare module 'payload' {
export interface GeneratedTypes {
collections: {
pages: Page
users: User
'payload-preferences': PayloadPreference
'payload-migrations': PayloadMigration
}
globals: {
'main-menu': MainMenu
}
}
} }

View File

@@ -1,2 +1,2 @@
NEXT_PUBLIC_CMS_URL=http://localhost:3000 NEXT_PUBLIC_PAYLOAD_URL=http://localhost:3000
NEXT_PRIVATE_REVALIDATION_KEY=EXAMPLE_REVALIDATION_KEY NEXT_PRIVATE_REVALIDATION_KEY=EXAMPLE_REVALIDATION_KEY

View File

@@ -20,7 +20,7 @@ export const AdminBar: React.FC<{
<PayloadAdminBar <PayloadAdminBar
{...adminBarProps} {...adminBarProps}
logo={<Title />} logo={<Title />}
cmsURL={process.env.NEXT_PUBLIC_CMS_URL} cmsURL={process.env.NEXT_PUBLIC_PAYLOAD_URL}
onAuthChange={setUser} onAuthChange={setUser}
className={classes.payloadAdminBar} className={classes.payloadAdminBar}
classNames={{ classNames={{

View File

@@ -7,7 +7,7 @@ import { Gutter } from '../components/Gutter'
import RichText from '../components/RichText' import RichText from '../components/RichText'
import type { MainMenu, Page as PageType } from '../payload-types' import type { MainMenu, Page as PageType } from '../payload-types'
import classes from './[slug].module.scss'; import classes from './[slug].module.scss'
const Page: React.FC< const Page: React.FC<
PageType & { PageType & {
@@ -67,7 +67,7 @@ export const getStaticProps: GetStaticProps = async (context: GetStaticPropsCont
) )
// when previewing, send the payload token to bypass draft access control // when previewing, send the payload token to bypass draft access control
const pageReq = await fetch(`${process.env.NEXT_PUBLIC_CMS_URL}/api/pages${searchParams}`, { const pageReq = await fetch(`${process.env.NEXT_PUBLIC_PAYLOAD_URL}/api/pages${searchParams}`, {
headers: { headers: {
...(preview ...(preview
? { ? {
@@ -110,7 +110,7 @@ export const getStaticPaths: GetStaticPaths = async () => {
let paths: Paths = [] let paths: Paths = []
const pagesReq = await fetch( const pagesReq = await fetch(
`${process.env.NEXT_PUBLIC_CMS_URL}/api/pages?where[_status][equals]=published&depth=0&limit=300`, `${process.env.NEXT_PUBLIC_PAYLOAD_URL}/api/pages?where[_status][equals]=published&depth=0&limit=300`,
) )
const pagesData = await pagesReq.json() const pagesData = await pagesReq.json()

View File

@@ -13,7 +13,7 @@ export interface IGlobals {
} }
export const getAllGlobals = async (): Promise<IGlobals> => { export const getAllGlobals = async (): Promise<IGlobals> => {
const res = await fetch(`${process.env.NEXT_PUBLIC_CMS_URL}/api/globals/main-menu?depth=1`) const res = await fetch(`${process.env.NEXT_PUBLIC_PAYLOAD_URL}/api/globals/main-menu?depth=1`)
const mainMenu = await res.json() const mainMenu = await res.json()
return { return {

View File

@@ -20,7 +20,7 @@ const preview = async (req: NextApiRequest, res: NextApiResponse): Promise<void>
} }
// validate the Payload token // validate the Payload token
const userReq = await fetch(`${process.env.NEXT_PUBLIC_CMS_URL}/api/users/me`, { const userReq = await fetch(`${process.env.NEXT_PUBLIC_PAYLOAD_URL}/api/users/me`, {
headers: { headers: {
Authorization: `JWT ${payloadToken}`, Authorization: `JWT ${payloadToken}`,
}, },

View File

@@ -8,52 +8,94 @@
export interface Config { export interface Config {
collections: { collections: {
pages: Page; pages: Page
users: User; users: User
}; 'payload-preferences': PayloadPreference
'payload-migrations': PayloadMigration
}
globals: { globals: {
'main-menu': MainMenu; 'main-menu': MainMenu
}; }
} }
export interface Page { export interface Page {
id: string; id: string
title: string; title: string
slug?: string; slug?: string
richText: { richText: {
[k: string]: unknown; [k: string]: unknown
}[]; }[]
updatedAt: string; updatedAt: string
createdAt: string; createdAt: string
_status?: 'draft' | 'published'; _status?: 'draft' | 'published'
} }
export interface User { export interface User {
id: string; id: string
updatedAt: string; updatedAt: string
createdAt: string; createdAt: string
email: string; email: string
resetPasswordToken?: string; resetPasswordToken?: string
resetPasswordExpiration?: string; resetPasswordExpiration?: string
salt?: string; salt?: string
hash?: string; hash?: string
loginAttempts?: number; loginAttempts?: number
lockUntil?: string; lockUntil?: string
password?: string; password?: string
}
export interface PayloadPreference {
id: string
user: {
relationTo: 'users'
value: string | User
}
key?: string
value?:
| {
[k: string]: unknown
}
| unknown[]
| string
| number
| boolean
| null
updatedAt: string
createdAt: string
}
export interface PayloadMigration {
id: string
name?: string
batch?: number
updatedAt: string
createdAt: string
} }
export interface MainMenu { export interface MainMenu {
id: string; id: string
navItems?: { navItems?: {
link: { link: {
type?: 'reference' | 'custom'; type?: 'reference' | 'custom'
newTab?: boolean; newTab?: boolean
reference: { reference: {
value: string | Page; relationTo: 'pages'
relationTo: 'pages'; value: string | Page
}; }
url: string; url: string
label: string; label: string
}; }
id?: string; id?: string
}[]; }[]
updatedAt?: string; updatedAt?: string
createdAt?: string; createdAt?: string
}
declare module 'payload' {
export interface GeneratedTypes {
collections: {
pages: Page
users: User
'payload-preferences': PayloadPreference
'payload-migrations': PayloadMigration
}
globals: {
'main-menu': MainMenu
}
}
} }

View File

@@ -1,4 +1,4 @@
MONGODB_URI=mongodb://127.0.0.1/payload-example-draft-preview DATABASE_URI=mongodb://127.0.0.1/payload-example-draft-preview
PAYLOAD_SECRET=ENTER-STRING-HERE PAYLOAD_SECRET=ENTER-STRING-HERE
PAYLOAD_PUBLIC_SERVER_URL=http://localhost:3000 PAYLOAD_PUBLIC_SERVER_URL=http://localhost:3000
PAYLOAD_PUBLIC_SITE_URL=http://localhost:3001 PAYLOAD_PUBLIC_SITE_URL=http://localhost:3001

View File

@@ -42,7 +42,7 @@ See the [Collections](https://payloadcms.com/docs/configuration/collections) doc
const searchParams = `?where[slug][equals]=${pageSlug}&depth=1${preview ? `&draft=true` : ''}` const searchParams = `?where[slug][equals]=${pageSlug}&depth=1${preview ? `&draft=true` : ''}`
// when previewing, send the payload token to bypass draft access control // when previewing, send the payload token to bypass draft access control
const pageReq = await fetch(`${process.env.NEXT_PUBLIC_CMS_URL}/api/pages${searchParams}`, { const pageReq = await fetch(`${process.env.NEXT_PUBLIC_PAYLOAD_URL}/api/pages${searchParams}`, {
headers: { headers: {
...preview ? { ...preview ? {
Authorization: `JWT ${payloadToken}`, Authorization: `JWT ${payloadToken}`,

View File

@@ -18,6 +18,9 @@
"lint:fix": "eslint --fix --ext .ts,.tsx src" "lint:fix": "eslint --fix --ext .ts,.tsx src"
}, },
"dependencies": { "dependencies": {
"@payloadcms/bundler-webpack": "^1.0.0-beta.5",
"@payloadcms/db-mongodb": "^1.0.0-beta.8",
"@payloadcms/richtext-slate": "^1.0.0-beta.4",
"dotenv": "^8.2.0", "dotenv": "^8.2.0",
"express": "^4.17.1", "express": "^4.17.1",
"payload": "latest" "payload": "latest"

View File

@@ -1,5 +1,5 @@
import type { RichTextElement } from 'payload/dist/fields/config/types' import type { RichTextElement } from '@payloadcms/richtext-slate'
const elements: RichTextElement[] = ['blockquote', 'h2', 'h3', 'h4', 'h5', 'h6', 'link'] const elements: RichTextElement[] = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'blockquote', 'link']
export default elements export default elements

View File

@@ -1,4 +1,6 @@
import type { RichTextElement, RichTextField, RichTextLeaf } from 'payload/dist/fields/config/types' import { slateEditor } from '@payloadcms/richtext-slate'
import type { RichTextElement, RichTextLeaf } from '@payloadcms/richtext-slate/dist/types'
import type { RichTextField } from 'payload/types'
import deepMerge from '../../utilities/deepMerge' import deepMerge from '../../utilities/deepMerge'
import link from '../link' import link from '../link'
@@ -25,60 +27,64 @@ const richText: RichText = (
name: 'richText', name: 'richText',
type: 'richText', type: 'richText',
required: true, required: true,
admin: { editor: slateEditor({
upload: { admin: {
collections: { upload: {
media: { collections: {
fields: [ media: {
{ fields: [
type: 'richText', {
name: 'caption', type: 'richText',
label: 'Caption', name: 'caption',
admin: { label: 'Caption',
elements: [...elements], editor: slateEditor({
leaves: [...leaves], admin: {
elements: [...elements],
leaves: [...leaves],
},
}),
}, },
}, {
{ type: 'radio',
type: 'radio', name: 'alignment',
name: 'alignment', label: 'Alignment',
label: 'Alignment', options: [
options: [ {
{ label: 'Left',
label: 'Left', value: 'left',
value: 'left', },
}, {
{ label: 'Center',
label: 'Center', value: 'center',
value: 'center', },
}, {
{ label: 'Right',
label: 'Right', value: 'right',
value: 'right', },
}, ],
],
},
{
name: 'enableLink',
type: 'checkbox',
label: 'Enable Link',
},
link({
appearances: false,
disableLabel: true,
overrides: {
admin: {
condition: (_, data) => Boolean(data?.enableLink),
},
}, },
}), {
], name: 'enableLink',
type: 'checkbox',
label: 'Enable Link',
},
link({
appearances: false,
disableLabel: true,
overrides: {
admin: {
condition: (_, data) => Boolean(data?.enableLink),
},
},
}),
],
},
}, },
}, },
elements: [...elements, ...(additions.elements || [])],
leaves: [...leaves, ...(additions.leaves || [])],
}, },
elements: [...elements, ...(additions.elements || [])], }),
leaves: [...leaves, ...(additions.leaves || [])],
},
}, },
overrides, overrides,
) )

View File

@@ -1,4 +1,4 @@
import type { RichTextLeaf } from 'payload/dist/fields/config/types' import { RichTextLeaf } from '@payloadcms/richtext-slate'
const defaultLeaves: RichTextLeaf[] = ['bold', 'italic', 'underline'] const defaultLeaves: RichTextLeaf[] = ['bold', 'italic', 'underline']

View File

@@ -8,52 +8,94 @@
export interface Config { export interface Config {
collections: { collections: {
pages: Page; pages: Page
users: User; users: User
}; 'payload-preferences': PayloadPreference
'payload-migrations': PayloadMigration
}
globals: { globals: {
'main-menu': MainMenu; 'main-menu': MainMenu
}; }
} }
export interface Page { export interface Page {
id: string; id: string
title: string; title: string
slug?: string; slug?: string
richText: { richText: {
[k: string]: unknown; [k: string]: unknown
}[]; }[]
updatedAt: string; updatedAt: string
createdAt: string; createdAt: string
_status?: 'draft' | 'published'; _status?: 'draft' | 'published'
} }
export interface User { export interface User {
id: string; id: string
updatedAt: string; updatedAt: string
createdAt: string; createdAt: string
email: string; email: string
resetPasswordToken?: string; resetPasswordToken?: string
resetPasswordExpiration?: string; resetPasswordExpiration?: string
salt?: string; salt?: string
hash?: string; hash?: string
loginAttempts?: number; loginAttempts?: number
lockUntil?: string; lockUntil?: string
password?: string; password?: string
}
export interface PayloadPreference {
id: string
user: {
relationTo: 'users'
value: string | User
}
key?: string
value?:
| {
[k: string]: unknown
}
| unknown[]
| string
| number
| boolean
| null
updatedAt: string
createdAt: string
}
export interface PayloadMigration {
id: string
name?: string
batch?: number
updatedAt: string
createdAt: string
} }
export interface MainMenu { export interface MainMenu {
id: string; id: string
navItems?: { navItems?: {
link: { link: {
type?: 'reference' | 'custom'; type?: 'reference' | 'custom'
newTab?: boolean; newTab?: boolean
reference: { reference: {
value: string | Page; relationTo: 'pages'
relationTo: 'pages'; value: string | Page
}; }
url: string; url: string
label: string; label: string
}; }
id?: string; id?: string
}[]; }[]
updatedAt?: string; updatedAt?: string
createdAt?: string; createdAt?: string
}
declare module 'payload' {
export interface GeneratedTypes {
collections: {
pages: Page
users: User
'payload-preferences': PayloadPreference
'payload-migrations': PayloadMigration
}
globals: {
'main-menu': MainMenu
}
}
} }

View File

@@ -1,3 +1,6 @@
import { webpackBundler } from '@payloadcms/bundler-webpack'
import { mongooseAdapter } from '@payloadcms/db-mongodb'
import { slateEditor } from '@payloadcms/richtext-slate'
import path from 'path' import path from 'path'
import { buildConfig } from 'payload/config' import { buildConfig } from 'payload/config'
@@ -9,10 +12,15 @@ import { MainMenu } from './globals/MainMenu'
export default buildConfig({ export default buildConfig({
collections: [Pages, Users], collections: [Pages, Users],
admin: { admin: {
bundler: webpackBundler(),
components: { components: {
beforeLogin: [BeforeLogin], beforeLogin: [BeforeLogin],
}, },
}, },
editor: slateEditor({}),
db: mongooseAdapter({
url: process.env.DATABASE_URI,
}),
serverURL: process.env.PAYLOAD_PUBLIC_SERVER_URL, serverURL: process.env.PAYLOAD_PUBLIC_SERVER_URL,
cors: [ cors: [
process.env.PAYLOAD_PUBLIC_SERVER_URL || '', process.env.PAYLOAD_PUBLIC_SERVER_URL || '',

View File

@@ -1,7 +1,7 @@
import type { Page } from '../payload-types' import type { Page } from '../payload-types'
export const examplePage: Partial<Page> = { export const examplePage: Partial<Page> = {
title: 'Example Page', title: 'Example Page (Published)',
slug: 'example-page', slug: 'example-page',
_status: 'published', _status: 'published',
richText: [ richText: [

View File

@@ -19,7 +19,6 @@ app.get('/', (_, res) => {
const start = async (): Promise<void> => { const start = async (): Promise<void> => {
await payload.init({ await payload.init({
secret: process.env.PAYLOAD_SECRET, secret: process.env.PAYLOAD_SECRET,
mongoURL: process.env.MONGODB_URI,
express: app, express: app,
onInit: () => { onInit: () => {
payload.logger.info(`Payload Admin URL: ${payload.getAdminURL()}`) payload.logger.info(`Payload Admin URL: ${payload.getAdminURL()}`)

View File

@@ -16,7 +16,6 @@
"sourceMap": true, "sourceMap": true,
"resolveJsonModule": true, "resolveJsonModule": true,
"paths": { "paths": {
"payload/generated-types": ["./src/payload-types.ts"],
"node_modules/*": ["./node_modules/*"] "node_modules/*": ["./node_modules/*"]
}, },
}, },

File diff suppressed because it is too large Load Diff