Compare commits

..

1 Commits

Author SHA1 Message Date
Elliot DeNolf
e3ef443217 chore(release): db-postgres/0.1.2 2023-10-10 15:57:51 -04:00
60 changed files with 446 additions and 758 deletions

View File

@@ -2,7 +2,7 @@
<!-- Please include a summary of the pull request and any related issues it fixes. Please also include relevant motivation and context. -->
- [ ] I have read and understand the [CONTRIBUTING.md](https://github.com/payloadcms/payload/blob/main/CONTRIBUTING.md) document in this repository.
- [ ] I have read and understand the [CONTRIBUTING.md](../CONTRIBUTING.md) document in this repository.
## Type of change

View File

@@ -121,12 +121,6 @@ This means that in some fringe cases, if you are creating a doc and then instant
To avoid any issues, you can pass the `req.transactionID` through to your Local API calls, so that your Local API calls are included as part of the parent transaction.
### ⚠️ Locales now have more functionality, and in some places, you might need to update custom code
Payload's locales have become more powerful and now allow you to customize more aspects per locale such as a human-friendly label and if the locale is RTL or not.
This means that certain functions now return a different shape, such as `useLocale`. This hook used to return a string of the locale code you are currently editing, but it now returns an object with type of `Locale`.
### ⚠️ Admin panel CSS classes may have changed
The revisions we've made in 2.0 required changes to both HTML and CSS within the admin panel. For this reason, if you were loading custom CSS into the admin panel to customize the look and feel, your stylesheets may need to be updated. If your CSS is targeting elements on the page using HTML selectors or class names, you may need to update these selectors based on the current markup. It may also be necessary to update your style definitions if the core Payload component you are targeting has undergone significant change.

View File

@@ -26,9 +26,7 @@
</h4>
<hr/>
<h3>
🎉 Payload 2.0 is now available! Read more in the <a target="_blank" href="https://payloadcms.com/blog/payload-2-0" rel="dofollow"><strong>announcement post</strong></a>
</h3>
### 🎉 Payload 2.0 is now available! Read more in the [announcement post](https://payloadcms.com/blog/payload-2-0).
<h3>Benefits over a regular CMS</h3>
<ul>

View File

@@ -347,7 +347,7 @@ The `useForm` hook returns an object with the following properties: |
value: <strong><code>rowIndex</code></strong>,
},
{
value: "The index of the row to add. If omitted, the row will be added to the end of the array.",
value: "The index of the row to add",
},
],
[

View File

@@ -65,7 +65,7 @@ After a user logs in, they can change their language selection in the `/account`
<strong>Note:</strong>
<br />
If there is a language that Payload does not yet support, we accept code
[contributions](https://github.com/payloadcms/payload/blob/main/CONTRIBUTING.md).
[contributions](https://github.com/payloadcms/payload/blob/main/contributing.md).
</Banner>
### Node Express

View File

@@ -8,7 +8,7 @@ keywords: headless cms, typescript, documentation, Content Management System, cm
When working with GraphQL it is useful to have the schema for development of other projects that need to call on your GraphQL endpoint. In Payload the schema is controlled by your collections and globals and is made available to the developer or third parties, it is not necessary for developers using Payload to write schema types manually.
### Schema generation script
### Schema generatation script
Run the following command in a Payload project to generate your project's GraphQL schema from Payload:

View File

@@ -1,5 +1,4 @@
{
"ext": "ts",
"exec": "ts-node src/server.ts -- -I",
"stdin": false
"exec": "ts-node src/server.ts"
}

View File

@@ -1,6 +1,5 @@
{
"watch": ["server.ts"],
"exec": "ts-node --project tsconfig.server.json src/server.ts -- -I",
"ext": "js ts",
"stdin": false
"exec": "ts-node --project tsconfig.server.json src/server.ts",
"ext": "js ts"
}

View File

@@ -1,5 +1,4 @@
{
"ext": "ts",
"exec": "ts-node src/server.ts -- -I",
"stdin": false
"exec": "ts-node src/server.ts"
}

View File

@@ -1,5 +1,4 @@
{
"ext": "ts",
"exec": "ts-node src/server.ts -- -I",
"stdin": false
"exec": "ts-node src/server.ts"
}

View File

@@ -1,5 +1,4 @@
{
"ext": "ts",
"exec": "ts-node src/server.ts -- -I",
"stdin": false
"exec": "ts-node src/server.ts"
}

View File

@@ -1,5 +1,4 @@
{
"ext": "ts",
"exec": "ts-node src/server.ts -- -I",
"stdin": false
"exec": "ts-node src/server.ts"
}

View File

@@ -1,5 +1,4 @@
{
"ext": "ts",
"exec": "ts-node src/server.ts -- -I",
"stdin": false
"exec": "ts-node src/server.ts"
}

View File

@@ -1,5 +1,4 @@
{
"ext": "ts",
"exec": "ts-node src/server.ts -- -I",
"stdin": false
"exec": "ts-node src/server.ts"
}

View File

@@ -1,5 +1,4 @@
{
"ext": "ts",
"exec": "ts-node src/server.ts -- -I",
"stdin": false
"exec": "ts-node src/server.ts"
}

View File

@@ -50,7 +50,6 @@
"@types/shelljs": "0.8.12",
"@types/testing-library__jest-dom": "5.14.8",
"chalk": "^5.3.0",
"chalk-template": "1.1.0",
"copyfiles": "2.4.1",
"cross-env": "7.0.3",
"dotenv": "8.6.0",
@@ -59,6 +58,7 @@
"fs-extra": "10.1.0",
"get-port": "5.1.1",
"glob": "8.1.0",
"graphql-request": "6.1.0",
"husky": "^8.0.3",
"isomorphic-fetch": "3.0.0",
"jest": "29.6.4",
@@ -77,7 +77,6 @@
"slash": "3.0.0",
"slate": "0.91.4",
"ts-node": "10.9.1",
"tsx": "^3.13.0",
"turbo": "^1.10.15",
"typescript": "5.2.2",
"uuid": "^9.0.0"

View File

@@ -1,6 +1,6 @@
{
"name": "@payloadcms/db-mongodb",
"version": "1.0.3",
"version": "1.0.2",
"description": "The officially supported MongoDB database adapter for Payload",
"repository": "https://github.com/payloadcms/payload",
"license": "MIT",
@@ -23,7 +23,7 @@
"bson-objectid": "2.0.4",
"deepmerge": "4.3.1",
"get-port": "5.1.1",
"mongoose": "6.12.0",
"mongoose": "6.11.4",
"mongoose-aggregate-paginate-v2": "1.0.6",
"mongoose-paginate-v2": "1.7.22",
"prompts": "2.4.2",

View File

@@ -68,9 +68,7 @@ export type MongooseAdapter = BaseDatabaseAdapter &
type MongooseAdapterResult = (args: { payload: Payload }) => MongooseAdapter
declare module 'payload' {
export interface DatabaseAdapter
extends Omit<BaseDatabaseAdapter, 'sessions'>,
Omit<Args, 'migrationDir'> {
export interface DatabaseAdapter extends Args {
collections: {
[slug: string]: CollectionModel
}

View File

@@ -1,6 +1,6 @@
{
"name": "@payloadcms/db-postgres",
"version": "0.1.3",
"version": "0.1.2",
"description": "The officially supported Postgres database adapter for Payload",
"repository": "https://github.com/payloadcms/payload",
"license": "MIT",
@@ -22,7 +22,7 @@
"dependencies": {
"@libsql/client": "^0.3.1",
"console-table-printer": "2.11.2",
"drizzle-kit": "0.19.13",
"drizzle-kit": "0.19.13-e99bac1",
"drizzle-orm": "0.28.5",
"pg": "8.11.3",
"prompts": "2.4.2",

View File

@@ -15,7 +15,6 @@ type Args = Omit<FindArgs, 'collection'> & {
adapter: PostgresAdapter
fields: Field[]
tableName: string
version?: boolean
}
export const findMany = async function find({
@@ -27,9 +26,8 @@ export const findMany = async function find({
pagination,
req = {} as PayloadRequest,
skip,
sort: sortArg,
sort,
tableName,
version,
where: whereArg,
}: Args) {
const db = adapter.sessions[req.transactionID]?.db || adapter.drizzle
@@ -42,11 +40,6 @@ export const findMany = async function find({
let hasNextPage: boolean
let pagingCounter: number
let selectDistinctResult
let sort = sortArg
if (version && sort) {
const direction = sort[0] === '-' ? '-' : ''
sort = `${direction}version.${direction.length === 1 ? sort.substring(1) : sort}`
}
const { joinAliases, joins, orderBy, selectFields, where } = await buildQuery({
adapter,
@@ -157,10 +150,7 @@ export const findMany = async function find({
const countResult = await chainMethods({
methods: selectCountMethods,
query: db
.select({
count: sql<number>`count
(*)`,
})
.select({ count: sql<number>`count(*)` })
.from(table)
.where(where),
})

View File

@@ -39,7 +39,6 @@ export const findVersions: FindVersions = async function findVersions(
skip,
sort,
tableName,
version: true,
where,
})
}

View File

@@ -24,7 +24,6 @@ export const init: Init = async function init(this: PostgresAdapter) {
buildTable({
adapter: this,
buildRelationships: true,
disableNotNull: !!collection?.versions?.drafts,
disableUnique: false,
fields: collection.fields,
tableName,
@@ -38,7 +37,6 @@ export const init: Init = async function init(this: PostgresAdapter) {
buildTable({
adapter: this,
buildRelationships: true,
disableNotNull: !!collection.versions?.drafts,
disableUnique: true,
fields: versionFields,
tableName: versionsTableName,
@@ -53,7 +51,6 @@ export const init: Init = async function init(this: PostgresAdapter) {
buildTable({
adapter: this,
buildRelationships: true,
disableNotNull: !!global?.versions?.drafts,
disableUnique: false,
fields: global.fields,
tableName,
@@ -67,7 +64,6 @@ export const init: Init = async function init(this: PostgresAdapter) {
buildTable({
adapter: this,
buildRelationships: true,
disableNotNull: !!global.versions?.drafts,
disableUnique: true,
fields: versionFields,
tableName: versionsTableName,

View File

@@ -32,7 +32,6 @@ export const queryDrafts: QueryDrafts = async function queryDrafts({
req,
sort,
tableName,
version: true,
where: combinedWhere,
})

View File

@@ -27,7 +27,6 @@ type Args = {
baseColumns?: Record<string, PgColumnBuilder>
baseExtraConfig?: Record<string, (cols: GenericColumns) => IndexBuilder | UniqueConstraintBuilder>
buildRelationships?: boolean
disableNotNull: boolean
disableUnique: boolean
fields: Field[]
rootRelationsToBuild?: Map<string, string>
@@ -47,7 +46,6 @@ export const buildTable = ({
baseColumns = {},
baseExtraConfig = {},
buildRelationships,
disableNotNull,
disableUnique = false,
fields,
rootRelationsToBuild,
@@ -104,7 +102,6 @@ export const buildTable = ({
adapter,
buildRelationships,
columns,
disableNotNull,
disableUnique,
fields,
indexes,

View File

@@ -34,7 +34,6 @@ type Args = {
buildRelationships: boolean
columnPrefix?: string
columns: Record<string, PgColumnBuilder>
disableNotNull: boolean
disableUnique?: boolean
fieldPrefix?: string
fields: (Field | TabAsField)[]
@@ -63,7 +62,6 @@ export const traverseFields = ({
buildRelationships,
columnPrefix,
columns,
disableNotNull,
disableUnique = false,
fieldPrefix,
fields,
@@ -176,7 +174,7 @@ export const traverseFields = ({
case 'radio':
case 'select': {
const enumName = `enum_${newTableName}_${toSnakeCase(field.name)}`
const enumName = `enum_${newTableName}_${columnPrefix || ''}${toSnakeCase(field.name)}`
adapter.enums[enumName] = pgEnum(
enumName,
@@ -190,7 +188,7 @@ export const traverseFields = ({
)
if (field.type === 'select' && field.hasMany) {
const selectTableName = `${newTableName}_${toSnakeCase(field.name)}`
const selectTableName = `${newTableName}_${toSnakeCase(fieldName)}`
const baseColumns: Record<string, PgColumnBuilder> = {
order: integer('order').notNull(),
parent: parentIDColumnMap[parentIDColType]('parent_id')
@@ -220,7 +218,6 @@ export const traverseFields = ({
adapter,
baseColumns,
baseExtraConfig,
disableNotNull,
disableUnique,
fields: [],
tableName: selectTableName,
@@ -277,7 +274,6 @@ export const traverseFields = ({
adapter,
baseColumns,
baseExtraConfig,
disableNotNull,
disableUnique,
fields: field.fields,
rootRelationsToBuild,
@@ -343,7 +339,6 @@ export const traverseFields = ({
adapter,
baseColumns,
baseExtraConfig,
disableNotNull,
disableUnique,
fields: block.fields,
rootRelationsToBuild,
@@ -404,7 +399,6 @@ export const traverseFields = ({
buildRelationships,
columnPrefix,
columns,
disableNotNull,
disableUnique,
fieldPrefix,
fields: field.fields,
@@ -438,7 +432,6 @@ export const traverseFields = ({
buildRelationships,
columnPrefix: `${columnName}_`,
columns,
disableNotNull,
disableUnique,
fieldPrefix: `${fieldName}_`,
fields: field.fields,
@@ -473,7 +466,6 @@ export const traverseFields = ({
buildRelationships,
columnPrefix,
columns,
disableNotNull,
disableUnique,
fieldPrefix,
fields: field.tabs.map((tab) => ({ ...tab, type: 'tab' })),
@@ -510,7 +502,6 @@ export const traverseFields = ({
buildRelationships,
columnPrefix,
columns,
disableNotNull,
disableUnique,
fieldPrefix,
fields: field.fields,
@@ -553,13 +544,7 @@ export const traverseFields = ({
const condition = field.admin && field.admin.condition
if (
!disableNotNull &&
targetTable[fieldName] &&
'required' in field &&
field.required &&
!condition
) {
if (targetTable[fieldName] && 'required' in field && field.required && !condition) {
targetTable[fieldName].notNull()
}
})

View File

@@ -69,9 +69,7 @@ export type MigrateUpArgs = { payload: Payload }
export type MigrateDownArgs = { payload: Payload }
declare module 'payload' {
export interface DatabaseAdapter
extends Omit<Args, 'migrationDir' | 'pool'>,
BaseDatabaseAdapter {
export interface DatabaseAdapter extends Omit<Args, 'pool'> {
drizzle: DrizzleDB
enums: Record<string, GenericEnum>
pool: Pool

View File

@@ -26,9 +26,7 @@
</h4>
<hr/>
<h3>
🎉 Payload 2.0 is now available! Read more in the <a target="_blank" href="https://payloadcms.com/blog/payload-2-0" rel="dofollow"><strong>announcement post</strong></a>
</h3>
### 🎉 Payload 2.0 is now available! Read more in the [announcement post](https://payloadcms.com/blog/payload-2-0).
<h3>Benefits over a regular CMS</h3>
<ul>

View File

@@ -1,6 +1,6 @@
{
"name": "payload",
"version": "2.0.4",
"version": "2.0.3",
"description": "Node, React and MongoDB Headless CMS and Application Framework",
"license": "MIT",
"main": "./dist/index.js",
@@ -77,7 +77,7 @@
"flatley": "5.2.0",
"fs-extra": "10.1.0",
"get-tsconfig": "4.6.2",
"graphql": "16.8.1",
"graphql": "16.7.1",
"graphql-http": "1.21.0",
"graphql-playground-middleware-express": "1.7.23",
"graphql-query-complexity": "0.12.0",
@@ -187,7 +187,7 @@
"file-loader": "6.2.0",
"form-data": "3.0.1",
"get-port": "5.1.1",
"graphql-request": "6.1.0",
"graphql-request": "3.7.0",
"mini-css-extract-plugin": "1.6.2",
"node-fetch": "2.6.12",
"nodemon": "3.0.1",

View File

@@ -66,7 +66,7 @@ export const ArrayAction: React.FC<Props> = ({
<PopupList.Button
className={`${baseClass}__action ${baseClass}__add`}
onClick={() => {
addRow(index + 1)
addRow(index)
close()
}}
>

View File

@@ -132,9 +132,7 @@ export function fieldReducer(state: Fields, action: FieldAction): Fields {
}
case 'ADD_ROW': {
const { blockType, path, rowIndex: rowIndexFromArgs, subFieldState } = action
const rowIndex =
typeof rowIndexFromArgs === 'number' ? rowIndexFromArgs : state[path]?.rows?.length || 0
const { blockType, path, rowIndex, subFieldState } = action
const rowsMetadata = [...(state[path]?.rows || [])]
rowsMetadata.splice(
@@ -157,22 +155,19 @@ export function fieldReducer(state: Fields, action: FieldAction): Fields {
}
}
// add new row to array _field state_
const { remainingFields, rows: siblingRows } = separateRows(path, state)
siblingRows.splice(rowIndex, 0, subFieldState)
const { remainingFields, rows } = separateRows(path, state)
// add new row to array _value_
const currentValue = (Array.isArray(state[path]?.value) ? state[path]?.value : []) as Fields[]
const newValue = currentValue.splice(rowIndex, 0, reduceFieldsToValues(subFieldState, true))
// actual form state (value saved in db)
rows.splice(rowIndex, 0, subFieldState)
const newState: Fields = {
...remainingFields,
...flattenRows(path, siblingRows),
...flattenRows(path, rows),
[path]: {
...state[path],
disableFormData: true,
rows: rowsMetadata,
value: newValue,
value: rows,
},
}
@@ -181,8 +176,8 @@ export function fieldReducer(state: Fields, action: FieldAction): Fields {
case 'REPLACE_ROW': {
const { blockType, path, rowIndex: rowIndexArg, subFieldState } = action
const { remainingFields, rows: siblingRows } = separateRows(path, state)
const rowIndex = Math.max(0, Math.min(rowIndexArg, siblingRows?.length - 1 || 0))
const { remainingFields, rows } = separateRows(path, state)
const rowIndex = Math.max(0, Math.min(rowIndexArg, rows?.length - 1 || 0))
const rowsMetadata = [...(state[path]?.rows || [])]
rowsMetadata[rowIndex] = {
@@ -200,21 +195,17 @@ export function fieldReducer(state: Fields, action: FieldAction): Fields {
}
}
// replace form _field state_
siblingRows[rowIndex] = subFieldState
// replace array _value_
const newValue = Array.isArray(state[path]?.value) ? state[path]?.value : []
newValue[rowIndex] = reduceFieldsToValues(subFieldState, true)
// replace form field state
rows[rowIndex] = subFieldState
const newState: Fields = {
...remainingFields,
...flattenRows(path, siblingRows),
...flattenRows(path, rows),
[path]: {
...state[path],
disableFormData: true,
rows: rowsMetadata,
value: newValue,
value: rows,
},
}

View File

@@ -431,7 +431,7 @@ const Form: React.FC<Props> = (props) => {
[],
)
const getRowSchemaByPath = React.useCallback(
const getRowConfigByPath = React.useCallback(
({ blockType, path }: { blockType?: string; path: string }) => {
const rowConfig = traverseRowConfigs({
fieldConfig: collection?.fields || global?.fields,
@@ -449,24 +449,23 @@ const Form: React.FC<Props> = (props) => {
const addFieldRow: Context['addFieldRow'] = useCallback(
async ({ data, path, rowIndex }) => {
const preferences = await getDocPreferences()
const rowSchema = getRowSchemaByPath({
const fieldConfig = getRowConfigByPath({
blockType: data?.blockType,
path,
})
if (rowSchema) {
if (fieldConfig) {
const subFieldState = await buildStateFromSchema({
id,
config,
data,
fieldSchema: rowSchema,
fieldSchema: fieldConfig,
locale,
operation,
preferences,
t,
user,
})
dispatchFields({
blockType: data?.blockType,
path,
@@ -476,11 +475,11 @@ const Form: React.FC<Props> = (props) => {
})
}
},
[dispatchFields, getDocPreferences, id, user, operation, locale, t, getRowSchemaByPath, config],
[dispatchFields, getDocPreferences, id, user, operation, locale, t, getRowConfigByPath, config],
)
const removeFieldRow: Context['removeFieldRow'] = useCallback(
({ path, rowIndex }) => {
async ({ path, rowIndex }) => {
dispatchFields({ path, rowIndex, type: 'REMOVE_ROW' })
},
[dispatchFields],
@@ -489,17 +488,17 @@ const Form: React.FC<Props> = (props) => {
const replaceFieldRow: Context['replaceFieldRow'] = useCallback(
async ({ data, path, rowIndex }) => {
const preferences = await getDocPreferences()
const rowSchema = getRowSchemaByPath({
const fieldConfig = getRowConfigByPath({
blockType: data?.blockType,
path,
})
if (rowSchema) {
if (fieldConfig) {
const subFieldState = await buildStateFromSchema({
id,
config,
data,
fieldSchema: rowSchema,
fieldSchema: fieldConfig,
locale,
operation,
preferences,
@@ -515,7 +514,7 @@ const Form: React.FC<Props> = (props) => {
})
}
},
[dispatchFields, getDocPreferences, id, user, operation, locale, t, getRowSchemaByPath, config],
[dispatchFields, getDocPreferences, id, user, operation, locale, t, getRowConfigByPath, config],
)
const getFields = useCallback(() => contextRef.current.fields, [contextRef])

View File

@@ -12,9 +12,9 @@ export const separateRows = (path: string, fields: Fields): Result => {
const newRows = incomingRows
if (fieldPath.indexOf(`${path}.`) === 0) {
const [rowIndex] = fieldPath.replace(`${path}.`, '').split('.')
if (!newRows[rowIndex]) newRows[rowIndex] = {}
newRows[rowIndex][fieldPath.replace(`${path}.${String(rowIndex)}.`, '')] = { ...field }
const index = Number(fieldPath.replace(`${path}.`, '').split('.')[0])
if (!newRows[index]) newRows[index] = {}
newRows[index][fieldPath.replace(`${path}.${String(index)}.`, '')] = { ...field }
} else {
remainingFields[fieldPath] = field
}

View File

@@ -174,10 +174,7 @@ export type Context = {
}: {
data?: Data
path: string
/*
* by default the new row will be added to the end of the list
*/
rowIndex?: number
rowIndex: number
}) => Promise<void>
buildRowErrors: () => void
createFormData: CreateFormData
@@ -193,7 +190,7 @@ export type Context = {
getField: GetField
getFields: GetFields
getSiblingData: GetSiblingData
removeFieldRow: ({ path, rowIndex }: { path: string; rowIndex: number }) => void
removeFieldRow: ({ path, rowIndex }: { path: string; rowIndex: number }) => Promise<void>
replaceFieldRow: ({
data,
path,

View File

@@ -5,9 +5,9 @@ import type { Props } from './types'
import { createNestedFieldPath } from '../../Form/createNestedFieldPath'
import RenderFields from '../../RenderFields'
import withCondition from '../../withCondition'
import { fieldBaseClass } from '../shared'
import './index.scss'
import { RowProvider } from './provider'
import { fieldBaseClass } from '../shared'
const Row: React.FC<Props> = (props) => {
const {
@@ -29,6 +29,7 @@ const Row: React.FC<Props> = (props) => {
}))}
fieldTypes={fieldTypes}
indexPath={indexPath}
margins={false}
permissions={permissions}
readOnly={readOnly}
/>

View File

@@ -7,10 +7,6 @@
gap: calc(var(--base) * 2);
align-items: flex-start;
ul {
padding-left: calc(var(--base) * 1);
}
&--fullscreen {
padding-left: 0;
.query-inspector__configuration {
@@ -177,10 +173,6 @@
}
}
&__row-line--nested {
margin-left: 25px;
}
&__bracket {
position: relative;

View File

@@ -1,8 +1,6 @@
import * as React from 'react'
import { useTranslation } from 'react-i18next'
import type { EditViewProps } from '../types'
import { Chevron } from '../..'
import { requests } from '../../../api'
import CopyToClipboard from '../../elements/CopyToClipboard'
@@ -13,7 +11,6 @@ import { MinimizeMaximize } from '../../icons/MinimizeMaximize'
import { useConfig } from '../../utilities/Config'
import { useDocumentInfo } from '../../utilities/DocumentInfo'
import { useLocale } from '../../utilities/Locale'
import { SetStepNav } from '../collections/Edit/SetStepNav'
import './index.scss'
const chars = {
@@ -122,19 +119,12 @@ const RecursivelyRenderObjectData = ({
}
if (type === 'date' || type === 'string' || type === 'null' || type === 'number') {
const parentHasKey = Boolean(parentType === 'object' && key)
const rowClasses = [
`${baseClass}__row-line`,
`${baseClass}__value-type--${type}`,
`${baseClass}__row-line--${objectKey ? 'nested' : 'top'}`,
]
.filter(Boolean)
.join(' ')
return (
<li className={rowClasses} key={`${key}-${keyIndex}`}>
{parentHasKey ? <span>{`"${key}": `}</span> : null}
<li
className={`${baseClass}__row-line ${baseClass}__value-type--${type}`}
key={`${key}-${keyIndex}`}
>
{parentType === 'object' ? <span>{`"${key}": `}</span> : null}
{type === 'string' ? (
<span className={`${baseClass}__value`}>{`"${value}"`}</span>
@@ -166,8 +156,7 @@ function createURL(url: string) {
}
}
export const API: React.FC<EditViewProps> = (props) => {
const { apiURL } = props
export const API = ({ apiURL }) => {
const { i18n } = useTranslation()
const {
localization,
@@ -212,15 +201,8 @@ export const API: React.FC<EditViewProps> = (props) => {
const classes = [baseClass, fullscreen && `${baseClass}--fullscreen`].filter(Boolean).join(' ')
let isEditing: boolean
if ('collection' in props) {
isEditing = props?.isEditing
}
return (
<Gutter className={classes} right={false}>
<SetStepNav collection={collection} global={global} id={id} isEditing={isEditing} />
<div className={`${baseClass}__configuration`}>
<div className={`${baseClass}__api-url`}>
<span className={`${baseClass}__label`}>

View File

@@ -49,9 +49,8 @@
&__sidebar-wrap {
position: sticky;
top: var(--doc-controls-height);
width: 33.33%;
height: 100%;
top: 0;
flex-grow: 1;
}
&__sidebar {

View File

@@ -53,9 +53,8 @@
&__sidebar-wrap {
position: sticky;
top: var(--doc-controls-height);
width: 33.33%;
height: 100%;
top: 0;
flex-grow: 1;
}
&__sidebar {

View File

@@ -13,7 +13,7 @@ import { useConfig } from '../../../utilities/Config'
export const SetStepNav: React.FC<
| {
collection: SanitizedCollectionConfig
id: number | string
id: string
isEditing: boolean
}
| {
@@ -27,7 +27,7 @@ export const SetStepNav: React.FC<
let pluralLabel: SanitizedCollectionConfig['labels']['plural']
let slug: string
let isEditing = false
let id: number | string | undefined
let id: string | undefined
if ('collection' in props) {
const {
@@ -70,7 +70,7 @@ export const SetStepNav: React.FC<
if (isEditing) {
nav.push({
label: useAsTitle && useAsTitle !== 'id' ? title || `[${t('untitled')}]` : `${id}`,
label: useAsTitle && useAsTitle !== 'id' ? title || `[${t('untitled')}]` : id,
})
} else {
nav.push({

View File

@@ -139,19 +139,6 @@ async function deleteOperation<TSlug extends keyof GeneratedTypes['collections']
t,
})
// /////////////////////////////////////
// Delete versions
// /////////////////////////////////////
if (collectionConfig.versions) {
await deleteCollectionVersions({
id,
payload,
req,
slug: collectionConfig.slug,
})
}
// /////////////////////////////////////
// Delete document
// /////////////////////////////////////
@@ -166,6 +153,19 @@ async function deleteOperation<TSlug extends keyof GeneratedTypes['collections']
},
})
// /////////////////////////////////////
// Delete versions
// /////////////////////////////////////
if (collectionConfig.versions) {
await deleteCollectionVersions({
id,
payload,
req,
slug: collectionConfig.slug,
})
}
// /////////////////////////////////////
// afterRead - Fields
// /////////////////////////////////////

View File

@@ -109,19 +109,6 @@ async function deleteByID<TSlug extends keyof GeneratedTypes['collections']>(
t,
})
// /////////////////////////////////////
// Delete versions
// /////////////////////////////////////
if (collectionConfig.versions) {
await deleteCollectionVersions({
id,
payload,
req,
slug: collectionConfig.slug,
})
}
// /////////////////////////////////////
// Delete document
// /////////////////////////////////////
@@ -143,6 +130,19 @@ async function deleteByID<TSlug extends keyof GeneratedTypes['collections']>(
req,
})
// /////////////////////////////////////
// Delete versions
// /////////////////////////////////////
if (collectionConfig.versions) {
await deleteCollectionVersions({
id,
payload,
req,
slug: collectionConfig.slug,
})
}
// /////////////////////////////////////
// afterRead - Fields
// /////////////////////////////////////

View File

@@ -243,8 +243,8 @@ async function updateByID<TSlug extends keyof GeneratedTypes['collections']>(
const { hash, salt } = await generatePasswordSaltHash({ password })
dataToUpdate.salt = salt
dataToUpdate.hash = hash
delete dataToUpdate.password
delete data.password
delete result.password
}
// /////////////////////////////////////

View File

@@ -273,7 +273,7 @@
"near": "in der Nähe"
},
"upload": {
"crop": "Zuschneiden",
"crop": "Ernte",
"cropToolDescription": "Ziehen Sie die Ecken des ausgewählten Bereichs, zeichnen Sie einen neuen Bereich oder passen Sie die Werte unten an.",
"dragAndDrop": "Ziehen Sie eine Datei per Drag-and-Drop",
"dragAndDropHere": "oder ziehe eine Datei hier",
@@ -368,4 +368,4 @@
"viewingVersions": "Betrachte Versionen für {{entityLabel}} {{documentTitle}}",
"viewingVersionsGlobal": "`Betrachte Versionen für das Globale Dokument {{entityLabel}}"
}
}
}

View File

@@ -273,7 +273,7 @@
"near": "рядом"
},
"upload": {
"crop": "Обрезать",
"crop": "Урожай",
"cropToolDescription": "Перетащите углы выбранной области, нарисуйте новую область или отрегулируйте значения ниже.",
"dragAndDrop": "Перетащите файл",
"dragAndDropHere": "или перетащите файл сюда",
@@ -368,4 +368,4 @@
"viewingVersions": "Просмотр версий для {{entityLabel}} {{documentTitle}}",
"viewingVersionsGlobal": "`Просмотр версии для глобальной Коллекции {{entityLabel}}"
}
}
}

View File

@@ -273,7 +273,7 @@
"near": "поруч"
},
"upload": {
"crop": "Обрізати",
"crop": "Врожай",
"cropToolDescription": "Перетягніть кути обраної області, намалюйте нову область або скоригуйте значення нижче.",
"dragAndDrop": "Перемістіть файл",
"dragAndDropHere": "або перемістіть сюди файл",
@@ -368,4 +368,4 @@
"viewingVersions": "Огляд версій для {{entityLabel}} {{documentTitle}}",
"viewingVersionsGlobal": "Огляд версій для глобальної колекції {{entityLabel}}"
}
}
}

View File

@@ -1,6 +1,6 @@
{
"name": "@payloadcms/richtext-slate",
"version": "1.0.2",
"version": "1.0.1",
"description": "The officially supported Slate richtext adapter for Payload",
"repository": "https://github.com/payloadcms/payload",
"license": "MIT",

149
pnpm-lock.yaml generated
View File

@@ -69,9 +69,6 @@ importers:
chalk:
specifier: ^5.3.0
version: 5.3.0
chalk-template:
specifier: 1.1.0
version: 1.1.0
copyfiles:
specifier: 2.4.1
version: 2.4.1
@@ -96,6 +93,9 @@ importers:
glob:
specifier: 8.1.0
version: 8.1.0
graphql-request:
specifier: 6.1.0
version: 6.1.0(graphql@16.7.1)
husky:
specifier: ^8.0.3
version: 8.0.3
@@ -150,9 +150,6 @@ importers:
ts-node:
specifier: 10.9.1
version: 10.9.1(@swc/core@1.3.76)(@types/node@20.5.7)(typescript@5.2.2)
tsx:
specifier: ^3.13.0
version: 3.13.0
turbo:
specifier: ^1.10.15
version: 1.10.15
@@ -315,8 +312,8 @@ importers:
specifier: 5.1.1
version: 5.1.1
mongoose:
specifier: 6.12.0
version: 6.12.0
specifier: 6.11.4
version: 6.11.4
mongoose-aggregate-paginate-v2:
specifier: 1.0.6
version: 1.0.6
@@ -355,11 +352,11 @@ importers:
specifier: 2.11.2
version: 2.11.2
drizzle-kit:
specifier: 0.19.13
version: 0.19.13
specifier: 0.19.13-e99bac1
version: 0.19.13-e99bac1
drizzle-orm:
specifier: 0.28.5
version: 0.28.5(@libsql/client@0.3.4)(@types/pg@8.10.2)(pg@8.11.3)
version: 0.28.5(@libsql/client@0.3.4)(@types/pg@8.10.2)(better-sqlite3@8.6.0)(pg@8.11.3)
pg:
specifier: 8.11.3
version: 8.11.3
@@ -549,23 +546,23 @@ importers:
specifier: 4.6.2
version: 4.6.2
graphql:
specifier: 16.8.1
version: 16.8.1
specifier: 16.7.1
version: 16.7.1
graphql-http:
specifier: 1.21.0
version: 1.21.0(graphql@16.8.1)
version: 1.21.0(graphql@16.7.1)
graphql-playground-middleware-express:
specifier: 1.7.23
version: 1.7.23(express@4.18.2)
graphql-query-complexity:
specifier: 0.12.0
version: 0.12.0(graphql@16.8.1)
version: 0.12.0(graphql@16.7.1)
graphql-scalars:
specifier: 1.22.2
version: 1.22.2(graphql@16.8.1)
version: 1.22.2(graphql@16.7.1)
graphql-type-json:
specifier: 0.3.2
version: 0.3.2(graphql@16.8.1)
version: 0.3.2(graphql@16.7.1)
html-webpack-plugin:
specifier: 5.5.3
version: 5.5.3(webpack@5.88.2)
@@ -874,8 +871,8 @@ importers:
specifier: 5.1.1
version: 5.1.1
graphql-request:
specifier: 6.1.0
version: 6.1.0(graphql@16.8.1)
specifier: 3.7.0
version: 3.7.0(graphql@16.7.1)
mini-css-extract-plugin:
specifier: 1.6.2
version: 1.6.2(webpack@5.88.2)
@@ -2414,7 +2411,7 @@ packages:
resolution: {integrity: sha512-FxEMIkJKnodyA1OaCUoEvbYRkoZlLZ4d/eXFu9Fh8CbBBgP5EmZxrfTRyN0qpXZ4vOvqnE5YdRdcrmUUXuU+dA==}
dependencies:
'@esbuild-kit/core-utils': 3.3.2
get-tsconfig: 4.7.2
get-tsconfig: 4.7.0
dev: false
/@esbuild/android-arm64@0.18.20:
@@ -2681,12 +2678,12 @@ packages:
resolution: {integrity: sha512-qprfWkn82Iw821mcKofJ5Pk9wgioHicxcQMxx+5zt5GSKoqdWvgG5AxVmpmUUjzTLPVSH5auBrhI93Deayn/DA==}
dev: false
/@graphql-typed-document-node/core@3.2.0(graphql@16.8.1):
/@graphql-typed-document-node/core@3.2.0(graphql@16.7.1):
resolution: {integrity: sha512-mB9oAsNCm9aM3/SOv4YtBMqZbYj10R7dkq8byBqxGY/ncFwhf2oQzMV+LCRlWoDSEBJ3COiR1yeDvMtsoOsuFQ==}
peerDependencies:
graphql: ^0.8.0 || ^0.9.0 || ^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^14.0.0 || ^15.0.0 || ^16.0.0 || ^17.0.0
dependencies:
graphql: 16.8.1
graphql: 16.7.1
dev: true
/@hapi/hoek@9.3.0:
@@ -3330,6 +3327,7 @@ packages:
requiresBuild: true
dependencies:
sparse-bitfield: 3.0.3
dev: true
optional: true
/@nodelib/fs.scandir@2.1.5:
@@ -4497,7 +4495,7 @@ packages:
/@types/mongoose-aggregate-paginate-v2@1.0.9:
resolution: {integrity: sha512-YKDKtSuE1vzMY/SAtlDTWJr52UhTYdrOypCqyx7T2xFYEWfybLnV98m4ZoVgYJH0XowVl7Y2Gnn6p1sF+3NbLA==}
dependencies:
mongoose: 6.12.0
mongoose: 6.11.4
transitivePeerDependencies:
- aws-crt
- supports-color
@@ -6046,13 +6044,6 @@ packages:
/caniuse-lite@1.0.30001535:
resolution: {integrity: sha512-48jLyUkiWFfhm/afF7cQPqPjaUmSraEhK4j+FCTJpgnGGEZHqyLe3hmWH7lIooZdSzXL0ReMvHz0vKDoTBsrwg==}
/chalk-template@1.1.0:
resolution: {integrity: sha512-T2VJbcDuZQ0Tb2EWwSotMPJjgpy1/tGee1BTpUNsGZ/qgNjV2t7Mvu+d4600U564nbLesN1x2dPL+xii174Ekg==}
engines: {node: '>=14.16'}
dependencies:
chalk: 5.3.0
dev: true
/chalk@2.4.2:
resolution: {integrity: sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==}
engines: {node: '>=4'}
@@ -7284,8 +7275,8 @@ packages:
wordwrap: 1.0.0
dev: false
/drizzle-kit@0.19.13:
resolution: {integrity: sha512-Rba5VW1O2JfJlwVBeZ8Zwt2E2us5oZ08PQBDiVSGlug53TOc8hzXjblZFuF+dnll9/RQEHrkzBmJFgqTvn5Rxg==}
/drizzle-kit@0.19.13-e99bac1:
resolution: {integrity: sha512-25Ahwm7CoaXCcrSuDjNqNH7vwrjt1s+I4O1yXVDBwYnyRe4RY8ZD57s5iA9PE5C+IJwBJtxBSXYWkat+efb3ug==}
hasBin: true
dependencies:
'@drizzle-team/studio': 0.0.5
@@ -7304,7 +7295,7 @@ packages:
- supports-color
dev: false
/drizzle-orm@0.28.5(@libsql/client@0.3.4)(@types/pg@8.10.2)(pg@8.11.3):
/drizzle-orm@0.28.5(@libsql/client@0.3.4)(@types/pg@8.10.2)(better-sqlite3@8.6.0)(pg@8.11.3):
resolution: {integrity: sha512-6r6Iw4c38NAmW6TiKH3TUpGUQ1YdlEoLJOQptn8XPx3Z63+vFNKfAiANqrIiYZiMjKR9+NYAL219nFrmo1duXA==}
peerDependencies:
'@aws-sdk/client-rds-data': '>=3'
@@ -7368,6 +7359,7 @@ packages:
dependencies:
'@libsql/client': 0.3.4
'@types/pg': 8.10.2
better-sqlite3: 8.6.0
pg: 8.11.3
dev: false
@@ -8232,6 +8224,11 @@ packages:
tmp: 0.0.33
dev: true
/extract-files@9.0.0:
resolution: {integrity: sha512-CvdFfHkC95B4bBBk36hcEmvdR2awOdhhVUYH6S/zrVj3477zven/fJMYg7121h4T1xHZC+tetUpubpAhxwI7hQ==}
engines: {node: ^10.17.0 || ^12.0.0 || >= 13.7.0}
dev: true
/fast-copy@3.0.1:
resolution: {integrity: sha512-Knr7NOtK3HWRYGtHoJrjkaWepqT8thIVGAwt0p0aUs1zqkAzXZV4vo9fFNwyb5fcqK1GKYFYxldQdIDVKhUAfA==}
dev: false
@@ -8637,10 +8634,11 @@ packages:
resolve-pkg-maps: 1.0.0
dev: false
/get-tsconfig@4.7.2:
resolution: {integrity: sha512-wuMsz4leaj5hbGgg4IvDU0bqJagpftG5l5cXIAvo8uZrqn0NJqwtfupTN00VnkQJPcIRrxYrm1Ue24btpCha2A==}
/get-tsconfig@4.7.0:
resolution: {integrity: sha512-pmjiZ7xtB8URYm74PlGJozDNyhvsVLUcpBa8DZBG3bWHwaHa9bPiRpiSfovw+fjhwONSCWKRyk+JQHEGZmMrzw==}
dependencies:
resolve-pkg-maps: 1.0.0
dev: false
/get-uri@6.0.1:
resolution: {integrity: sha512-7ZqONUVqaabogsYNWlYj0t3YZaL6dhuEueZXGF+/YVmf6dHmaFg8/6psJKqhx9QykIDKzpGcy2cn4oV4YC7V/Q==}
@@ -8868,13 +8866,13 @@ packages:
resolution: {integrity: sha512-EtKwoO6kxCL9WO5xipiHTZlSzBm7WLT627TqC/uVRd0HKmq8NXyebnNYxDoBi7wt8eTWrUrKXCOVaFq9x1kgag==}
dev: false
/graphql-http@1.21.0(graphql@16.8.1):
/graphql-http@1.21.0(graphql@16.7.1):
resolution: {integrity: sha512-yrItPfHj5WeT4n7iusbVin+vGSQjXFAX6U/GnYytdCJRXVad1TWGtYFDZ2ROjCKpXQzIwvfbiWCEwfuXgR3B6A==}
engines: {node: '>=12'}
peerDependencies:
graphql: '>=0.11 <=16'
dependencies:
graphql: 16.8.1
graphql: 16.7.1
dev: false
/graphql-playground-html@1.6.30:
@@ -8892,47 +8890,60 @@ packages:
graphql-playground-html: 1.6.30
dev: false
/graphql-query-complexity@0.12.0(graphql@16.8.1):
/graphql-query-complexity@0.12.0(graphql@16.7.1):
resolution: {integrity: sha512-fWEyuSL6g/+nSiIRgIipfI6UXTI7bAxrpPlCY1c0+V3pAEUo1ybaKmSBgNr1ed2r+agm1plJww8Loig9y6s2dw==}
peerDependencies:
graphql: ^14.6.0 || ^15.0.0 || ^16.0.0
dependencies:
graphql: 16.8.1
graphql: 16.7.1
lodash.get: 4.4.2
dev: false
/graphql-request@6.1.0(graphql@16.8.1):
resolution: {integrity: sha512-p+XPfS4q7aIpKVcgmnZKhMNqhltk20hfXtkaIkTfjjmiKMJ5xrt5c743cL03y/K7y1rg3WrIC49xGiEQ4mxdNw==}
/graphql-request@3.7.0(graphql@16.7.1):
resolution: {integrity: sha512-dw5PxHCgBneN2DDNqpWu8QkbbJ07oOziy8z+bK/TAXufsOLaETuVO4GkXrbs0WjhdKhBMN3BkpN/RIvUHkmNUQ==}
peerDependencies:
graphql: 14 - 16
dependencies:
'@graphql-typed-document-node/core': 3.2.0(graphql@16.8.1)
cross-fetch: 3.1.8
graphql: 16.8.1
extract-files: 9.0.0
form-data: 3.0.1
graphql: 16.7.1
transitivePeerDependencies:
- encoding
dev: true
/graphql-scalars@1.22.2(graphql@16.8.1):
/graphql-request@6.1.0(graphql@16.7.1):
resolution: {integrity: sha512-p+XPfS4q7aIpKVcgmnZKhMNqhltk20hfXtkaIkTfjjmiKMJ5xrt5c743cL03y/K7y1rg3WrIC49xGiEQ4mxdNw==}
peerDependencies:
graphql: 14 - 16
dependencies:
'@graphql-typed-document-node/core': 3.2.0(graphql@16.7.1)
cross-fetch: 3.1.8
graphql: 16.7.1
transitivePeerDependencies:
- encoding
dev: true
/graphql-scalars@1.22.2(graphql@16.7.1):
resolution: {integrity: sha512-my9FB4GtghqXqi/lWSVAOPiTzTnnEzdOXCsAC2bb5V7EFNQjVjwy3cSSbUvgYOtDuDibd+ZsCDhz+4eykYOlhQ==}
engines: {node: '>=10'}
peerDependencies:
graphql: ^0.8.0 || ^0.9.0 || ^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^14.0.0 || ^15.0.0 || ^16.0.0
dependencies:
graphql: 16.8.1
graphql: 16.7.1
tslib: 2.6.2
dev: false
/graphql-type-json@0.3.2(graphql@16.8.1):
/graphql-type-json@0.3.2(graphql@16.7.1):
resolution: {integrity: sha512-J+vjof74oMlCWXSvt0DOf2APEdZOCdubEvGDUAlqH//VBYcOYsGgRW7Xzorr44LvkjiuvecWc8fChxuZZbChtg==}
peerDependencies:
graphql: '>=0.8.0'
dependencies:
graphql: 16.8.1
graphql: 16.7.1
dev: false
/graphql@16.8.1:
resolution: {integrity: sha512-59LZHPdGZVh695Ud9lRzPBVTtlX9ZCV150Er2W43ro37wVof0ctenSaskPPjN7lVTIN8mSZt8PHUNKZuNQUuxw==}
/graphql@16.7.1:
resolution: {integrity: sha512-DRYR9tf+UGU0KOsMcKAlXeFfX89UiiIZ0dRU3mR0yJfu6OjZqUcp68NnFLnqQU5RexygFoDy1EW+ccOYcPfmHg==}
engines: {node: ^12.22.0 || ^14.16.0 || ^16.0.0 || >=17.0.0}
/gzip-size@6.0.0:
@@ -11095,6 +11106,19 @@ packages:
- supports-color
dev: true
/mongodb@4.16.0:
resolution: {integrity: sha512-0EB113Fsucaq1wsY0dOhi1fmZOwFtLOtteQkiqOXGklvWMnSH3g2QS53f0KTP+/6qOkuoXE2JksubSZNmxeI+g==}
engines: {node: '>=12.9.0'}
dependencies:
bson: 4.7.2
mongodb-connection-string-url: 2.6.0
socks: 2.7.1
optionalDependencies:
'@aws-sdk/credential-providers': 3.414.0
saslprep: 1.0.3
transitivePeerDependencies:
- aws-crt
/mongodb@4.17.1:
resolution: {integrity: sha512-MBuyYiPUPRTqfH2dV0ya4dcr2E5N52ocBuZ8Sgg/M030nGF78v855B3Z27mZJnp8PxjnUquEnAtjOsphgMZOlQ==}
engines: {node: '>=12.9.0'}
@@ -11107,6 +11131,7 @@ packages:
'@mongodb-js/saslprep': 1.1.0
transitivePeerDependencies:
- aws-crt
dev: true
/mongoose-aggregate-paginate-v2@1.0.6:
resolution: {integrity: sha512-UuALu+mjhQa1K9lMQvjLL3vm3iALvNw8PQNIh2gp1b+tO5hUa0NC0Wf6/8QrT9PSJVTihXaD8hQVy3J4e0jO0Q==}
@@ -11118,13 +11143,13 @@ packages:
engines: {node: '>=4.0.0'}
dev: false
/mongoose@6.12.0:
resolution: {integrity: sha512-sd/q83C6TBRPBrrD2A/POSbA/exbCFM2WOuY7Lf2JuIJFlHFG39zYSDTTAEiYlzIfahNOLmXPxBGFxdAch41Mw==}
/mongoose@6.11.4:
resolution: {integrity: sha512-q9NaW9/BBYZofx80SqlR7uoSR09CS3g02y+KMj1lNLUxcFFsPshupY3WWisNFauYG9gyuDF4L/RgyIK3obSghg==}
engines: {node: '>=12.0.0'}
dependencies:
bson: 4.7.2
kareem: 2.5.1
mongodb: 4.17.1
mongodb: 4.16.0
mpath: 0.9.0
mquery: 4.0.3
ms: 2.1.3
@@ -13520,6 +13545,7 @@ packages:
/resolve-pkg-maps@1.0.0:
resolution: {integrity: sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==}
dev: false
/resolve.exports@2.0.2:
resolution: {integrity: sha512-X2UW6Nw3n/aMgDVy+0rSqgHlv39WZAlZrXCdnbyEiKm17DSqHX4MmQMaST3FbeWR5FTuRcUwYAziZajji0Y7mg==}
@@ -13656,6 +13682,14 @@ packages:
truncate-utf8-bytes: 1.0.2
dev: false
/saslprep@1.0.3:
resolution: {integrity: sha512-/MY/PEMbk2SuY5sScONwhUDsV2p77Znkb/q3nSVstq/yQzYJOH/Azh29p9oJLsl3LnQwSvZDKagDGBsBwSooag==}
engines: {node: '>=6'}
requiresBuild: true
dependencies:
sparse-bitfield: 3.0.3
optional: true
/sass-loader@12.6.0(sass@1.64.0)(webpack@5.88.2):
resolution: {integrity: sha512-oLTaH0YCtX4cfnJZxKSLAyglED0naiYfNG1iXfU5w1LNZ+ukoA5DtyDIN5zmKVZwYNJP4KRc5Y3hkWga+7tYfA==}
engines: {node: '>= 12.13.0'}
@@ -14715,17 +14749,6 @@ packages:
typescript: 5.2.2
dev: false
/tsx@3.13.0:
resolution: {integrity: sha512-rjmRpTu3as/5fjNq/kOkOtihgLxuIz6pbKdj9xwP4J5jOLkBxw/rjN5ANw+KyrrOXV5uB7HC8+SrrSJxT65y+A==}
hasBin: true
dependencies:
esbuild: 0.18.20
get-tsconfig: 4.7.2
source-map-support: 0.5.21
optionalDependencies:
fsevents: 2.3.3
dev: true
/tunnel-agent@0.6.0:
resolution: {integrity: sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==}
dependencies:

View File

@@ -3,126 +3,89 @@ import { ExecSyncOptions, execSync } from 'child_process'
import chalk from 'chalk'
import prompts from 'prompts'
import minimist from 'minimist'
import chalkTemplate from 'chalk-template'
const execOpts: ExecSyncOptions = { stdio: 'inherit' }
const args = minimist(process.argv.slice(2))
async function main() {
const { _: packageNames, tag = 'latest', bump = 'patch' } = args
const args = minimist(process.argv.slice(2))
const { _: packageNames } = args
// If packageNames contains a comma, parse
if (packageNames[0]?.includes(',')) {
packageNames.length = 0
const splitNames = process.argv[2].split(',')
packageNames.push(...splitNames)
}
if (packageNames.length === 0) {
abort('Please specify a package to publish')
console.error('Please specify a package to publish')
process.exit(1)
}
if (packageNames.find((p) => p === 'payload' && packageNames.length > 1)) {
abort('Cannot publish payload with other packages')
if (packageNames.length > 1 && packageNames.find((p) => p === 'payload')) {
console.error(chalk.bold.red('Cannot publish payload with other packages'))
process.exit(1)
}
// Get current version of each package from package.json
const packageDetails = await Promise.all(
packageNames.map(async (packageName) => {
const packageDir = `packages/${packageName}`
if (!(await fse.pathExists(packageDir))) {
abort(`Package path ${packageDir} does not exist`)
}
const packageObj = await fse.readJson(`${packageDir}/package.json`)
console.log(`\n${chalk.bold.green('Publishing packages:')}\n`)
console.log(`${packageNames.map((p) => ` ${p}`).join('\n')}`)
console.log('\n')
return { name: packageName, version: packageObj.version, dir: packageDir }
}),
const { confirm } = await prompts(
{
name: 'confirm',
initial: false,
message: `Publish ${packageNames.length} package(s)?`,
type: 'confirm',
},
{
onCancel: () => {
console.log(chalk.bold.red('\nAborted'))
process.exit(0)
},
},
)
console.log(chalkTemplate`
{bold.green Publishing packages:}
{bold.yellow Bump: ${bump}}
{bold.yellow Tag: ${tag}}
${packageDetails.map((p) => ` ${p.name} - current: ${p.version}`).join('\n')}
`)
const confirmPublish = await confirm(`Publish ${packageNames.length} package(s)?`)
if (!confirmPublish) {
abort()
if (!confirm) {
console.log(chalk.bold.red('\nAborted\n'))
process.exit(0)
}
const results: { name: string; success: boolean }[] = []
for (const pkg of packageDetails) {
const { dir, name } = pkg
for (const packageName of packageNames) {
const packageDir = `packages/${packageName}`
try {
console.log(chalk.bold(`\n\nPublishing ${name}...\n\n`))
console.log(chalk.bold(`Publishing ${packageName}...`))
execSync(`npm --prefix ${packageDir} version pre --preid beta`, execOpts)
execSync(`git add ${packageDir}/package.json`, execOpts)
execSync(`npm --no-git-tag-version --prefix ${dir} version ${bump}`, execOpts)
execSync(`git add ${dir}/package.json`, execOpts)
const packageObj = await fse.readJson(`${dir}/package.json`)
const packageObj = await fse.readJson(`${packageDir}/package.json`)
const newVersion = packageObj.version
const tagName = `${name}/${newVersion}`
execSync(`git commit -m "chore(release): ${tagName}"`, execOpts)
execSync(`git tag -a ${tagName} -m "${tagName}"`, execOpts)
execSync(`pnpm publish -C ${dir} --no-git-checks`, execOpts)
results.push({ name, success: true })
execSync(`git commit -m "chore(release): ${packageName}@${newVersion}"`, execOpts)
execSync(`pnpm publish -C ${packageDir} --tag latest --no-git-checks`, execOpts)
results.push({ name: packageName, success: true })
} catch (error) {
console.error(chalk.bold.red(`ERROR: ${error.message}`))
results.push({ name, success: false })
console.error(`ERROR: ${error.message}`)
results.push({ name: packageName, success: false })
}
}
console.log(chalkTemplate`
{bold.green Results:}
${results
.map(({ name, success }) => ` ${success ? chalk.bold.green('✔') : chalk.bold.red('✘')} ${name}`)
.join('\n')}
`)
// Show unpushed commits and tags
execSync(
`git log --oneline $(git rev-parse --abbrev-ref --symbolic-full-name @{u})..HEAD`,
execOpts,
)
console.log('\n')
const push = await confirm(`Push commits and tags?`)
if (push) {
console.log(chalk.bold(`\n\nPushing commits and tags...\n\n`))
execSync(`git push --follow-tags`, execOpts)
}
console.log(chalk.bold.green(`\n\nDone!\n\n`))
console.log(`${chalk.bold('Results:')}\n`)
console.log(
results
.map(
({ name, success }) =>
` ${success ? chalk.bold.green('✔') : chalk.bold.red('✘')} ${name}`,
)
.join('\n'),
)
console.log('\n')
}
main().catch((error) => {
console.error(error)
process.exit(1)
})
async function abort(message = 'Abort', exitCode = 1) {
console.error(chalk.bold.red(`\n${message}\n`))
process.exit(exitCode)
}
async function confirm(message: string): Promise<boolean> {
const { confirm } = await prompts(
{
name: 'confirm',
initial: false,
message,
type: 'confirm',
},
{
onCancel: () => {
abort()
},
},
)
return confirm
}

View File

@@ -151,8 +151,6 @@ export default buildConfigWithDefaults({
type: 'text',
admin: {
position: 'sidebar',
description:
'This is a very long description that takes many characters to complete and hopefully will wrap instead of push the sidebar open, lorem ipsum dolor sit amet consectetur adipisicing elit. Quisquam, voluptatum voluptates. Quisquam, voluptatum voluptates.',
},
},
],

View File

@@ -42,11 +42,11 @@ describe('Auth', () => {
// language=graphQL
const query = `mutation {
loginUser(email: "${devUser.email}", password: "${devUser.password}") {
token
user {
id
email
}
token
user {
id
email
}
}
}`
const response = await client.request(query)
@@ -62,7 +62,7 @@ describe('Auth', () => {
it('should have fields saved to JWT', async () => {
const decoded = jwtDecode<User>(token)
const { collection, email: jwtEmail, exp, iat, roles } = decoded
const { email: jwtEmail, collection, roles, iat, exp } = decoded
expect(jwtEmail).toBeDefined()
expect(collection).toEqual('users')
@@ -132,19 +132,6 @@ describe('Auth', () => {
loggedInUser = data.user
})
it('should allow a user to change password without returning password', async () => {
const result = await payload.update({
id: loggedInUser.id,
collection: slug,
data: {
password: 'test',
},
})
expect(result.id).toStrictEqual(loggedInUser.id)
expect(result.password).toBeUndefined()
})
it('should return a logged in user from /me', async () => {
const response = await fetch(`${apiUrl}/${slug}/me`, {
headers: {
@@ -162,16 +149,16 @@ describe('Auth', () => {
it('should have fields saved to JWT', async () => {
const decoded = jwtDecode<User>(token)
const {
collection,
email: jwtEmail,
exp,
iat,
collection,
roles,
[saveToJWTKey]: customJWTPropertyKey,
tabLiftedSaveToJWT,
unnamedTabSaveToJWTFalse,
'x-lifted-from-group': liftedFromGroup,
'x-tab-field': unnamedTabSaveToJWTString,
tabLiftedSaveToJWT,
unnamedTabSaveToJWTFalse,
iat,
exp,
} = decoded
const group = decoded['x-group'] as Record<string, unknown>
@@ -203,9 +190,9 @@ describe('Auth', () => {
const user = await payload.create({
collection: slug,
data: {
apiKey,
email: 'dev@example.com',
password: 'test',
apiKey,
},
})
@@ -225,10 +212,10 @@ describe('Auth', () => {
it('should refresh a token and reset its expiration', async () => {
const response = await fetch(`${apiUrl}/${slug}/refresh-token`, {
method: 'post',
headers: {
Authorization: `JWT ${token}`,
},
method: 'post',
})
const data = await response.json()
@@ -241,18 +228,18 @@ describe('Auth', () => {
expect(loggedInUser?.custom).toBe('Hello, world!')
await payload.update({
id: loggedInUser?.id || '',
collection: slug,
id: loggedInUser?.id || '',
data: {
custom: 'Goodbye, world!',
},
})
const response = await fetch(`${apiUrl}/${slug}/refresh-token`, {
method: 'post',
headers: {
Authorization: `JWT ${token}`,
},
method: 'post',
})
const data = await response.json()
@@ -316,7 +303,7 @@ describe('Auth', () => {
},
})
const { _verificationToken, _verified } = userResult.docs[0]
const { _verified, _verificationToken } = userResult.docs[0]
expect(_verified).toBe(false)
expect(_verificationToken).toBeDefined()
@@ -344,7 +331,7 @@ describe('Auth', () => {
},
})
const { _verificationToken: afterToken, _verified: afterVerified } =
const { _verified: afterVerified, _verificationToken: afterToken } =
afterVerifyResult.docs[0]
expect(afterVerified).toBe(true)
expect(afterToken).toBeNull()
@@ -387,8 +374,8 @@ describe('Auth', () => {
password,
}),
headers: {
Authorization: `JWT ${token}`,
'Content-Type': 'application/json',
Authorization: `JWT ${token}`,
},
method: 'post',
})
@@ -409,7 +396,7 @@ describe('Auth', () => {
},
})
const { lockUntil, loginAttempts } = userResult.docs[0]
const { loginAttempts, lockUntil } = userResult.docs[0]
expect(loginAttempts).toBe(2)
expect(lockUntil).toBeDefined()
@@ -422,14 +409,14 @@ describe('Auth', () => {
await payload.update({
collection: slug,
data: {
lockUntil: Date.now() - 605 * 1000,
},
where: {
email: {
equals: userEmail,
},
},
data: {
lockUntil: Date.now() - 605 * 1000,
},
})
// login
@@ -456,7 +443,7 @@ describe('Auth', () => {
},
})
const { lockUntil, loginAttempts } = userResult.docs[0]
const { loginAttempts, lockUntil } = userResult.docs[0]
expect(loginAttempts).toBe(0)
expect(lockUntil).toBeNull()
@@ -467,13 +454,13 @@ describe('Auth', () => {
it('should allow forgot-password by email', async () => {
// TODO: Spy on payload sendEmail function
const response = await fetch(`${apiUrl}/${slug}/forgot-password`, {
method: 'post',
body: JSON.stringify({
email,
}),
headers: {
'Content-Type': 'application/json',
},
method: 'post',
})
// expect(mailSpy).toHaveBeenCalled();
@@ -508,10 +495,10 @@ describe('Auth', () => {
const user = await payload.create({
collection: slug,
data: {
adminOnlyField: 'admin secret',
email: 'insecure@me.com',
password: 'test',
roles: ['admin'],
adminOnlyField: 'admin secret',
},
})
@@ -533,8 +520,8 @@ describe('Auth', () => {
expect(adminMe.user.adminOnlyField).toEqual('admin secret')
await payload.update({
id: user?.id || '',
collection: slug,
id: user?.id || '',
data: {
roles: ['editor'],
},
@@ -559,8 +546,8 @@ describe('Auth', () => {
const success = await fetch(`${apiUrl}/api-keys/${user2.id}`, {
headers: {
Authorization: `api-keys API-Key ${user2.apiKey}`,
'Content-Type': 'application/json',
Authorization: `api-keys API-Key ${user2.apiKey}`,
},
}).then((res) => res.json())
@@ -568,8 +555,8 @@ describe('Auth', () => {
const fail = await fetch(`${apiUrl}/api-keys/${user1.id}`, {
headers: {
Authorization: `api-keys API-Key ${user2.apiKey}`,
'Content-Type': 'application/json',
Authorization: `api-keys API-Key ${user2.apiKey}`,
},
})

View File

@@ -10,6 +10,8 @@ export const AddCustomBlocks: React.FC = () => {
const { addFieldRow, replaceFieldRow } = useForm()
const { value } = useField({ path: 'customBlocks' })
const nextIndex = Array.isArray(value) ? value.length : 0
return (
<div className={baseClass}>
<div className={`${baseClass}__blocks-grid`}>
@@ -19,6 +21,7 @@ export const AddCustomBlocks: React.FC = () => {
addFieldRow({
data: { block1Title: 'Block 1: Prefilled Title', blockType: 'block-1' },
path: 'customBlocks',
rowIndex: nextIndex,
})
}
type="button"
@@ -32,6 +35,7 @@ export const AddCustomBlocks: React.FC = () => {
addFieldRow({
data: { block2Title: 'Block 2: Prefilled Title', blockType: 'block-2' },
path: 'customBlocks',
rowIndex: nextIndex,
})
}
type="button"
@@ -47,12 +51,12 @@ export const AddCustomBlocks: React.FC = () => {
replaceFieldRow({
data: { block1Title: 'REPLACED BLOCK', blockType: 'block-1' },
path: 'customBlocks',
rowIndex: (Array.isArray(value) ? value.length : 0) - 1,
rowIndex: nextIndex - 1,
})
}
type="button"
>
Replace Block {Array.isArray(value) ? value.length : 0}
Replace Block {nextIndex}
</button>
</div>
</div>

View File

@@ -1,7 +1,8 @@
import type { CollectionConfig } from '../../../../packages/payload/src/collections/config/types'
import { CollapsibleLabelComponent } from './LabelComponent'
import { collapsibleFieldsSlug } from './shared'
export const collapsibleFieldsSlug = 'collapsible-fields'
const CollapsibleFields: CollectionConfig = {
slug: collapsibleFieldsSlug,

View File

@@ -1 +0,0 @@
export const collapsibleFieldsSlug = 'collapsible-fields'

View File

@@ -122,30 +122,12 @@ const SelectFields: CollectionConfig = {
type: 'select',
options: ['One', 'Two', 'Three'],
},
{
type: 'group',
name: 'settings',
fields: [
{
name: 'category',
type: 'select',
hasMany: true,
options: [
{ value: 'a', label: 'A' },
{ value: 'b', label: 'B' },
],
},
],
},
],
}
export const selectsDoc = {
select: 'one',
selectHasMany: ['two', 'four'],
settings: {
category: ['a'],
},
}
export default SelectFields

View File

@@ -9,7 +9,7 @@ import wait from '../../packages/payload/src/utilities/wait'
import { saveDocAndAssert, saveDocHotkeyAndAssert } from '../helpers'
import { AdminUrlUtil } from '../helpers/adminUrlUtil'
import { initPayloadE2E } from '../helpers/configHelpers'
import { collapsibleFieldsSlug } from './collections/Collapsible/shared'
import { collapsibleFieldsSlug } from './collections/Collapsible'
import { jsonDoc } from './collections/JSON'
import { numberDoc } from './collections/Number'
import { pointFieldsSlug } from './collections/Point'

View File

@@ -1,48 +0,0 @@
import type { Page } from '@playwright/test'
import { expect, test } from '@playwright/test'
import { saveDocAndAssert } from '../helpers'
import { AdminUrlUtil } from '../helpers/adminUrlUtil'
import { initPayloadTest } from '../helpers/configHelpers'
const { beforeAll, describe } = test
let url: AdminUrlUtil
const slug = 'nested-fields'
let page: Page
describe('Nested Fields', () => {
beforeAll(async ({ browser }) => {
const { serverURL } = await initPayloadTest({
__dirname,
init: {
local: false,
},
})
url = new AdminUrlUtil(serverURL, slug)
const context = await browser.newContext()
page = await context.newPage()
})
test('should save deeply nested fields', async () => {
const assertionValue = 'sample block value'
await page.goto(url.create)
await page.locator('#field-array > button').click()
await page.locator('#field-array__0__group__namedTab__blocks > button').click()
await page.locator('button[title="Block With Field"]').click()
await page.locator('#field-array__0__group__namedTab__blocks__0__text').fill(assertionValue)
await saveDocAndAssert(page)
await expect(page.locator('#field-array__0__group__namedTab__blocks__0__text')).toHaveValue(
assertionValue,
)
})
})

View File

@@ -6,16 +6,16 @@ import Posts from './collections/Posts'
import VersionPosts from './collections/Versions'
import AutosaveGlobal from './globals/Autosave'
import DraftGlobal from './globals/Draft'
import { draftSlug, titleToDelete } from './shared'
import { draftSlug } from './shared'
export default buildConfigWithDefaults({
collections: [Posts, AutosavePosts, DraftPosts, VersionPosts],
globals: [AutosaveGlobal, DraftGlobal],
indexSortableFields: true,
localization: {
defaultLocale: 'en',
locales: ['en', 'es'],
defaultLocale: 'en',
},
indexSortableFields: true,
onInit: async (payload) => {
await payload.create({
collection: 'users',
@@ -27,52 +27,43 @@ export default buildConfigWithDefaults({
const { id: draftID } = await payload.create({
collection: draftSlug,
draft: true,
data: {
id: 1,
title: 'draft title',
description: 'draft description',
radio: 'test',
title: 'draft title',
},
draft: true,
})
await payload.create({
collection: draftSlug,
draft: false,
data: {
id: 2,
_status: 'published',
title: 'published title',
description: 'published description',
radio: 'test',
title: 'published title',
_status: 'published',
},
draft: false,
})
await payload.create({
collection: draftSlug,
data: {
description: 'published description',
title: titleToDelete,
},
draft: true,
})
await payload.update({
id: draftID,
collection: draftSlug,
id: draftID,
draft: true,
data: {
title: 'draft title 2',
},
draft: true,
})
await payload.update({
id: draftID,
collection: draftSlug,
id: draftID,
draft: true,
data: {
title: 'draft title 3',
},
draft: true,
})
},
})

View File

@@ -31,7 +31,7 @@ import wait from '../../packages/payload/src/utilities/wait'
import { changeLocale } from '../helpers'
import { AdminUrlUtil } from '../helpers/adminUrlUtil'
import { initPayloadE2E } from '../helpers/configHelpers'
import { autosaveSlug, draftSlug, titleToDelete } from './shared'
import { autosaveSlug, draftSlug } from './shared'
const { beforeAll, describe } = test
@@ -53,24 +53,6 @@ describe('versions', () => {
url = new AdminUrlUtil(serverURL, draftSlug)
})
// This test has to run before bulk updates that will rename the title
test('should delete', async () => {
await page.goto(url.list)
const rows = page.locator(`tr`)
const rowToDelete = rows.filter({ hasText: titleToDelete })
await rowToDelete.locator('.cell-_select input').click()
await page.locator('.delete-documents__toggle').click()
await page.locator('#confirm-delete').click()
await expect(page.locator('.Toastify__toast--success')).toContainText(
'Deleted 1 Draft Post successfully.',
)
await expect(page.locator('.row-1 .cell-title')).not.toHaveText(titleToDelete)
})
test('should bulk publish', async () => {
await page.goto(url.list)
@@ -110,7 +92,7 @@ describe('versions', () => {
await page.locator('.form-submit .edit-many__publish').click()
await expect(page.locator('.Toastify__toast--success')).toContainText(
'Draft Posts successfully.',
'Updated 2 Draft Posts successfully.',
)
await expect(page.locator('.row-1 .cell-_status')).toContainText('Published')
await expect(page.locator('.row-2 .cell-_status')).toContainText('Published')
@@ -129,7 +111,7 @@ describe('versions', () => {
await page.locator('.form-submit .edit-many__draft').click()
await expect(page.locator('.Toastify__toast--success')).toContainText(
'Draft Posts successfully.',
'Updated 2 Draft Posts successfully.',
)
await expect(page.locator('.row-1 .cell-_status')).toContainText('Draft')
await expect(page.locator('.row-2 .cell-_status')).toContainText('Draft')

View File

@@ -6,7 +6,6 @@ import { initPayloadTest } from '../helpers/configHelpers'
import AutosavePosts from './collections/Autosave'
import configPromise from './config'
import AutosaveGlobal from './globals/Autosave'
import { autosaveSlug, draftSlug } from './shared'
let collectionLocalPostID: string
let collectionLocalVersionID
@@ -57,8 +56,8 @@ describe('Versions', () => {
// First: delete potential existing versions from previous tests
if (collectionLocalPostID) {
await payload.delete({
id: collectionLocalPostID,
collection,
id: collectionLocalPostID,
})
}
@@ -66,8 +65,8 @@ describe('Versions', () => {
const autosavePost = await payload.create({
collection,
data: {
description: '345j23o4ifj34jf54g',
title: 'Here is an autosave post in EN',
description: '345j23o4ifj34jf54g',
},
})
collectionLocalPostID = autosavePost.id
@@ -92,23 +91,10 @@ describe('Versions', () => {
describe('Collections - Local', () => {
describe('Create', () => {
it('should allow creating a draft with missing required field data', async () => {
const draft = await payload.create({
collection: autosaveSlug,
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,
id: collectionLocalPostID,
})
expect(updatedPost.title).toBe(updatedTitle)
expect(updatedPost._status).toStrictEqual('draft')
@@ -119,8 +105,8 @@ describe('Versions', () => {
const autosavePost = await payload.create({
collection,
data: {
description: 'description 1',
title: 'unique unchanging title',
description: 'description 1',
},
})
@@ -147,8 +133,8 @@ describe('Versions', () => {
it('should allow a version to be retrieved by ID', async () => {
const version = await payload.findVersionByID({
id: collectionLocalVersionID,
collection,
id: collectionLocalVersionID,
})
expect(version.id).toStrictEqual(collectionLocalVersionID)
@@ -159,20 +145,20 @@ describe('Versions', () => {
const spanishTitle = 'Title in ES'
await payload.update({
id: collectionLocalPostID,
collection,
id: collectionLocalPostID,
data: {
title: englishTitle,
},
})
const updatedPostES = await payload.update({
id: collectionLocalPostID,
collection,
id: collectionLocalPostID,
locale: 'es',
data: {
title: spanishTitle,
},
locale: 'es',
})
expect(updatedPostES.title).toBe(spanishTitle)
@@ -180,8 +166,8 @@ describe('Versions', () => {
const newEnglishTitle = 'New title in EN'
await payload.update({
id: collectionLocalPostID,
collection,
id: collectionLocalPostID,
data: {
title: newEnglishTitle,
},
@@ -200,44 +186,6 @@ describe('Versions', () => {
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: draftSlug,
draft: true,
sort: 'title',
})
const draftsDescending = await payload.find({
collection: draftSlug,
draft: true,
sort: '-title',
})
expect(draftsAscending).toBeDefined()
expect(draftsDescending).toBeDefined()
expect(draftsAscending.docs[0]).toMatchObject(
draftsDescending.docs[draftsDescending.docs.length - 1],
)
})
it('should findVersions with sort', async () => {
const draftsAscending = await payload.findVersions({
collection: draftSlug,
draft: true,
sort: 'createdAt',
})
const draftsDescending = await payload.findVersions({
collection: draftSlug,
draft: true,
sort: '-updatedAt',
})
expect(draftsAscending).toBeDefined()
expect(draftsDescending).toBeDefined()
expect(draftsAscending.docs[0]).toMatchObject(
draftsDescending.docs[draftsDescending.docs.length - 1],
)
})
})
describe('Restore', () => {
@@ -245,14 +193,14 @@ describe('Versions', () => {
const somePost = await payload.create({
collection,
data: {
description: 'description 1',
title: 'first post',
description: 'description 1',
},
})
const updatedPost = await payload.update({
id: collectionLocalPostID,
collection,
id: collectionLocalPostID,
data: {
title: 'This should be the latest version',
},
@@ -268,8 +216,8 @@ describe('Versions', () => {
const title2 = 'Another updated post title in EN'
const updatedPost = await payload.update({
id: collectionLocalPostID,
collection,
id: collectionLocalPostID,
data: {
title: title2,
},
@@ -279,8 +227,8 @@ describe('Versions', () => {
// Make sure it was updated correctly
const draftFromUpdatedPost = await payload.findByID({
id: collectionLocalPostID,
collection,
id: collectionLocalPostID,
draft: true,
})
expect(draftFromUpdatedPost.title).toBe(title2)
@@ -291,15 +239,15 @@ describe('Versions', () => {
// restore to latest version
const restoredVersion = await payload.restoreVersion({
id: versions.docs[1].id,
collection,
id: versions.docs[1].id,
})
expect(restoredVersion.title).toBeDefined()
const latestDraft = await payload.findByID({
id: collectionLocalPostID,
collection,
id: collectionLocalPostID,
draft: true,
})
@@ -314,9 +262,9 @@ describe('Versions', () => {
const originalPublishedPost = await payload.create({
collection,
data: {
_status: 'published',
description: 'kjnjyhbbdsfseankuhsjsfghb',
title: originalTitle,
description: 'kjnjyhbbdsfseankuhsjsfghb',
_status: 'published',
},
})
@@ -325,11 +273,11 @@ describe('Versions', () => {
await payload.update({
id: originalPublishedPost.id,
collection,
locale: 'en',
data: {
title: patchedTitle,
},
draft: true,
locale: 'en',
})
const spanishTitle = 'es title'
@@ -338,23 +286,23 @@ describe('Versions', () => {
await payload.update({
id: originalPublishedPost.id,
collection,
locale: 'es',
data: {
title: spanishTitle,
},
draft: true,
locale: 'es',
})
const publishedPost = await payload.findByID({
id: originalPublishedPost.id,
collection,
id: originalPublishedPost.id,
})
const draftPost = await payload.findByID({
id: originalPublishedPost.id,
collection,
draft: true,
locale: 'all',
id: originalPublishedPost.id,
draft: true,
})
expect(publishedPost.title).toBe(originalTitle)
@@ -362,86 +310,44 @@ describe('Versions', () => {
expect(draftPost.title.es).toBe(spanishTitle)
})
})
describe('Delete', () => {
let postToDelete
beforeAll(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: {
id: {
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',
draft: true,
data: {
_status: 'draft',
description: 'A',
title: 'A',
description: 'A',
_status: 'draft',
},
draft: true,
})
await payload.update({
id: originalDraft.id,
collection: 'draft-posts',
id: originalDraft.id,
draft: true,
data: {
_status: 'draft',
description: 'B',
title: 'B',
description: 'B',
_status: 'draft',
},
draft: true,
})
await payload.update({
id: originalDraft.id,
collection: 'draft-posts',
data: {
_status: 'draft',
description: 'C',
title: 'C',
},
id: originalDraft.id,
draft: true,
data: {
title: 'C',
description: 'C',
_status: 'draft',
},
})
const mostRecentDraft = await payload.findByID({
id: originalDraft.id,
collection: 'draft-posts',
id: originalDraft.id,
draft: true,
})
@@ -467,52 +373,52 @@ describe('Versions', () => {
const doc1 = await payload.create({
collection: 'version-posts',
data: {
description: 'A',
title: 'A',
description: 'A',
},
})
await payload.update({
id: doc1.id,
collection: 'version-posts',
id: doc1.id,
data: {
description: 'B',
title: 'B',
description: 'B',
},
})
await payload.update({
id: doc1.id,
collection: 'version-posts',
id: doc1.id,
data: {
description: 'C',
title: 'C',
description: 'C',
},
})
const doc2 = await payload.create({
collection: 'version-posts',
data: {
description: 'D',
title: 'D',
description: 'D',
},
})
await payload.update({
id: doc2.id,
collection: 'version-posts',
id: doc2.id,
data: {
description: 'E',
title: 'E',
description: 'E',
},
})
await payload.update({
id: doc2.id,
collection: 'version-posts',
id: doc2.id,
data: {
description: 'F',
title: 'F',
description: 'F',
},
})
@@ -567,31 +473,31 @@ describe('Versions', () => {
firstDraft = await payload.create({
collection: 'draft-posts',
data: {
title: originalTitle,
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',
id: firstDraft.id,
draft: true,
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',
id: firstDraft.id,
draft: true,
data: {
title: updatedTitle2,
},
draft: true,
})
})
@@ -677,8 +583,8 @@ describe('Versions', () => {
// First: delete potential existing versions from previous tests
if (collectionGraphQLPostID) {
await payload.delete({
id: collectionGraphQLPostID,
collection,
id: collectionGraphQLPostID,
})
}
@@ -730,25 +636,25 @@ describe('Versions', () => {
// modify the post to create a new version
// language=graphQL
const update = `mutation {
updateAutosavePost(id: ${formatGraphQLID(
collectionGraphQLPostID,
)}, data: {title: "${updatedTitle2}"}) {
title
updatedAt
createdAt
}
updateAutosavePost(id: ${formatGraphQLID(
collectionGraphQLPostID,
)}, data: {title: "${updatedTitle2}"}) {
title
updatedAt
createdAt
}
}`
await graphQLClient.request(update)
// language=graphQL
const query = `query {
versionsAutosavePosts(where: { parent: { equals: ${formatGraphQLID(
collectionGraphQLPostID,
)} } }) {
docs {
id
}
versionsAutosavePosts(where: { parent: { equals: ${formatGraphQLID(
collectionGraphQLPostID,
)} } }) {
docs {
id
}
}
}`
const response = await graphQLClient.request(query)
@@ -781,17 +687,17 @@ describe('Versions', () => {
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
}
}
versionsAutosavePosts(where: { version__title: {equals: "${collectionGraphQLOriginalTitle}" } }) {
docs {
id
parent {
id
}
version {
title
}
}
}
}`
const response = await graphQLClient.request(query)
@@ -810,25 +716,25 @@ describe('Versions', () => {
// modify the post to create a new version
// language=graphQL
const update = `mutation {
updateAutosavePost(id: ${formatGraphQLID(
collectionGraphQLPostID,
)}, data: {title: "${collectionGraphQLOriginalTitle}"}) {
title
updatedAt
createdAt
}
updateAutosavePost(id: ${formatGraphQLID(
collectionGraphQLPostID,
)}, data: {title: "${collectionGraphQLOriginalTitle}"}) {
title
updatedAt
createdAt
}
}`
await graphQLClient.request(update)
// language=graphQL
const query = `query {
versionsAutosavePosts(where: { parent: { equals: ${formatGraphQLID(
collectionGraphQLPostID,
)} } }) {
docs {
id
}
versionsAutosavePosts(where: { parent: { equals: ${formatGraphQLID(
collectionGraphQLPostID,
)} } }) {
docs {
id
}
}
}`
const response = await graphQLClient.request(query)
@@ -874,17 +780,17 @@ describe('Versions', () => {
beforeEach(async () => {
const title2 = 'Here is an updated global title in EN'
await payload.updateGlobal({
slug: globalSlug,
data: {
title: 'Test Global',
},
slug: globalSlug,
})
const updatedGlobal = await payload.updateGlobal({
slug: globalSlug,
data: {
title: title2,
},
slug: globalSlug,
})
const versions = await payload.findGlobalVersions({
@@ -908,8 +814,8 @@ describe('Versions', () => {
describe('Read', () => {
it('should allow a version to be retrieved by ID', async () => {
const version = await payload.findGlobalVersionByID({
id: globalLocalVersionID,
slug: globalSlug,
id: globalLocalVersionID,
})
expect(version.id).toStrictEqual(globalLocalVersionID)
@@ -922,18 +828,18 @@ describe('Versions', () => {
const spanishTitle = 'Title in ES'
await payload.updateGlobal({
slug: globalSlug,
data: {
title: englishTitle,
},
slug: globalSlug,
})
const updatedGlobalES = await payload.updateGlobal({
slug: globalSlug,
locale: 'es',
data: {
title: spanishTitle,
},
locale: 'es',
slug: globalSlug,
})
expect(updatedGlobalES.title).toBe(spanishTitle)
@@ -941,15 +847,15 @@ describe('Versions', () => {
const newEnglishTitle = 'New title in EN'
await payload.updateGlobal({
slug: globalSlug,
data: {
title: newEnglishTitle,
},
slug: globalSlug,
})
const versions = await payload.findGlobalVersions({
locale: 'all',
slug: globalSlug,
locale: 'all',
})
expect(versions.docs[0].version.title.en).toStrictEqual(newEnglishTitle)
@@ -962,18 +868,18 @@ describe('Versions', () => {
const title2 = 'Another updated title in EN'
const updatedGlobal = await payload.updateGlobal({
slug: globalSlug,
data: {
title: title2,
},
slug: globalSlug,
})
expect(updatedGlobal.title).toBe(title2)
// Make sure it was updated correctly
const foundUpdatedGlobal = await payload.findGlobal({
draft: true,
slug: globalSlug,
draft: true,
})
expect(foundUpdatedGlobal.title).toBe(title2)
@@ -984,15 +890,15 @@ describe('Versions', () => {
globalLocalVersionID = versions.docs[1].id
const restore = await payload.restoreGlobalVersion({
id: globalLocalVersionID,
slug: globalSlug,
id: globalLocalVersionID,
})
expect(restore.title).toBeDefined()
const restoredGlobal = await payload.findGlobal({
draft: true,
slug: globalSlug,
draft: true,
})
expect(restoredGlobal.title).toBe(restore.title)
@@ -1004,43 +910,43 @@ describe('Versions', () => {
const originalTitle = 'Here is a published global'
await payload.updateGlobal({
data: {
_status: 'published',
description: 'kjnjyhbbdsfseankuhsjsfghb',
title: originalTitle,
},
slug: globalSlug,
data: {
title: originalTitle,
description: 'kjnjyhbbdsfseankuhsjsfghb',
_status: 'published',
},
})
const publishedGlobal = await payload.findGlobal({
draft: true,
slug: globalSlug,
draft: true,
})
const updatedTitle2 = 'Here is a draft global with a patched title'
await payload.updateGlobal({
slug: globalSlug,
locale: 'en',
data: {
title: updatedTitle2,
},
draft: true,
locale: 'en',
slug: globalSlug,
})
await payload.updateGlobal({
slug: globalSlug,
locale: 'es',
data: {
title: updatedTitle2,
},
draft: true,
locale: 'es',
slug: globalSlug,
})
const updatedGlobal = await payload.findGlobal({
draft: true,
locale: 'all',
slug: globalSlug,
locale: 'all',
draft: true,
})
expect(publishedGlobal.title).toBe(originalTitle)
@@ -1052,22 +958,22 @@ describe('Versions', () => {
const originalTitle = 'Here is a draft'
await payload.updateGlobal({
slug: globalSlug,
data: {
_status: 'draft',
title: originalTitle,
_status: 'draft',
},
draft: true,
slug: globalSlug,
})
const updatedTitle2 = 'Now try to publish'
const result = await payload.updateGlobal({
data: {
_status: 'published',
title: updatedTitle2,
},
slug: globalSlug,
data: {
title: updatedTitle2,
_status: 'published',
},
})
expect(result.title).toBe(updatedTitle2)
@@ -1079,25 +985,25 @@ describe('Versions', () => {
beforeAll(async () => {
// language=graphql
const update = `mutation {
updateAutosaveGlobal(draft: true, data: {
title: "${globalGraphQLOriginalTitle}"
}) {
_status
title
}
updateAutosaveGlobal(draft: true, data: {
title: "${globalGraphQLOriginalTitle}"
}) {
_status
title
}
}`
await graphQLClient.request(update)
// language=graphQL
const query = `query {
versionsAutosaveGlobal(where: { version__title: { equals: "${globalGraphQLOriginalTitle}" } }) {
docs {
id
version {
title
}
}
versionsAutosaveGlobal(where: { version__title: { equals: "${globalGraphQLOriginalTitle}" } }) {
docs {
id
version {
title
}
}
}
}`
const response = await graphQLClient.request(query)
@@ -1108,12 +1014,12 @@ describe('Versions', () => {
it('should allow read of versions by version id', async () => {
// language=graphql
const query = `query {
versionAutosaveGlobal(id: ${formatGraphQLID(globalGraphQLVersionID)}) {
id
version {
title
}
versionAutosaveGlobal(id: ${formatGraphQLID(globalGraphQLVersionID)}) {
id
version {
title
}
}
}`
const response = await graphQLClient.request(query)
@@ -1127,14 +1033,14 @@ describe('Versions', () => {
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
}
}
versionsAutosaveGlobal(where: { version__title: {equals: "${globalGraphQLOriginalTitle}" } }) {
docs {
id
version {
title
}
}
}
}`
const response = await graphQLClient.request(query)
@@ -1151,9 +1057,9 @@ describe('Versions', () => {
it('should allow a version to be restored', async () => {
// language=graphql
const restore = `mutation {
restoreVersionAutosaveGlobal(id: ${formatGraphQLID(globalGraphQLVersionID)}) {
title
}
restoreVersionAutosaveGlobal(id: ${formatGraphQLID(globalGraphQLVersionID)}) {
title
}
}`
await graphQLClient.request(restore)

View File

@@ -5,5 +5,3 @@ export const versionSlug = 'version-posts'
export const autoSaveGlobalSlug = 'autosave-global'
export const draftGlobalSlug = 'draft-global'
export const titleToDelete = 'title to delete'