Merge branch '2.0' of github.com:payloadcms/payload into 2.0

This commit is contained in:
James
2023-10-08 14:57:14 -04:00
12 changed files with 57 additions and 220 deletions

View File

@@ -6,17 +6,17 @@ desc: Structure your Collections for your needs by defining fields, adding slugs
keywords: collections, config, configuration, documentation, Content Management System, cms, headless, javascript, node, react, express
---
Payload Collections are defined through configs of their own, and you can define as many as your application needs. Each Collection will scaffold a new collection automatically in your database of choice, based on fields that you define.
Payload Collections are defined through configs of their own, and you can define as many as your application needs. Each
Collection will scaffold a new collection automatically in your database of choice, based on fields that you define.
It's often best practice to write your Collections in separate files and then import them into the main Payload config.
## Options
| Option | Description |
| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|-------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| **`slug`** \* | Unique, URL-friendly string that will act as an identifier for this Collection. |
| **`fields`** \* | Array of field types that will determine the structure and functionality of the data stored within this Collection. [Click here](/docs/fields/overview) for a full list of field types as well as how to configure them. |
| **`indexes`** \* | Array of database indexes to create, including compound indexes that have multiple fields. |
| **`labels`** | Singular and plural labels for use in identifying this Collection throughout Payload. Auto-generated from slug if not defined. |
| **`admin`** | Admin-specific configuration. See below for [more detail](#admin-options). |
| **`hooks`** | Entry points to "tie in" to Collection actions at specific points. [More](/docs/hooks/overview#collection-hooks) |
@@ -59,14 +59,17 @@ export const Orders: CollectionConfig = {
#### More collection config examples
You can find an assortment of [example collection configs](https://github.com/payloadcms/public-demo/tree/master/src/collections) in the Public Demo source code on GitHub.
You can find an assortment
of [example collection configs](https://github.com/payloadcms/public-demo/tree/master/src/collections) in the Public
Demo source code on GitHub.
### Admin options
You can customize the way that the Admin panel behaves on a collection-by-collection basis by defining the `admin` property on a collection's config.
You can customize the way that the Admin panel behaves on a collection-by-collection basis by defining the `admin`
property on a collection's config.
| Option | Description |
| ---------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `group` | Text used as a label for grouping collection and global links together in the navigation. |
| `hidden` | Set to true or a function, called with the current user, returning true to exclude this collection from navigation and admin routing. |
| `hooks` | Admin-specific hooks for this collection. [More](#admin-hooks) |
@@ -84,9 +87,11 @@ You can customize the way that the Admin panel behaves on a collection-by-collec
### Preview
Collection `admin` options can accept a `preview` function that will be used to generate a link pointing to the frontend of your app to preview data.
Collection `admin` options can accept a `preview` function that will be used to generate a link pointing to the frontend
of your app to preview data.
If the function is specified, a Preview button will automatically appear in the corresponding collection's Edit view. Clicking the Preview button will link to the URL that is generated by the function.
If the function is specified, a Preview button will automatically appear in the corresponding collection's Edit view.
Clicking the Preview button will link to the URL that is generated by the function.
**The preview function accepts two arguments:**
@@ -124,27 +129,36 @@ export const Posts: CollectionConfig = {
Here are a few options that you can specify options for pagination on a collection-by-collection basis:
| Option | Description |
| -------------- | --------------------------------------------------------------------------------------------------- |
|----------------|-----------------------------------------------------------------------------------------------------|
| `defaultLimit` | Integer that specifies the default per-page limit that should be used. Defaults to 10. |
| `limits` | Provide an array of integers to use as per-page options for admins to choose from in the List view. |
### Access control
You can specify extremely granular access control (what users can do with documents in a collection) on a collection by collection basis. To learn more, go to the [Access Control](/docs/access-control/overview) docs.
You can specify extremely granular access control (what users can do with documents in a collection) on a collection by
collection basis. To learn more, go to the [Access Control](/docs/access-control/overview) docs.
### Hooks
Hooks are a powerful way to extend collection functionality and execute your own logic, and can be defined on a collection by collection basis. To learn more, go to the [Hooks](/docs/hooks/overview) documentation.
Hooks are a powerful way to extend collection functionality and execute your own logic, and can be defined on a
collection by collection basis. To learn more, go to the [Hooks](/docs/hooks/overview) documentation.
### Field types
Collections support all field types that Payload has to offer—including simple fields like text and checkboxes all the way to more complicated layout-building field groups like Blocks. [Click here](/docs/fields/overview) to learn more about field types.
Collections support all field types that Payload has to offer—including simple fields like text and checkboxes all the
way to more complicated layout-building field groups like Blocks. [Click here](/docs/fields/overview) to learn more
about field types.
### List Searchable Fields
In the List view, there is a "search" box that allows you to quickly find a document with a search. By default, it searches on the ID field. If you have `admin.useAsTitle` defined, the list search will use that field. However, you can define more than one field to search to make it easier on your admin editors to find the data they need.
In the List view, there is a "search" box that allows you to quickly find a document with a search. By default, it
searches on the ID field. If you have `admin.useAsTitle` defined, the list search will use that field. However, you can
define more than one field to search to make it easier on your admin editors to find the data they need.
For example, let's say you have a Posts collection with `title`, `metaDescription`, and `tags` fields - and you want all three of those fields to be searchable in the List view. You can simply add `admin.listSearchableFields: ['title', 'metaDescription', 'tags']` - and the admin UI will automatically search on those three fields plus the ID field.
For example, let's say you have a Posts collection with `title`, `metaDescription`, and `tags` fields - and you want all
three of those fields to be searchable in the List view. You can simply
add `admin.listSearchableFields: ['title', 'metaDescription', 'tags']` - and the admin UI will automatically search on
those three fields plus the ID field.
<Banner type="warning">
<strong>Note:</strong>
@@ -159,7 +173,10 @@ In addition to collection hooks themselves, Payload provides for admin UI-specif
**`beforeDuplicate`**
The `beforeDuplicate` hook is an async function that accepts an object containing the data to duplicate, as well as the locale of the doc to duplicate. Within this hook, you can modify the data to be duplicated, which is useful in cases where you have unique fields that need to be incremented or similar, as well as if you want to automatically modify a document's `title`.
The `beforeDuplicate` hook is an async function that accepts an object containing the data to duplicate, as well as the
locale of the doc to duplicate. Within this hook, you can modify the data to be duplicated, which is useful in cases
where you have unique fields that need to be incremented or similar, as well as if you want to automatically modify a
document's `title`.
Example:

View File

@@ -6,9 +6,11 @@ import type { SanitizedCollectionConfig } from 'payload/types'
import mongoose from 'mongoose'
import mongooseAggregatePaginate from 'mongoose-aggregate-paginate-v2'
import paginate from 'mongoose-paginate-v2'
import { buildVersionGlobalFields } from 'payload/versions'
import { buildVersionCollectionFields } from 'payload/versions'
import { getVersionsModelName } from 'payload/versions'
import {
buildVersionCollectionFields,
buildVersionGlobalFields,
getVersionsModelName,
} from 'payload/versions'
import type { MongooseAdapter } from '.'
import type { CollectionModel } from './types'
@@ -36,20 +38,6 @@ export const init: Init = async function init(this: MongooseAdapter) {
},
})
if (collection.indexes) {
collection.indexes.forEach((index) => {
// prefix 'version.' to each field in the index
const versionIndex = {
fields: {},
options: index.options,
}
Object.entries(index.fields).forEach(([key, value]) => {
versionIndex.fields[`version.${key}`] = value
})
versionSchema.index(versionIndex.fields, versionIndex.options)
})
}
versionSchema.plugin<any, PaginateOptions>(paginate, { useEstimatedCount: true }).plugin(
getBuildQueryPlugin({
collectionSlug: collection.slug,

View File

@@ -26,11 +26,7 @@ const buildCollectionSchema = (
schema.index({ updatedAt: 1 })
schema.index({ createdAt: 1 })
}
if (collection.indexes) {
collection.indexes.forEach((index) => {
schema.index(index.fields, index.options)
})
}
schema
.plugin<any, PaginateOptions>(paginate, { useEstimatedCount: true })
.plugin(getBuildQueryPlugin({ collectionSlug: collection.slug }))

View File

@@ -24,7 +24,6 @@ export const init: Init = async function init(this: PostgresAdapter) {
buildTable({
adapter: this,
buildRelationships: true,
collectionIndexes: collection.indexes,
disableUnique: false,
fields: collection.fields,
tableName,

View File

@@ -1,7 +1,7 @@
/* eslint-disable no-param-reassign */
import type { Relation } from 'drizzle-orm'
import type { IndexBuilder, PgColumnBuilder, UniqueConstraintBuilder } from 'drizzle-orm/pg-core'
import type { Field, SanitizedCollectionConfig } from 'payload/types'
import type { Field } from 'payload/types'
import { relations } from 'drizzle-orm'
import {
@@ -27,7 +27,6 @@ type Args = {
baseColumns?: Record<string, PgColumnBuilder>
baseExtraConfig?: Record<string, (cols: GenericColumns) => IndexBuilder | UniqueConstraintBuilder>
buildRelationships?: boolean
collectionIndexes?: SanitizedCollectionConfig['indexes']
disableUnique: boolean
fields: Field[]
rootRelationsToBuild?: Map<string, string>
@@ -46,7 +45,6 @@ export const buildTable = ({
baseColumns = {},
baseExtraConfig = {},
buildRelationships,
collectionIndexes = [],
disableUnique = false,
fields,
rootRelationsToBuild,
@@ -98,7 +96,6 @@ export const buildTable = ({
} = traverseFields({
adapter,
buildRelationships,
collectionIndexes,
columns,
disableUnique,
fields,

View File

@@ -1,7 +1,7 @@
/* eslint-disable no-param-reassign */
import type { Relation } from 'drizzle-orm'
import type { IndexBuilder, PgColumnBuilder, UniqueConstraintBuilder } from 'drizzle-orm/pg-core'
import type { Field, SanitizedCollectionConfig, TabAsField } from 'payload/types'
import type { Field, TabAsField } from 'payload/types'
import { relations } from 'drizzle-orm'
import {
@@ -15,7 +15,6 @@ import {
pgEnum,
text,
timestamp,
unique,
varchar,
} from 'drizzle-orm/pg-core'
import { InvalidConfiguration } from 'payload/errors'
@@ -33,7 +32,6 @@ import { validateExistingBlockIsIdentical } from './validateExistingBlockIsIdent
type Args = {
adapter: PostgresAdapter
buildRelationships: boolean
collectionIndexes: SanitizedCollectionConfig['indexes']
columnPrefix?: string
columns: Record<string, PgColumnBuilder>
disableUnique?: boolean
@@ -62,7 +60,6 @@ type Result = {
export const traverseFields = ({
adapter,
buildRelationships,
collectionIndexes,
columnPrefix,
columns,
disableUnique = false,
@@ -111,24 +108,6 @@ export const traverseFields = ({
targetIndexes = localesIndexes
}
const collectionIndex = collectionIndexes
? collectionIndexes.findIndex((index) => {
return Object.keys(index.fields).some((indexField) => indexField === fieldName)
})
: -1
if (collectionIndex > -1) {
const name = toSnakeCase(
`${Object.keys(collectionIndexes[collectionIndex].fields).join('_')}`,
)
targetIndexes[`${name}Idx`] = createIndex({
name: Object.keys(collectionIndexes[collectionIndex].fields),
columnName: name,
unique: collectionIndexes[collectionIndex].options.unique,
})
collectionIndexes.splice(collectionIndex)
}
if (
(field.unique || field.index) &&
!['array', 'blocks', 'group', 'point', 'relationship', 'upload'].includes(field.type) &&
@@ -416,7 +395,6 @@ export const traverseFields = ({
} = traverseFields({
adapter,
buildRelationships,
collectionIndexes,
columnPrefix,
columns,
disableUnique,
@@ -450,7 +428,6 @@ export const traverseFields = ({
} = traverseFields({
adapter,
buildRelationships,
collectionIndexes,
columnPrefix: `${columnName}_`,
columns,
disableUnique,
@@ -485,7 +462,6 @@ export const traverseFields = ({
} = traverseFields({
adapter,
buildRelationships,
collectionIndexes,
columnPrefix,
columns,
disableUnique,
@@ -522,7 +498,6 @@ export const traverseFields = ({
} = traverseFields({
adapter,
buildRelationships,
collectionIndexes,
columnPrefix,
columns,
disableUnique,

View File

@@ -353,10 +353,6 @@ export type CollectionConfig = {
beforeRead?: BeforeReadHook[]
beforeValidate?: BeforeValidateHook[]
}
/**
* Array of database indexes to create, including compound indexes that have multiple fields
*/
indexes?: TypeOfIndex[]
/**
* Label configuration
*/
@@ -441,52 +437,3 @@ export type TypeWithTimestamps = {
id: number | string
updatedAt: string
}
type IndexDirection =
| '2d'
| '2dsphere'
| 'asc'
| 'ascending'
| 'desc'
| 'descending'
| 'geoHaystack'
| 'hashed'
| 'text'
| -1
| 1
type IndexOptions = {
'2dsphereIndexVersion'?: number
/** Creates the index in the background, yielding whenever possible. */
background?: boolean
bits?: number
bucketSize?: number
/** (MongoDB 4.4. or higher) Specifies how many data-bearing members of a replica set, including the primary, must complete the index builds successfully before the primary marks the indexes as ready. This option accepts the same values for the "w" field in a write concern plus "votingMembers", which indicates all voting data-bearing nodes. */
commitQuorum?: number | string
default_language?: string
/** Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) */
expireAfterSeconds?: number
expires?: number | string
/** Specifies that the index should exist on the target collection but should not be used by the query planner when executing operations. (MongoDB 4.4 or higher) */
hidden?: boolean
language_override?: string
/** For geospatial indexes set the high bound for the co-ordinates. */
max?: number
/** For geospatial indexes set the lower bound for the co-ordinates. */
min?: number
/** Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) */
name?: string
/** Creates a sparse index. */
sparse?: boolean
textIndexVersion?: number
/** Creates an unique index. */
unique?: boolean
/** Specifies the index version number, either 0 or 1. */
version?: number
weights?: Record<string, number>
}
export type TypeOfIndex = {
fields: Record<string, IndexDirection>
options?: IndexOptions
}

View File

@@ -14,7 +14,6 @@ import { migrateDown } from './migrations/migrateDown'
import { migrateRefresh } from './migrations/migrateRefresh'
import { migrateReset } from './migrations/migrateReset'
import { migrateStatus } from './migrations/migrateStatus'
import { transaction } from './transaction'
const beginTransaction: BeginTransaction = async () => null
const rollbackTransaction: RollbackTransaction = async () => null
@@ -31,7 +30,6 @@ export function createDatabaseAdapter<T extends BaseDatabaseAdapter>(
| 'migrateReset'
| 'migrateStatus'
| 'migrationDir'
| 'transaction'
>,
): T {
return {
@@ -46,7 +44,6 @@ export function createDatabaseAdapter<T extends BaseDatabaseAdapter>(
migrateReset,
migrateStatus,
rollbackTransaction,
transaction,
...args,

View File

@@ -26,7 +26,6 @@ export interface BaseDatabaseAdapter {
createGlobal: CreateGlobal
// migrations
createGlobalVersion: CreateGlobalVersion
/**
* Output a migration file
@@ -51,17 +50,14 @@ export interface BaseDatabaseAdapter {
*/
destroy?: Destroy
// operations
find: <T = TypeWithID>(args: FindArgs) => Promise<PaginatedDocs<T>>
// operations - globals
findGlobal: FindGlobal
// transactions
findGlobalVersions: FindGlobalVersions
findOne: FindOne
// versions
findVersions: FindVersions
/**
@@ -124,20 +120,14 @@ export interface BaseDatabaseAdapter {
resolve: () => void
}
}
/**
* Perform many database interactions in a single, all-or-nothing operation.
*/
transaction?: Transaction
updateGlobal: UpdateGlobal
updateGlobalVersion: UpdateGlobalVersion
updateOne: UpdateOne
updateVersion: UpdateVersion
/**
* assign the transaction to use when making queries, defaults to the last started transaction
*/
useTransaction?: (id: number | string) => void
}
export type Init = (payload: Payload) => Promise<void>

View File

@@ -67,18 +67,6 @@ const getPreferencesCollection = (config: Config): CollectionConfig => ({
type: 'json',
},
],
indexes: [
{
fields: {
key: 1,
'user.relationTo': 1,
'user.value': 1,
},
options: {
unique: true,
},
},
],
slug: 'payload-preferences',
})

View File

@@ -7,24 +7,23 @@ import type { IndexedField } from '../../payload-types'
const beforeDuplicate: BeforeDuplicate<IndexedField> = ({ data }) => {
return {
...data,
uniqueText: data.uniqueText ? `${data.uniqueText}-copy` : '',
collapsibleLocalizedUnique: data.collapsibleLocalizedUnique
? `${data.collapsibleLocalizedUnique}-copy`
: '',
collapsibleTextUnique: data.collapsibleTextUnique ? `${data.collapsibleTextUnique}-copy` : '',
group: {
...(data.group || {}),
localizedUnique: data.group?.localizedUnique ? `${data.group?.localizedUnique}-copy` : '',
},
collapsibleTextUnique: data.collapsibleTextUnique ? `${data.collapsibleTextUnique}-copy` : '',
collapsibleLocalizedUnique: data.collapsibleLocalizedUnique
? `${data.collapsibleLocalizedUnique}-copy`
: '',
partOne: data.partOne ? `${data.partOne}-copy` : '',
partTwo: data.partTwo ? `${data.partTwo}-copy` : '',
uniqueText: data.uniqueText ? `${data.uniqueText}-copy` : '',
}
}
const IndexedFields: CollectionConfig = {
slug: 'indexed-fields',
// used to assert that versions also get indexes
versions: true,
admin: {
hooks: {
beforeDuplicate,
@@ -33,9 +32,9 @@ const IndexedFields: CollectionConfig = {
fields: [
{
name: 'text',
type: 'text',
required: true,
index: true,
required: true,
type: 'text',
},
{
name: 'uniqueText',
@@ -47,54 +46,41 @@ const IndexedFields: CollectionConfig = {
type: 'point',
},
{
type: 'group',
name: 'group',
fields: [
{
name: 'localizedUnique',
localized: true,
type: 'text',
unique: true,
localized: true,
},
{
name: 'point',
type: 'point',
},
],
type: 'group',
},
{
type: 'collapsible',
label: 'Collapsible',
fields: [
{
name: 'collapsibleLocalizedUnique',
localized: true,
type: 'text',
unique: true,
localized: true,
},
{
name: 'collapsibleTextUnique',
type: 'text',
label: 'collapsibleTextUnique',
type: 'text',
unique: true,
},
],
},
{
name: 'partOne',
type: 'text',
},
{
name: 'partTwo',
type: 'text',
},
],
indexes: [
{
fields: { partOne: 1, partTwo: 1 },
options: { unique: true, name: 'compound-index', sparse: true },
label: 'Collapsible',
type: 'collapsible',
},
],
versions: true,
}
export default IndexedFields

View File

@@ -286,15 +286,6 @@ describe('Fields', () => {
expect(options.uniqueText).toMatchObject({ unique: true })
})
it('should have unique compound indexes', () => {
expect(definitions.partOne).toEqual(1)
expect(options.partOne).toMatchObject({
name: 'compound-index',
sparse: true,
unique: true,
})
})
it('should have 2dsphere indexes on point fields', () => {
expect(definitions.point).toEqual('2dsphere')
})
@@ -342,14 +333,6 @@ describe('Fields', () => {
it('should have versions indexes', () => {
expect(definitions['version.text']).toEqual(1)
})
it('should have version indexes from collection indexes', () => {
expect(definitions['version.partOne']).toEqual(1)
expect(options['version.partOne']).toMatchObject({
name: 'compound-index',
sparse: true,
unique: true,
})
})
})
describe('point', () => {
@@ -440,32 +423,6 @@ describe('Fields', () => {
return result.error
}).toBeDefined()
})
it('should throw validation error saving on unique combined fields', async () => {
await payload.delete({ collection: 'indexed-fields', where: {} })
const data1 = {
partOne: 'u',
partTwo: 'u',
text: 'a',
uniqueText: 'a',
}
const data2 = {
partOne: 'u',
partTwo: 'u',
text: 'b',
uniqueText: 'b',
}
await payload.create({
collection: 'indexed-fields',
data: data1,
})
expect(async () => {
const result = await payload.create({
collection: 'indexed-fields',
data: data2,
})
return result.error
}).toBeDefined()
})
})
describe('array', () => {