Files
payload/test/versions/int.spec.ts
Alessio Gravili 90b7b20699 feat!: beta-next (#7620)
This PR makes three major changes to the codebase:

1. [Component Paths](#component-paths)
Instead of importing custom components into your config directly, they
are now defined as file paths and rendered only when needed. That way
the Payload config will be significantly more lightweight, and ensures
that the Payload config is 100% server-only and Node-safe. Related
discussion: https://github.com/payloadcms/payload/discussions/6938

2. [Client Config](#client-config)
Deprecates the component map by merging its logic into the client
config. The main goal of this change is for performance and
simplification. There was no need to deeply iterate over the Payload
config twice, once for the component map, and another for the client
config. Instead, we can do everything in the client config one time.
This has also dramatically simplified the client side prop drilling
through the UI library. Now, all components can share the same client
config which matches the exact shape of their Payload config (with the
exception of non-serializable props and mapped custom components).

3. [Custom client component are no longer
server-rendered](#custom-client-components-are-no-longer-server-rendered)
Previously, custom components would be server-rendered, no matter if
they are server or client components. Now, only server components are
rendered on the server. Client components are automatically detected,
and simply get passed through as `MappedComponent` to be rendered fully
client-side.

## Component Paths

Instead of importing custom components into your config directly, they
are now defined as file paths and rendered only when needed. That way
the Payload config will be significantly more lightweight, and ensures
that the Payload config is 100% server-only and Node-safe. Related
discussion: https://github.com/payloadcms/payload/discussions/6938

In order to reference any custom components in the Payload config, you
now have to specify a string path to the component instead of importing
it.

Old:

```ts
import { MyComponent2} from './MyComponent2.js'

admin: {
  components: {
    Label: MyComponent2
  },
},
```

New:

```ts
admin: {
  components: {
    Label: '/collections/Posts/MyComponent2.js#MyComponent2', // <= has to be a relative path based on a baseDir configured in the Payload config - NOT relative based on the importing file
  },
},
```

### Local API within Next.js routes

Previously, if you used the Payload Local API within Next.js pages, all
the client-side modules are being added to the bundle for that specific
page, even if you only need server-side functionality.

This `/test` route, which uses the Payload local API, was previously 460
kb. It is now down to 91 kb and does not bundle the Payload client-side
admin panel anymore.

All tests done
[here](https://github.com/payloadcms/payload-3.0-demo/tree/feat/path-test)
with beta.67/PR, db-mongodb and default richtext-lexical:

**dev /admin before:**
![CleanShot 2024-07-29 at 22 49
12@2x](https://github.com/user-attachments/assets/4428e766-b368-4bcf-8c18-d0187ab64f3e)

**dev /admin after:**
![CleanShot 2024-07-29 at 22 50
49@2x](https://github.com/user-attachments/assets/f494c848-7247-4b02-a650-a3fab4000de6)

---

**dev /test before:**
![CleanShot 2024-07-29 at 22 56
18@2x](https://github.com/user-attachments/assets/1a7e9500-b859-4761-bf63-abbcdac6f8d6)

**dev /test after:**
![CleanShot 2024-07-29 at 22 47
45@2x](https://github.com/user-attachments/assets/f89aa76d-f2d5-4572-9753-2267f034a45a)

---

**build before:**
![CleanShot 2024-07-29 at 22 57
14@2x](https://github.com/user-attachments/assets/5f8f7281-2a4a-40a5-a788-c30ddcdd51b5)

**build after::**
![CleanShot 2024-07-29 at 22 56
39@2x](https://github.com/user-attachments/assets/ea8772fd-512f-4db0-9a81-4b014715a1b7)

### Usage of the Payload Local API / config outside of Next.js

This will make it a lot easier to use the Payload config / local API in
other, server-side contexts. Previously, you might encounter errors due
to client files (like .scss files) not being allowed to be imported.

## Client Config

Deprecates the component map by merging its logic into the client
config. The main goal of this change is for performance and
simplification. There was no need to deeply iterate over the Payload
config twice, once for the component map, and another for the client
config. Instead, we can do everything in the client config one time.
This has also dramatically simplified the client side prop drilling
through the UI library. Now, all components can share the same client
config which matches the exact shape of their Payload config (with the
exception of non-serializable props and mapped custom components).

This is breaking change. The `useComponentMap` hook no longer exists,
and most component props have changed (for the better):

```ts
const { componentMap } = useComponentMap() // old
const { config } = useConfig() // new
```

The `useConfig` hook has also changed in shape, `config` is now a
property _within_ the context obj:

```ts
const config = useConfig() // old
const { config } = useConfig() // new
```

## Custom Client Components are no longer server rendered

Previously, custom components would be server-rendered, no matter if
they are server or client components. Now, only server components are
rendered on the server. Client components are automatically detected,
and simply get passed through as `MappedComponent` to be rendered fully
client-side.

The benefit of this change:

Custom client components can now receive props. Previously, the only way
for them to receive dynamic props from a parent client component was to
use hooks, e.g. `useFieldProps()`. Now, we do have the option of passing
in props to the custom components directly, if they are client
components. This will be simpler than having to look for the correct
hook.

This makes rendering them on the client a little bit more complex, as
you now have to check if that component is a server component (=>
already has been rendered) or a client component (=> not rendered yet,
has to be rendered here). However, this added complexity has been
alleviated through the easy-to-use `<RenderMappedComponent />` helper.

This helper now also handles rendering arrays of custom components (e.g.
beforeList, beforeLogin ...), which actually makes rendering custom
components easier in some cases.

## Misc improvements

This PR includes misc, breaking changes. For example, we previously
allowed unions between components and config object for the same
property. E.g. for the custom view property, you were allowed to pass in
a custom component or an object with other properties, alongside a
custom component.

Those union types are now gone. You can now either pass an object, or a
component. The previous `{ View: MyViewComponent}` is now `{ View: {
Component: MyViewComponent} }` or `{ View: { Default: { Component:
MyViewComponent} } }`.

This dramatically simplifies the way we read & process those properties,
especially in buildComponentMap. We can now simply check for the
existence of one specific property, which always has to be a component,
instead of running cursed runtime checks on a shared union property
which could contain a component, but could also contain functions or
objects.

![CleanShot 2024-07-29 at 23 07
07@2x](https://github.com/user-attachments/assets/1e75aa4c-7a4c-419f-9070-216bb7b9a5e5)

![CleanShot 2024-07-29 at 23 09
40@2x](https://github.com/user-attachments/assets/b4c96450-6b7e-496c-a4f7-59126bfd0991)

- [x] I have read and understand the
[CONTRIBUTING.md](https://github.com/payloadcms/payload/blob/main/CONTRIBUTING.md)
document in this repository.

---------

Co-authored-by: PatrikKozak <patrik@payloadcms.com>
Co-authored-by: Paul <paul@payloadcms.com>
Co-authored-by: Paul Popus <paul@nouance.io>
Co-authored-by: Jacob Fletcher <jacobsfletch@gmail.com>
Co-authored-by: James <james@trbl.design>
2024-08-13 12:54:33 -04:00

1549 lines
41 KiB
TypeScript

import type { Payload } from 'payload'
import path from 'path'
import { ValidationError } from 'payload'
import { fileURLToPath } from 'url'
import type { NextRESTClient } from '../helpers/NextRESTClient.js'
import { devUser } from '../credentials.js'
import { initPayloadInt } from '../helpers/initPayloadInt.js'
import { clearAndSeedEverything } from './clearAndSeedEverything.js'
import AutosavePosts from './collections/Autosave.js'
import AutosaveGlobal from './globals/Autosave.js'
import { autosaveCollectionSlug, draftCollectionSlug } from './slugs.js'
let payload: Payload
let restClient: NextRESTClient
let collectionLocalPostID: string
let collectionLocalVersionID
let token
let collectionGraphQLPostID
let collectionGraphQLVersionID
const collectionGraphQLOriginalTitle = 'autosave title'
const collection = AutosavePosts.slug
const globalSlug = AutosaveGlobal.slug
let globalLocalVersionID
let globalGraphQLVersionID
const globalGraphQLOriginalTitle = 'updated global title'
const updatedTitle = 'Here is an updated post title in EN'
const filename = fileURLToPath(import.meta.url)
const dirname = path.dirname(filename)
const formatGraphQLID = (id: number | string) =>
payload.db.defaultIDType === 'number' ? id : `"${id}"`
describe('Versions', () => {
beforeAll(async () => {
process.env.SEED_IN_CONFIG_ONINIT = 'false' // Makes it so the payload config onInit seed is not run. Otherwise, the seed would be run unnecessarily twice for the initial test run - once for beforeEach and once for onInit
;({ payload, restClient } = await initPayloadInt(dirname))
})
afterAll(async () => {
if (typeof payload.db.destroy === 'function') {
await payload.db.destroy()
}
})
beforeEach(async () => {
await clearAndSeedEverything(payload)
const login = `
mutation {
loginUser(
email: "${devUser.email}",
password: "${devUser.password}"
) {
token
}
}`
const { data } = await restClient
.GRAPHQL_POST({ body: JSON.stringify({ query: login }) })
.then((res) => res.json())
token = data.loginUser.token
// now: initialize
const autosavePost = await payload.create({
collection,
data: {
description: '345j23o4ifj34jf54g',
title: 'Here is an autosave post in EN',
},
})
collectionLocalPostID = autosavePost.id
await payload.update({
id: collectionLocalPostID,
collection,
data: {
title: updatedTitle,
},
})
const versions = await payload.findVersions({
collection,
})
collectionLocalVersionID = versions.docs[0].id
})
describe('Collections - Local', () => {
describe('Create', () => {
it('should allow creating a draft with missing required field data', async () => {
const draft = await payload.create({
collection: autosaveCollectionSlug,
data: {
description: undefined,
title: 'i have a title',
},
draft: true,
})
expect(draft.id).toBeDefined()
})
it('should allow a new version to be created and updated', async () => {
const updatedPost = await payload.findByID({
id: collectionLocalPostID,
collection,
})
expect(updatedPost.title).toBe(updatedTitle)
expect(updatedPost._status).toStrictEqual('draft')
expect(collectionLocalVersionID).toBeDefined()
})
it('should paginate versions', async () => {
const versions = await payload.findVersions({
collection: draftCollectionSlug,
limit: 5,
})
const versionsPage2 = await payload.findVersions({
collection: draftCollectionSlug,
limit: 5,
page: 2,
})
expect(versions.docs).toHaveLength(5)
expect(versions.page).toBe(1)
expect(versionsPage2.docs).toHaveLength(5)
expect(versionsPage2.page).toBe(2)
expect(versions.docs[0].id).not.toBe(versionsPage2.docs[0].id)
})
it('should allow saving multiple versions of models with unique fields', async () => {
const autosavePost = await payload.create({
collection,
data: {
description: 'description 1',
title: 'unique unchanging title',
},
})
await payload.update({
id: autosavePost.id,
collection,
data: {
description: 'description 2',
},
})
const finalDescription = 'final description'
const secondUpdate = await payload.update({
id: autosavePost.id,
collection,
data: {
description: finalDescription,
},
})
expect(secondUpdate.description).toBe(finalDescription)
})
it('should allow a version to be retrieved by ID', async () => {
const version = await payload.findVersionByID({
id: collectionLocalVersionID,
collection,
})
expect(version.id).toStrictEqual(collectionLocalVersionID)
})
it('should allow a version to save locales properly', async () => {
const englishTitle = 'Title in EN'
const spanishTitle = 'Title in ES'
await payload.update({
id: collectionLocalPostID,
collection,
data: {
title: englishTitle,
},
})
const updatedPostES = await payload.update({
id: collectionLocalPostID,
collection,
data: {
title: spanishTitle,
},
locale: 'es',
})
expect(updatedPostES.title).toBe(spanishTitle)
const newEnglishTitle = 'New title in EN'
await payload.update({
id: collectionLocalPostID,
collection,
data: {
title: newEnglishTitle,
},
})
const versions = await payload.findVersions({
collection,
locale: 'all',
where: {
parent: {
equals: collectionLocalPostID,
},
},
})
expect(versions.docs[0].version.title.en).toStrictEqual(newEnglishTitle)
expect(versions.docs[0].version.title.es).toStrictEqual(spanishTitle)
})
it('should query drafts with sort', async () => {
const draftsAscending = await payload.find({
collection: draftCollectionSlug,
draft: true,
sort: 'title',
})
const draftsDescending = await payload.find({
collection: draftCollectionSlug,
draft: true,
sort: '-title',
})
expect(draftsAscending).toBeDefined()
expect(draftsDescending).toBeDefined()
expect(draftsAscending.docs[0]).toMatchObject(
draftsDescending.docs[draftsDescending.docs.length - 1],
)
})
// https://github.com/payloadcms/payload/issues/4827
it('should query drafts with relation', async () => {
const draftPost = await payload.create({
collection: draftCollectionSlug,
data: {
description: 'Description',
title: 'Some Title',
},
})
await payload.create({
collection: draftCollectionSlug,
data: {
description: 'Description',
relation: draftPost.id,
title: 'With Relation',
},
})
const query = {
collection: draftCollectionSlug,
where: {
relation: {
equals: draftPost.id,
},
},
}
const all = await payload.find(query)
const drafts = await payload.find({ ...query, draft: true })
expect(all.docs).toHaveLength(1)
expect(drafts.docs).toHaveLength(1)
})
it('should `findVersions` with sort', async () => {
const draftsAscending = await payload.findVersions({
collection: draftCollectionSlug,
draft: true,
limit: 100,
sort: 'createdAt',
})
const draftsDescending = await payload.findVersions({
collection: draftCollectionSlug,
draft: true,
limit: 100,
sort: '-createdAt',
})
expect(draftsAscending).toBeDefined()
expect(draftsDescending).toBeDefined()
expect(draftsAscending.docs[0]).toMatchObject(
draftsDescending.docs[draftsDescending.docs.length - 1],
)
})
})
describe('Restore', () => {
it('should return `findVersions` in correct order', async () => {
const somePost = await payload.create({
collection: draftCollectionSlug,
data: {
description: 'description 1',
title: 'first post',
},
})
const updatedPost = await payload.update({
id: somePost.id,
collection: draftCollectionSlug,
data: {
title: 'This should be the latest version',
},
})
const versions = await payload.findVersions({
collection: draftCollectionSlug,
where: {
parent: { equals: somePost.id },
},
})
expect(versions.docs[0].version.title).toBe(updatedPost.title)
})
it('should allow a version to be restored', async () => {
const title2 = 'Another updated post title in EN'
const updated = 'updated'
const versionedPost = await payload.create({
collection: draftCollectionSlug,
data: {
description: 'version description',
title: 'version title',
},
draft: true,
})
let updatedPost = await payload.update({
id: versionedPost.id,
collection: draftCollectionSlug,
data: {
blocksField: [
{
blockType: 'block',
localized: 'text',
text: 'text',
},
],
title: title2,
},
draft: true,
})
updatedPost = await payload.update({
id: versionedPost.id,
collection: draftCollectionSlug,
data: {
blocksField: [
{
id: updatedPost.blocksField[0].id,
blockName: 'breakpoint',
blockType: 'block',
localized: updated,
text: updated,
},
],
title: title2,
},
draft: true,
})
expect(updatedPost.title).toBe(title2)
expect(updatedPost.blocksField[0].text).toBe(updated)
expect(updatedPost.blocksField[0].localized).toBe(updated)
// Make sure it was updated correctly
const draftFromUpdatedPost = await payload.findByID({
id: versionedPost.id,
collection: draftCollectionSlug,
draft: true,
})
expect(draftFromUpdatedPost.title).toBe(title2)
expect(draftFromUpdatedPost.blocksField).toHaveLength(1)
expect(draftFromUpdatedPost.blocksField[0].localized).toStrictEqual(updated)
const versions = await payload.findVersions({
collection: draftCollectionSlug,
where: {
parent: {
equals: versionedPost.id,
},
},
})
const versionToRestore = versions.docs[versions.docs.length - 1]
// restore to previous version
const restoredVersion = await payload.restoreVersion({
id: versionToRestore.id,
collection: draftCollectionSlug,
})
expect({ ...restoredVersion }).toMatchObject({
...versionToRestore.version,
updatedAt: restoredVersion.updatedAt,
})
const latestDraft = await payload.findByID({
id: versionedPost.id,
collection: draftCollectionSlug,
draft: true,
})
expect(latestDraft).toMatchObject({
...versionToRestore.version,
// timestamps cannot be guaranteed to be the exact same to the milliseconds
createdAt: latestDraft.createdAt,
updatedAt: latestDraft.updatedAt,
})
expect(latestDraft.blocksField).toHaveLength(0)
})
})
describe('Update', () => {
it('should allow a draft to be patched', async () => {
const originalTitle = 'Here is a published post'
const originalPublishedPost = await payload.create({
collection,
data: {
_status: 'published',
description: 'kjnjyhbbdsfseankuhsjsfghb',
title: originalTitle,
},
})
const patchedTitle = 'Here is a draft post with a patched title'
await payload.update({
id: originalPublishedPost.id,
collection,
data: {
_status: 'draft',
title: patchedTitle,
},
draft: true,
locale: 'en',
})
const spanishTitle = 'es title'
// second update to existing draft
await payload.update({
id: originalPublishedPost.id,
collection,
data: {
_status: 'draft',
title: spanishTitle,
},
draft: true,
locale: 'es',
})
const publishedPost = await payload.findByID({
id: originalPublishedPost.id,
collection,
})
const draftPost = await payload.findByID({
id: originalPublishedPost.id,
collection,
draft: true,
locale: 'all',
})
expect(publishedPost.title).toBe(originalTitle)
expect(draftPost.title.en).toBe(patchedTitle)
expect(draftPost.title.es).toBe(spanishTitle)
})
it('should validate when publishing with the draft arg', async () => {
// no title (not valid for publishing)
const doc = await payload.create({
collection: draftCollectionSlug,
data: {
description: 'desc',
},
draft: true,
})
await expect(async () => {
// should not be able to publish a doc that fails validation
await payload.update({
id: doc.id,
collection: draftCollectionSlug,
data: { _status: 'published' },
draft: true,
})
}).rejects.toThrow(ValidationError)
// succeeds but returns zero docs updated, with an error
const updateManyResult = await payload.update({
collection: draftCollectionSlug,
data: { _status: 'published' },
draft: true,
where: {
id: { equals: doc.id },
},
})
expect(updateManyResult.docs).toHaveLength(0)
expect(updateManyResult.errors).toStrictEqual([
{ id: doc.id, message: 'The following field is invalid: title' },
])
})
})
describe('Update Many', () => {
it('should update many using drafts', async () => {
const doc = await payload.create({
collection: draftCollectionSlug,
data: {
_status: 'published',
description: 'description to bulk update',
title: 'initial value',
},
})
await payload.update({
id: doc.id,
collection: draftCollectionSlug,
data: {
title: 'updated title',
},
draft: true,
})
// bulk publish
const updated = await payload.update({
collection: draftCollectionSlug,
data: {
_status: 'published',
description: 'updated description',
},
draft: true,
where: {
id: {
in: [doc.id],
},
},
})
const updatedDoc = updated.docs?.[0]
// get the published doc
const findResult = await payload.find({
collection: draftCollectionSlug,
where: {
id: { equals: doc.id },
},
})
const findDoc = findResult.docs?.[0]
expect(updatedDoc.description).toStrictEqual('updated description')
expect(updatedDoc.title).toStrictEqual('updated title')
expect(findDoc.title).toStrictEqual('updated title')
expect(findDoc.description).toStrictEqual('updated description')
})
})
describe('Delete', () => {
let postToDelete
beforeEach(async () => {
postToDelete = await payload.create({
collection,
data: {
_status: 'draft',
description: 'description',
title: 'title to delete',
},
})
})
it('should delete drafts', async () => {
const drafts = await payload.db.queryDrafts({
collection,
where: {
parent: {
equals: postToDelete.id,
},
},
})
await payload.delete({
collection,
where: {
id: { equals: postToDelete.id },
},
})
const result = await payload.db.queryDrafts({
collection,
where: {
parent: {
in: drafts.docs.map(({ id }) => id),
},
// appendVersionToQueryKey,
},
})
expect(result.docs).toHaveLength(0)
})
})
describe('Draft Count', () => {
it('creates proper number of drafts', async () => {
const originalDraft = await payload.create({
collection: 'draft-posts',
data: {
_status: 'draft',
description: 'A',
title: 'A',
},
draft: true,
})
await payload.update({
id: originalDraft.id,
collection: 'draft-posts',
data: {
_status: 'draft',
description: 'B',
title: 'B',
},
draft: true,
})
await payload.update({
id: originalDraft.id,
collection: 'draft-posts',
data: {
_status: 'draft',
description: 'C',
title: 'C',
},
draft: true,
})
const mostRecentDraft = await payload.findByID({
id: originalDraft.id,
collection: 'draft-posts',
draft: true,
})
expect(mostRecentDraft.title).toStrictEqual('C')
const versions = await payload.findVersions({
collection: 'draft-posts',
where: {
parent: {
equals: originalDraft.id,
},
},
})
expect(versions.docs).toHaveLength(3)
})
})
describe('Max Versions', () => {
// create 2 documents with 3 versions each
// expect 2 documents with 2 versions each
it('retains correct versions', async () => {
const doc1 = await payload.create({
collection: 'version-posts',
data: {
description: 'A',
title: 'A',
},
})
await payload.update({
id: doc1.id,
collection: 'version-posts',
data: {
description: 'B',
title: 'B',
},
})
const result = await payload.find({
collection: 'version-posts',
where: {
updatedAt: { less_than_equal: '2027-01-01T00:00:00.000Z' },
},
})
await payload.update({
id: doc1.id,
collection: 'version-posts',
data: {
description: 'C',
title: 'C',
},
})
const doc2 = await payload.create({
collection: 'version-posts',
data: {
description: 'D',
title: 'D',
},
})
await payload.update({
id: doc2.id,
collection: 'version-posts',
data: {
description: 'E',
title: 'E',
},
})
await payload.update({
id: doc2.id,
collection: 'version-posts',
data: {
description: 'F',
title: 'F',
},
})
const doc1Versions = await payload.findVersions({
collection: 'version-posts',
sort: '-updatedAt',
where: {
parent: {
equals: doc1.id,
},
},
})
const doc2Versions = await payload.findVersions({
collection: 'version-posts',
sort: '-updatedAt',
where: {
parent: {
equals: doc2.id,
},
},
})
// correctly retains 2 documents in the versions collection
expect(doc1Versions.totalDocs).toStrictEqual(2)
// correctly retains the most recent 2 versions
expect(doc1Versions.docs[1].version.title).toStrictEqual('B')
// correctly retains 2 documents in the versions collection
expect(doc2Versions.totalDocs).toStrictEqual(2)
// correctly retains the most recent 2 versions
expect(doc2Versions.docs[1].version.title).toStrictEqual('E')
const docs = await payload.find({
collection: 'version-posts',
})
// correctly retains 2 documents in the actual collection
expect(docs.totalDocs).toStrictEqual(2)
})
})
})
describe('Querying', () => {
const originalTitle = 'original title'
const updatedTitle1 = 'new title 1'
const updatedTitle2 = 'new title 2'
let firstDraft
beforeEach(async () => {
// This will be created in the `draft-posts` collection
firstDraft = await payload.create({
collection: 'draft-posts',
data: {
description: 'my description',
radio: 'test',
title: originalTitle,
},
})
// This will be created in the `_draft-posts_versions` collection
await payload.update({
id: firstDraft.id,
collection: 'draft-posts',
data: {
title: updatedTitle1,
},
draft: true,
})
// This will be created in the `_draft-posts_versions` collection
// and will be the newest draft, able to be queried on
await payload.update({
id: firstDraft.id,
collection: 'draft-posts',
data: {
title: updatedTitle2,
},
draft: true,
})
})
it('should allow querying a draft doc from main collection', async () => {
const findResults = await payload.find({
collection: 'draft-posts',
where: {
title: {
equals: originalTitle,
},
},
})
expect(findResults.docs[0].title).toStrictEqual(originalTitle)
})
it('should return more than 10 `totalDocs`', async () => {
const { id } = await payload.create({
collection: 'draft-posts',
data: {
description: 'Description',
title: 'Title',
},
})
const createVersions = async (int: number = 1) => {
for (let i = 0; i < int; i++) {
await payload.update({
id,
collection: 'draft-posts',
data: {
title: `Title ${i}`,
},
})
}
}
await createVersions(10)
const findResults = await payload.findVersions({
collection: 'draft-posts',
where: {
parent: {
equals: id,
},
},
})
expect(findResults.totalDocs).toBe(11)
})
it('should not be able to query an old draft version with draft=true', async () => {
const draftFindResults = await payload.find({
collection: 'draft-posts',
draft: true,
where: {
title: {
equals: updatedTitle1,
},
},
})
expect(draftFindResults.docs).toHaveLength(0)
})
it('should be able to query the newest draft version with draft=true', async () => {
const draftFindResults = await payload.find({
collection: 'draft-posts',
draft: true,
where: {
title: {
equals: updatedTitle2,
},
},
})
expect(draftFindResults.docs[0].title).toStrictEqual(updatedTitle2)
})
it("should not be able to query old drafts that don't match with draft=true", async () => {
const draftFindResults = await payload.find({
collection: 'draft-posts',
draft: true,
where: {
title: {
equals: originalTitle,
},
},
})
expect(draftFindResults.docs).toHaveLength(0)
})
it('should be able to query by id with draft=true', async () => {
const allDocs = await payload.find({
collection: 'draft-posts',
draft: true,
})
expect(allDocs.docs.length).toBeGreaterThan(1)
const byID = await payload.find({
collection: 'draft-posts',
draft: true,
where: {
id: {
equals: allDocs.docs[0].id,
},
},
})
expect(byID.docs).toHaveLength(1)
})
it('should be able to query by id AND any other field with draft=true', async () => {
const allDocs = await payload.find({
collection: 'draft-posts',
draft: true,
})
expect(allDocs.docs.length).toBeGreaterThan(1)
const results = await payload.find({
collection: 'draft-posts',
draft: true,
where: {
and: [
{
id: {
not_in: allDocs.docs[0].id,
},
},
{
title: {
like: 'Published',
},
},
],
},
})
expect(results.docs).toHaveLength(1)
})
})
describe('Collections - GraphQL', () => {
beforeEach(async () => {
const description = 'autosave description'
const query = `mutation {
createAutosavePost(data: {title: "${collectionGraphQLOriginalTitle}", description: "${description}"}) {
id
title
description
createdAt
updatedAt
_status
}
}`
const { data } = await restClient
.GRAPHQL_POST({
body: JSON.stringify({ query }),
headers: {
Authorization: `JWT ${token}`,
},
})
.then((res) => res.json())
collectionGraphQLPostID = data.createAutosavePost.id
})
describe('Create', () => {
it('should allow a new doc to be created with draft status', async () => {
const description2 = 'other autosave description'
const query = `mutation {
createAutosavePost(data: {title: "${'Some other title'}", description: "${description2}"}) {
id
title
description
createdAt
updatedAt
_status
}
}`
const { data } = await restClient
.GRAPHQL_POST({
body: JSON.stringify({ query }),
headers: {
Authorization: `JWT ${token}`,
},
})
.then((res) => res.json())
expect(data.createAutosavePost._status).toStrictEqual('draft')
})
})
describe('Read', () => {
const updatedTitle2 = 'updated title'
beforeEach(async () => {
// modify the post to create a new version
// language=graphQL
const update = `mutation {
updateAutosavePost(id: ${formatGraphQLID(
collectionGraphQLPostID,
)}, data: {title: "${updatedTitle2}"}) {
title
updatedAt
createdAt
}
}`
await restClient.GRAPHQL_POST({
body: JSON.stringify({ query: update }),
headers: {
Authorization: `JWT ${token}`,
},
})
// language=graphQL
const query = `query {
versionsAutosavePosts(where: { parent: { equals: ${formatGraphQLID(
collectionGraphQLPostID,
)} } }) {
docs {
id
}
}
}`
const { data } = await restClient
.GRAPHQL_POST({
body: JSON.stringify({ query }),
headers: {
Authorization: `JWT ${token}`,
},
})
.then((res) => res.json())
collectionGraphQLVersionID = data.versionsAutosavePosts.docs[0].id
})
it('should allow read of versions by version id', async () => {
const query = `query {
versionAutosavePost(id: ${formatGraphQLID(collectionGraphQLVersionID)}) {
id
parent {
id
}
version {
title
}
}
}`
const { data } = await restClient
.GRAPHQL_POST({
body: JSON.stringify({ query }),
headers: {
Authorization: `JWT ${token}`,
},
})
.then((res) => res.json())
expect(data.versionAutosavePost.id).toBeDefined()
expect(data.versionAutosavePost.parent.id).toStrictEqual(collectionGraphQLPostID)
expect(data.versionAutosavePost.version.title).toStrictEqual(updatedTitle2)
})
it('should allow read of versions by querying version content', async () => {
// language=graphQL
const query = `query {
versionsAutosavePosts(where: { version__title: {equals: "${collectionGraphQLOriginalTitle}" } }) {
docs {
id
parent {
id
}
version {
title
}
}
}
}`
const { data } = await restClient
.GRAPHQL_POST({
body: JSON.stringify({ query }),
headers: {
Authorization: `JWT ${token}`,
},
})
.then((res) => res.json())
const doc = data.versionsAutosavePosts.docs[0]
expect(doc.id).toBeDefined()
expect(doc.parent.id).toStrictEqual(collectionGraphQLPostID)
expect(doc.version.title).toStrictEqual(collectionGraphQLOriginalTitle)
})
})
describe('Restore', () => {
beforeEach(async () => {
// modify the post to create a new version
// language=graphQL
const update = `mutation {
updateAutosavePost(id: ${formatGraphQLID(
collectionGraphQLPostID,
)}, data: {title: "${collectionGraphQLOriginalTitle}"}) {
title
updatedAt
createdAt
}
}`
await restClient.GRAPHQL_POST({
body: JSON.stringify({ query: update }),
headers: {
Authorization: `JWT ${token}`,
},
})
// language=graphQL
const query = `query {
versionsAutosavePosts(where: { parent: { equals: ${formatGraphQLID(
collectionGraphQLPostID,
)} } }) {
docs {
id
}
}
}`
const { data } = await restClient
.GRAPHQL_POST({
body: JSON.stringify({ query }),
headers: {
Authorization: `JWT ${token}`,
},
})
.then((res) => res.json())
collectionGraphQLVersionID = data.versionsAutosavePosts.docs[0].id
})
it('should allow a version to be restored', async () => {
// Update it
const update = `mutation {
updateAutosavePost(id: ${formatGraphQLID(
collectionGraphQLPostID,
)}, data: {title: "${'Wrong title'}"}) {
title
updatedAt
createdAt
}
}`
await restClient.GRAPHQL_POST({
body: JSON.stringify({ query: update }),
headers: {
Authorization: `JWT ${token}`,
},
})
// restore a versionsPost
const restore = `mutation {
restoreVersionAutosavePost(id: ${formatGraphQLID(collectionGraphQLVersionID)}) {
title
}
}`
await restClient.GRAPHQL_POST({
body: JSON.stringify({ query: restore }),
headers: {
Authorization: `JWT ${token}`,
},
})
const query = `query {
AutosavePost(id: ${formatGraphQLID(collectionGraphQLPostID)}) {
title
}
}`
const { data } = await restClient
.GRAPHQL_POST({
body: JSON.stringify({ query }),
headers: {
Authorization: `JWT ${token}`,
},
})
.then((res) => res.json())
expect(data.AutosavePost.title).toStrictEqual(collectionGraphQLOriginalTitle)
})
})
})
describe('Globals - Local', () => {
beforeEach(async () => {
const title2 = 'Here is an updated global title in EN'
await payload.updateGlobal({
slug: globalSlug,
data: {
title: 'Test Global',
},
})
await payload.updateGlobal({
slug: globalSlug,
data: {
title: title2,
},
})
const versions = await payload.findGlobalVersions({
slug: globalSlug,
})
globalLocalVersionID = versions.docs[0].id
})
describe('Create', () => {
it('should allow a new version to be created', async () => {
const title2 = 'Here is an updated global title in EN'
const updatedGlobal = await payload.findGlobal({
slug: globalSlug,
})
expect(updatedGlobal.title).toBe(title2)
expect(updatedGlobal._status).toStrictEqual('draft')
expect(globalLocalVersionID).toBeDefined()
})
})
describe('Read', () => {
it('should allow a version to be retrieved by ID', async () => {
const version = await payload.findGlobalVersionByID({
id: globalLocalVersionID,
slug: globalSlug,
})
expect(version.id).toStrictEqual(globalLocalVersionID)
})
})
describe('Update', () => {
it('should allow a version to save locales properly', async () => {
const englishTitle = 'Title in EN'
const spanishTitle = 'Title in ES'
await payload.updateGlobal({
slug: globalSlug,
data: {
title: englishTitle,
},
})
const updatedGlobalES = await payload.updateGlobal({
slug: globalSlug,
data: {
title: spanishTitle,
},
locale: 'es',
})
expect(updatedGlobalES.title).toBe(spanishTitle)
const newEnglishTitle = 'New title in EN'
await payload.updateGlobal({
slug: globalSlug,
data: {
title: newEnglishTitle,
},
})
const versions = await payload.findGlobalVersions({
slug: globalSlug,
locale: 'all',
})
expect(versions.docs[0].version.title.en).toStrictEqual(newEnglishTitle)
expect(versions.docs[0].version.title.es).toStrictEqual(spanishTitle)
})
})
describe('Restore', () => {
it('should allow a version to be restored', async () => {
const title2 = 'Another updated title in EN'
const updatedGlobal = await payload.updateGlobal({
slug: globalSlug,
data: {
title: title2,
},
})
expect(updatedGlobal.title).toBe(title2)
// Make sure it was updated correctly
const foundUpdatedGlobal = await payload.findGlobal({
slug: globalSlug,
draft: true,
})
expect(foundUpdatedGlobal.title).toBe(title2)
const versions = await payload.findGlobalVersions({
slug: globalSlug,
})
globalLocalVersionID = versions.docs[1].id
const restore = await payload.restoreGlobalVersion({
id: globalLocalVersionID,
slug: globalSlug,
})
expect(restore.version.title).toBeDefined()
const restoredGlobal = await payload.findGlobal({
slug: globalSlug,
draft: true,
})
expect(restoredGlobal.title).toBe(restore.version.title.en)
})
})
describe('Patch', () => {
it('should allow a draft to be patched', async () => {
const originalTitle = 'Here is a published global'
await payload.updateGlobal({
slug: globalSlug,
data: {
_status: 'published',
description: 'kjnjyhbbdsfseankuhsjsfghb',
title: originalTitle,
},
})
const publishedGlobal = await payload.findGlobal({
slug: globalSlug,
draft: true,
})
const updatedTitle2 = 'Here is a draft global with a patched title'
await payload.updateGlobal({
slug: globalSlug,
data: {
_status: 'draft',
title: updatedTitle2,
},
draft: true,
locale: 'en',
})
await payload.updateGlobal({
slug: globalSlug,
data: {
_status: 'draft',
title: updatedTitle2,
},
draft: true,
locale: 'es',
})
const updatedGlobal = await payload.findGlobal({
slug: globalSlug,
draft: true,
locale: 'all',
})
expect(publishedGlobal.title).toBe(originalTitle)
expect(updatedGlobal.title.en).toBe(updatedTitle2)
expect(updatedGlobal.title.es).toBe(updatedTitle2)
})
it('should allow a draft to be published', async () => {
const originalTitle = 'Here is a draft'
await payload.updateGlobal({
slug: globalSlug,
data: {
_status: 'draft',
title: originalTitle,
},
draft: true,
})
const updatedTitle2 = 'Now try to publish'
const result = await payload.updateGlobal({
slug: globalSlug,
data: {
_status: 'published',
title: updatedTitle2,
},
})
expect(result.title).toBe(updatedTitle2)
})
})
})
describe('Globals - GraphQL', () => {
beforeEach(async () => {
// language=graphql
const update = `mutation {
updateAutosaveGlobal(draft: true, data: {
title: "${globalGraphQLOriginalTitle}"
}) {
_status
title
}
}`
await restClient.GRAPHQL_POST({
body: JSON.stringify({ query: update }),
headers: {
Authorization: `JWT ${token}`,
},
})
// language=graphQL
const query = `query {
versionsAutosaveGlobal(where: { version__title: { equals: "${globalGraphQLOriginalTitle}" } }) {
docs {
id
version {
title
}
}
}
}`
const { data } = await restClient
.GRAPHQL_POST({
body: JSON.stringify({ query }),
headers: {
Authorization: `JWT ${token}`,
},
})
.then((res) => res.json())
globalGraphQLVersionID = data.versionsAutosaveGlobal.docs[0].id
})
describe('Read', () => {
it('should allow read of versions by version id', async () => {
// language=graphql
const query = `query {
versionAutosaveGlobal(id: ${formatGraphQLID(globalGraphQLVersionID)}) {
id
version {
title
}
}
}`
const { data } = await restClient
.GRAPHQL_POST({
body: JSON.stringify({ query }),
headers: {
Authorization: `JWT ${token}`,
},
})
.then((res) => res.json())
expect(data.versionAutosaveGlobal.id).toBeDefined()
expect(data.versionAutosaveGlobal.version.title).toStrictEqual(globalGraphQLOriginalTitle)
})
it('should allow read of versions by querying version content', async () => {
// language=graphQL
const query = `query {
versionsAutosaveGlobal(where: { version__title: {equals: "${globalGraphQLOriginalTitle}" } }) {
docs {
id
version {
title
}
}
}
}`
const { data } = await restClient
.GRAPHQL_POST({
body: JSON.stringify({ query }),
headers: {
Authorization: `JWT ${token}`,
},
})
.then((res) => res.json())
const doc = data.versionsAutosaveGlobal.docs[0]
expect(doc.id).toBeDefined()
expect(doc.version.title).toStrictEqual(globalGraphQLOriginalTitle)
})
})
describe('Restore', () => {
it('should allow a version to be restored', async () => {
// language=graphql
const restore = `mutation {
restoreVersionAutosaveGlobal(id: ${formatGraphQLID(globalGraphQLVersionID)}) {
title
}
}`
await restClient.GRAPHQL_POST({
body: JSON.stringify({ query: restore }),
headers: {
Authorization: `JWT ${token}`,
},
})
const query = `query {
AutosaveGlobal {
title
}
}`
const { data } = await restClient
.GRAPHQL_POST({
body: JSON.stringify({ query }),
headers: {
Authorization: `JWT ${token}`,
},
})
.then((res) => res.json())
expect(data.AutosaveGlobal).toEqual({ title: globalGraphQLOriginalTitle })
})
})
})
})