docs: update examples with ts types

This commit is contained in:
Elliot DeNolf
2022-08-23 11:43:24 -04:00
parent b21a56fdf7
commit 1ed867ce0c
53 changed files with 547 additions and 400 deletions

View File

@@ -27,8 +27,10 @@ If a Collection supports [`Authentication`](/docs/authentication/overview), the
| **[`unlock`](#unlock)** | Used to restrict which users can access the `unlock` operation |
**Example Collection config:**
```js
export default {
```ts
import { CollectionConfig } from 'payload/types';
const Posts: CollectionConfig = {
slug: "posts",
// highlight-start
access: {
@@ -40,6 +42,8 @@ export default {
},
// highlight-end
};
export default Categories;
```
### Create
@@ -55,7 +59,7 @@ Returns a boolean which allows/denies access to the `create` request.
**Example:**
```js
```ts
const PublicUsers = {
slug: 'public-users',
access: {
@@ -82,8 +86,10 @@ Read access functions can return a boolean result or optionally return a [query
**Example:**
```js
const canReadPage = ({ req: { user } }) => {
```ts
import { Access } from 'payload/config';
const canReadPage: Access = ({ req: { user } }) => {
// allow authenticated users
if (user) {
return true;
@@ -92,8 +98,8 @@ const canReadPage = ({ req: { user } }) => {
return {
// assumes we have a checkbox field named 'isPublic'
isPublic: {
equals: true
}
equals: true,
},
}
};
```
@@ -112,11 +118,12 @@ Update access functions can return a boolean result or optionally return a [quer
**Example:**
```js
```ts
import { Access } from 'payload/config';
const canUpdateUser = ({ req: { user }, id }) => {
const canUpdateUser: Access = ({ req: { user }, id }) => {
// allow users with a role of 'admin'
if (user.roles && user.roles.some((role) => role === 'admin')) {
if (user.roles && user.roles.some(role => role === 'admin')) {
return true;
}
// allow any other users to update only oneself
@@ -137,8 +144,10 @@ Similarly to the Update function, returns a boolean or a [query constraint](/doc
**Example:**
```js
const canDeleteCustomer = async ({ req, id }) => {
```ts
import { Access } from 'payload/config'
const canDeleteCustomer: Access = async ({ req, id }) => {
if (!id) {
// allow the admin UI to show controls to delete since it is indeterminate without the id
return true;

View File

@@ -17,8 +17,10 @@ Field Access Control is specified with functions inside a field's config. All fi
| **[`update`](#update)** | Allows or denies the ability to update a field's value |
**Example Collection config:**
```js
export default {
```ts
import { CollectionConfig } from 'payload/types';
const Posts: CollectionConfig = {
slug: 'posts',
fields: [
{
@@ -33,7 +35,7 @@ export default {
// highlight-end
};
],
}
};
```
### Create

View File

@@ -18,16 +18,20 @@ You can define Global-level Access Control within each Global's `access` propert
| **[`update`](#update)** | Used in the `update` Global operation |
**Example Global config:**
```js
export default {
```ts
import { GlobalConfig } from 'payload/types';
const Header: GlobalConfig = {
slug: "header",
// highlight-start
access: {
read: ({ req: { user } }) => { ... },
update: ({ req: { user } }) => { ... },
read: ({ req: { user } }) => { /* */ },
update: ({ req: { user } }) => { /* */ },
},
// highlight-end
};
export default Header;
```
### Read

View File

@@ -23,7 +23,7 @@ Access control within Payload is extremely powerful while remaining easy and int
**Default Access function:**
```js
```ts
const defaultPayloadAccess = ({ req: { user } }) => {
// Return `true` if a user is found
// and `false` if it is undefined or null

View File

@@ -38,9 +38,16 @@ You can override a set of admin panel-wide components by providing a component t
#### Full example:
`payload.config.js`
```js
import { buildConfig } from 'payload/config';
import { MyCustomNav, MyCustomLogo, MyCustomIcon, MyCustomAccount, MyCustomDashboard, MyProvider } from './customComponents.js';
```ts
import { buildConfig } from 'payload/config'
import {
MyCustomNav,
MyCustomLogo,
MyCustomIcon,
MyCustomAccount,
MyCustomDashboard,
MyProvider,
} from './customComponents';
export default buildConfig({
admin: {
@@ -55,9 +62,9 @@ export default buildConfig({
Dashboard: MyCustomDashboard,
},
providers: [MyProvider],
}
}
})
},
},
});
```
*For more examples regarding how to customize components, look at the following [examples](https://github.com/payloadcms/payload/tree/master/test/admin/components).*
@@ -100,20 +107,17 @@ All Payload fields support the ability to swap in your own React components. So,
When swapping out the `Field` component, you'll be responsible for sending and receiving the field's `value` from the form itself. To do so, import the `useField` hook as follows:
```js
import { useField } from 'payload/components/forms';
```tsx
import { useField } from 'payload/components/forms'
const CustomTextField = ({ path }) => {
type Props = { path: string }
const CustomTextField: React.FC<Props> = ({ path }) => {
// highlight-start
const { value, setValue } = useField({ path });
const { value, setValue } = useField<Props>({ path })
// highlight-end
return (
<input
onChange={(e) => setValue(e.target.value)}
value={value}
/>
)
return <input onChange={e => setValue(e.target.value)} value={value.path} />
}
```
@@ -121,10 +125,10 @@ const CustomTextField = ({ path }) => {
There are times when a custom field component needs to have access to data from other fields. This can be done using `getDataByPath` from `useWatchForm` as follows:
```js
```tsx
import { useWatchForm } from 'payload/components/forms';
const DisplayFee = () => {
const DisplayFee: React.FC = () => {
const { getDataByPath } = useWatchForm();
const amount = getDataByPath('amount');
@@ -132,7 +136,7 @@ const DisplayFee = () => {
if (amount && feePercentage) {
return (
<span>The fee is ${ amount * feePercentage / 100 }</span>
<span>The fee is ${(amount * feePercentage) / 100}</span>
);
}
};
@@ -142,10 +146,10 @@ const DisplayFee = () => {
The document ID can be very useful for certain custom components. You can get the `id` from the `useDocumentInfo` hook. Here is an example of a `UI` field using `id` to link to related collections:
```js
```tsx
import { useDocumentInfo } from 'payload/components/utilities';
const LinkFromCategoryToPosts = () => {
const LinkFromCategoryToPosts: React.FC = () => {
// highlight-start
const { id } = useDocumentInfo();
// highlight-end
@@ -222,10 +226,10 @@ To make use of Payload SCSS variables / mixins to use directly in your own compo
In any custom component you can get the selected locale with the `useLocale` hook. Here is a simple example:
```js
```tsx
import { useLocale } from 'payload/components/utilities';
const Greeting = () => {
const Greeting: React.FC = () => {
// highlight-start
const locale = useLocale();
// highlight-end
@@ -237,6 +241,6 @@ const Greeting = () => {
return (
<span> { trans[locale] } </span>
)
}
);
};
```

View File

@@ -13,7 +13,7 @@ You can add your own CSS by providing your base Payload config with a path to yo
To do so, provide your base Payload config with a path to your own stylesheet. It can be either a CSS or SCSS file.
**Example in payload.config.js:**
```js
```ts
import { buildConfig } from 'payload/config';
import path from 'path';
@@ -21,7 +21,7 @@ const config = buildConfig({
admin: {
css: path.resolve(__dirname, 'relative/path/to/stylesheet.scss'),
},
})
});
```
### Overriding built-in styles

View File

@@ -45,14 +45,14 @@ All options for the Admin panel are defined in your base Payload config file.
To specify which Collection to use to log in to the Admin panel, pass the `admin` options a `user` key equal to the slug of the Collection that you'd like to use.
`payload.config.js`:
```js
```ts
import { buildConfig } from 'payload/config';
const config = buildConfig({
admin: {
user: 'admins', // highlight-line
},
})
});
```
By default, if you have not specified a Collection, Payload will automatically provide you with a `User` Collection which will be used to access the Admin panel. You can customize or override the fields and settings of the default `User` Collection by passing your own collection using `users` as its `slug` to Payload. When this is done, Payload will use your provided `User` Collection instead of its default version.

View File

@@ -10,8 +10,8 @@ Payload uses Webpack 5 to build the Admin panel. It comes with support for many
To extend the Webpack config, add the `webpack` key to your base Payload config, and provide a function that accepts the default Webpack config as its only argument:
`payload.config.js`
```js
`payload.config.ts`
```ts
import { buildConfig } from 'payload/config';
export default buildConfig({
@@ -24,7 +24,7 @@ export default buildConfig({
}
// highlight-end
}
})
});
```
### Aliasing server-only modules
@@ -52,16 +52,17 @@ You may rely on server-only packages such as the above to perform logic in acces
<br/><br/>
`collections/Subscriptions/index.js`
```js
```ts
import { CollectionConfig } from 'payload/types';
import createStripeSubscription from './hooks/createStripeSubscription';
const Subscription = {
const Subscription: CollectionConfig = {
slug: 'subscriptions',
hooks: {
beforeChange: [
createStripeSubscription,
]
}
},
fields: [
{
name: 'stripeSubscriptionID',
@@ -69,7 +70,7 @@ const Subscription = {
required: true,
}
]
}
};
export default Subscription;
```

View File

@@ -49,7 +49,7 @@ To utilize your API key while interacting with the REST or GraphQL API, add the
**For example, using Fetch:**
```js
```ts
const response = await fetch("http://localhost:3000/api/pages", {
headers: {
Authorization: `${collection.labels.singular} API-Key ${YOUR_API_KEY}`,
@@ -77,8 +77,10 @@ Function that accepts one argument, containing `{ req, token, user }`, that allo
Example:
```js
{
```ts
import { CollectionConfig } from 'payload/types';
const Customers: CollectionConfig = {
slug: 'customers',
auth: {
forgotPassword: {
@@ -104,7 +106,7 @@ Example:
// highlight-end
}
}
}
};
```
<Banner type="warning">
@@ -123,7 +125,7 @@ Similarly to the above `generateEmailHTML`, you can also customize the subject o
Example:
```js
```ts
{
slug: 'customers',
auth: {
@@ -148,8 +150,11 @@ Function that accepts one argument, containing `{ req, token, user }`, that allo
Example:
```js
{
```ts
import { CollectionConfig } from 'payload/types';
const Customers: CollectionConfig = {
slug: 'customers',
auth: {
verify: {
@@ -163,7 +168,7 @@ Example:
// highlight-end
}
}
}
};
```
<Banner type="warning">
@@ -182,7 +187,7 @@ Similarly to the above `generateEmailHTML`, you can also customize the subject o
Example:
```js
```ts
{
slug: 'customers',
auth: {

View File

@@ -17,7 +17,7 @@ The Access operation returns what a logged in user can and can't do with the col
`GET http://localhost:3000/api/access`
Example response:
```js
```ts
{
canAccessAdmin: true,
collections: {
@@ -54,7 +54,7 @@ Example response:
**Example GraphQL Query**:
```
```graphql
query {
Access {
pages {
@@ -75,7 +75,7 @@ Returns either a logged in user with token or null when there is no logged in us
`GET http://localhost:3000/api/[collection-slug]/me`
Example response:
```js
```ts
{
user: { // The JWT "payload" ;) from the logged in user
email: 'dev@payloadcms.com',
@@ -90,7 +90,7 @@ Example response:
**Example GraphQL Query**:
```
```graphql
query {
Me[collection-singular-label] {
user {
@@ -106,7 +106,7 @@ query {
Accepts an `email` and `password`. On success, it will return the logged in user as well as a token that can be used to authenticate. In the GraphQL and REST APIs, this operation also automatically sets an HTTP-only cookie including the user's token. If you pass an Express `res` to the Local API operation, Payload will set a cookie there as well.
**Example REST API login**:
```js
```ts
const res = await fetch('http://localhost:3000/api/[collection-slug]/login', {
method: 'POST',
headers: {
@@ -137,7 +137,7 @@ const json = await res.json();
**Example GraphQL Mutation**:
```
```graphql
mutation {
login[collection-singular-label](email: "dev@payloadcms.com", password: "yikes") {
user {
@@ -151,7 +151,7 @@ mutation {
**Example Local API login**:
```js
```ts
const result = await payload.login({
collection: '[collection-slug]',
data: {
@@ -166,7 +166,7 @@ const result = await payload.login({
As Payload sets HTTP-only cookies, logging out cannot be done by just removing a cookie in JavaScript, as HTTP-only cookies are inaccessible by JS within the browser. So, Payload exposes a `logout` operation to delete the token in a safe way.
**Example REST API logout**:
```js
```ts
const res = await fetch('http://localhost:3000/api/[collection-slug]/logout', {
method: 'POST',
headers: {
@@ -192,7 +192,7 @@ This operation requires a non-expired token to send back a new one. If the user'
If successful, this operation will automatically renew the user's HTTP-only cookie and will send back the updated token in JSON.
**Example REST API token refresh**:
```js
```ts
const res = await fetch('http://localhost:3000/api/[collection-slug]/refresh-token', {
method: 'POST',
headers: {
@@ -239,18 +239,18 @@ mutation {
If your collection supports email verification, the Verify operation will be exposed which accepts a verification token and sets the user's `_verified` property to `true`, thereby allowing the user to authenticate with the Payload API.
**Example REST API user verification**:
```js
```ts
const res = await fetch(`http://localhost:3000/api/[collection-slug]/verify/${TOKEN_HERE}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
})
});
```
**Example GraphQL Mutation**:
```
```graphql
mutation {
verifyEmail[collection-singular-label](token: "TOKEN_HERE")
}
@@ -258,7 +258,7 @@ mutation {
**Example Local API verification**:
```js
```ts
const result = await payload.verifyEmail({
collection: '[collection-slug]',
token: 'TOKEN_HERE',
@@ -272,7 +272,7 @@ If a user locks themselves out and you wish to deliberately unlock them, you can
To restrict who is allowed to unlock users, you can utilize the [`unlock`](/docs/access-control/overview#unlock) access control function.
**Example REST API unlock**:
```js
```ts
const res = await fetch(`http://localhost:3000/api/[collection-slug]/unlock`, {
method: 'POST',
headers: {
@@ -291,7 +291,7 @@ mutation {
**Example Local API unlock**:
```js
```ts
const result = await payload.unlock({
collection: '[collection-slug]',
})
@@ -306,7 +306,7 @@ The link to reset the user's password contains a token which is what allows the
By default, the Forgot Password operations send users to the Payload Admin panel to reset their password, but you can customize the generated email to send users to the frontend of your app instead by [overriding the email HTML](/docs/authentication/config#forgot-password).
**Example REST API Forgot Password**:
```js
```ts
const res = await fetch(`http://localhost:3000/api/[collection-slug]/forgot-password`, {
method: 'POST',
headers: {
@@ -315,7 +315,7 @@ const res = await fetch(`http://localhost:3000/api/[collection-slug]/forgot-pass
body: JSON.stringify({
email: 'dev@payloadcms.com',
}),
})
});
```
**Example GraphQL Mutation**:
@@ -328,14 +328,14 @@ mutation {
**Example Local API forgot password**:
```js
```ts
const token = await payload.forgotPassword({
collection: '[collection-slug]',
data: {
email: 'dev@payloadcms.com',
},
disableEmail: false // you can disable the auto-generation of email via local API
})
});
```
<Banner type="success">
@@ -348,7 +348,7 @@ const token = await payload.forgotPassword({
After a user has "forgotten" their password and a token is generated, that token can be used to send to the reset password operation along with a new password which will allow the user to reset their password securely.
**Example REST API Reset Password**:
```js
```ts
const res = await fetch(`http://localhost:3000/api/[collection-slug]/reset-password`, {
method: 'POST',
headers: {
@@ -358,7 +358,7 @@ const res = await fetch(`http://localhost:3000/api/[collection-slug]/reset-passw
token: 'TOKEN_GOES_HERE'
password: 'not-today',
}),
})
});
const json = await res.json();
@@ -379,7 +379,7 @@ const json = await res.json();
**Example GraphQL Mutation**:
```
```graphql
mutation {
resetPassword[collection-singular-label](token: "TOKEN_GOES_HERE", password: "not-today")
}

View File

@@ -32,8 +32,10 @@ Every Payload Collection can opt-in to supporting Authentication by specifying t
Simple example collection:
```js
const Admins = {
```ts
import { CollectionConfig } from 'payload/types';
const Admins: CollectionConfig = {
slug:
// highlight-start
auth: {
@@ -95,7 +97,7 @@ However, if you use `fetch` or similar APIs to retrieve Payload resources from i
Fetch example, including credentials:
```js
```ts
const response = await fetch('http://localhost:3000/api/pages', {
credentials: 'include',
});
@@ -124,8 +126,8 @@ So, if a user of coolsite.com is logged in and just browsing around on the inter
To define domains that should allow users to identify themselves via the Payload HTTP-only cookie, use the `csrf` option on the base Payload config to whitelist domains that you trust.
`payload.config.js`:
```js
`payload.config.ts`:
```ts
import { buildConfig } from 'payload/config';
const config = buildConfig({
@@ -148,7 +150,7 @@ export default config;
In addition to authenticating via an HTTP-only cookie, you can also identify users via the `Authorization` header on an HTTP request.
Example:
```js
```ts
const request = await fetch('http://localhost:3000', {
headers: {
Authorization: `JWT ${token}`

View File

@@ -15,7 +15,7 @@ This approach has a ton of benefits - it's great for isolation of concerns and l
</Banner>
Example in `server.js`:
```js
```ts
import express from 'express';
import payload from 'payload';

View File

@@ -31,8 +31,10 @@ It's often best practice to write your Collections in separate files and then im
#### Simple collection example
```js
const Orders = {
```ts
import { CollectionConfig } from 'payload/types';
const Orders: CollectionConfig = {
slug: 'orders',
fields: [
{
@@ -47,7 +49,7 @@ const Orders = {
required: true,
}
]
}
};
```
#### More collection config examples
@@ -80,8 +82,10 @@ If the function is specified, a Preview button will automatically appear in the
**Example collection with preview function:**
```js
const Posts = {
```ts
import { CollectionConfig } from 'payload/types';
const Posts: CollectionConfig = {
slug: 'posts',
fields: [
{
@@ -118,14 +122,14 @@ Collections support all field types that Payload has to offer—including simple
You can import collection types as follows:
```js
```ts
import { CollectionConfig } from 'payload/types';
// This is the type used for incoming collection configs.
// Only the bare minimum properties are marked as required.
```
```js
```ts
import { SanitizedCollectionConfig } from 'payload/types';
// This is the type used after an incoming collection config is fully sanitized.

View File

@@ -28,8 +28,10 @@ As with Collection configs, it's often best practice to write your Globals in se
#### Simple Global example
```js
const Nav = {
```ts
import { GlobalConfig } from 'payload/types';
const Nav: GlobalConfig = {
slug: 'nav',
fields: [
{
@@ -47,7 +49,9 @@ const Nav = {
]
},
]
}
};
export default Nav;
```
#### Global config example
@@ -78,14 +82,14 @@ Globals support all field types that Payload has to offer—including simple fie
You can import global types as follows:
```js
```ts
import { GlobalConfig } from 'payload/types';
// This is the type used for incoming global configs.
// Only the bare minimum properties are marked as required.
```
```js
```ts
import { SanitizedGlobalConfig } from 'payload/types';
// This is the type used after an incoming global config is fully sanitized.

View File

@@ -14,21 +14,23 @@ Add the `localization` property to your Payload config to enable localization pr
**Example Payload config set up for localization:**
```js
{
collections: [
... // collections go here
],
localization: {
locales: [
'en',
'es',
'de',
],
defaultLocale: 'en',
fallback: true,
},
}
```ts
import { buildConfig } from 'payload/config'
export default buildConfig({
collections: [
// collections go here
],
localization: {
locales: [
'en',
'es',
'de',
],
defaultLocale: 'en',
fallback: true,
},
});
```
**Here is a brief explanation of each of the options available within the `localization` property:**
@@ -53,11 +55,11 @@ Payload localization works on a **field** level—not a document level. In addit
```js
{
name: 'title',
type: 'text',
// highlight-start
localized: true,
// highlight-end
name: 'title',
type: 'text',
// highlight-start
localized: true,
// highlight-end
}
```
@@ -66,8 +68,8 @@ With the above configuration, the `title` field will now be saved in the databas
All field types with a `name` property support the `localized` property—even the more complex field types like `array`s and `block`s.
<Banner>
<strong>Note:</strong><br/>
Enabling localization for field types that support nested fields will automatically create localized "sets" of all fields contained within the field. For example, if you have a page layout using a blocks field type, you have the choice of either localizing the full layout, by enabling localization on the top-level blocks field, or only certain fields within the layout.
<strong>Note:</strong><br/>
Enabling localization for field types that support nested fields will automatically create localized "sets" of all fields contained within the field. For example, if you have a page layout using a blocks field type, you have the choice of either localizing the full layout, by enabling localization on the top-level blocks field, or only certain fields within the layout.
</Banner>
### Retrieving localized docs
@@ -104,16 +106,16 @@ The `fallbackLocale` arg will accept valid locales as well as `none` to disable
```graphql
query {
Posts(locale: de, fallbackLocale: none) {
docs {
title
}
}
Posts(locale: de, fallbackLocale: none) {
docs {
title
}
}
}
```
<Banner>
In GraphQL, specifying the locale at the top level of a query will automatically apply it throughout all nested relationship fields. You can override this behavior by re-specifying locale arguments in nested related document queries.
In GraphQL, specifying the locale at the top level of a query will automatically apply it throughout all nested relationship fields. You can override this behavior by re-specifying locale arguments in nested related document queries.
</Banner>
##### Local API
@@ -124,9 +126,9 @@ You can specify `locale` as well as `fallbackLocale` within the Local API as wel
```js
const posts = await payload.find({
collection: 'posts',
locale: 'es',
fallbackLocale: false,
collection: 'posts',
locale: 'es',
fallbackLocale: false,
})
```

View File

@@ -43,10 +43,10 @@ Payload is a *config-based*, code-first CMS and application framework. The Paylo
#### Simple example
```js
```ts
import { buildConfig } from 'payload/config';
const config = buildConfig({
export default buildConfig({
collections: [
{
slug: 'pages',
@@ -83,9 +83,6 @@ const config = buildConfig({
}
]
});
export default config;
```
#### Full example config
@@ -174,14 +171,14 @@ Then, you could import this file into both your Payload config and your server,
You can import config types as follows:
```js
```ts
import { Config } from 'payload/config';
// This is the type used for an incoming Payload config.
// Only the bare minimum properties are marked as required.
```
```js
```ts
import { SanitizedConfig } from 'payload/config';
// This is the type used after an incoming Payload config is fully sanitized.

View File

@@ -40,7 +40,7 @@ The following options are configurable in the `email` property object as part of
Simple Mail Transfer Protocol, also known as SMTP can be passed in using the `transportOptions` object on the `email` options.
**Example email part using SMTP:**
```js
```ts
payload.init({
email: {
transportOptions: {
@@ -60,6 +60,7 @@ payload.init({
fromAddress: 'hello@example.com'
}
// ...
})
```
<Banner type="warning">
@@ -70,9 +71,9 @@ payload.init({
Many third party mail providers are available and offer benefits beyond basic SMTP. As an example your payload init could look this if you wanted to use SendGrid.com though the same approach would work for any other [NodeMailer transports](https://nodemailer.com/transports/) shown here or provided by another third party.
```js
const nodemailerSendgrid = require('nodemailer-sendgrid');
const payload = require('payload');
```ts
import payload from 'payload'
import nodemailerSendgrid from 'nodemailer-sendgrid'
const sendGridAPIKey = process.env.SENDGRID_API_KEY;
@@ -92,7 +93,10 @@ payload.init({
### Use a custom NodeMailer transport
To take full control of the mail transport you may wish to use `nodemailer.createTransport()` on your server and provide it to Payload init.
```js
```ts
import payload from 'payload'
import nodemailer from 'nodemailer'
const payload = require('payload');
const nodemailer = require('nodemailer');
@@ -112,7 +116,7 @@ payload.init({
transport
},
// ...
}
});
```
### Sending Mail
@@ -123,7 +127,7 @@ By default, Payload uses a mock implementation that only sends mail to the [ethe
To see ethereal credentials, add `logMockCredentials: true` to the email options. This will cause them to be logged to console on startup.
```js
```ts
payload.init({
email: {
fromName: 'Admin',

View File

@@ -41,9 +41,11 @@ keywords: array, fields, config, configuration, documentation, Content Managemen
### Example
`collections/ExampleCollection.js`
```js
{
`collections/ExampleCollection.ts`
```ts
import { CollectionConfig } from 'payload/types';
const ExampleCollection: CollectionConfig = {
slug: 'example-collection',
fields: [
{
@@ -70,6 +72,5 @@ keywords: array, fields, config, configuration, documentation, Content Managemen
]
}
]
}
};
```

View File

@@ -72,8 +72,10 @@ The Admin panel provides each block with a `blockName` field which optionally al
### Example
`collections/ExampleCollection.js`
```js
const QuoteBlock = {
```ts
import { Block, CollectionConfig } from 'payload/types';
const QuoteBlock: Block = {
slug: 'Quote', // required
imageURL: 'https://google.com/path/to/image.jpg',
imageAltText: 'A nice thumbnail image to show what this block looks like',
@@ -90,7 +92,7 @@ const QuoteBlock = {
]
};
const ExampleCollection = {
const ExampleCollection: CollectionConfig = {
slug: 'example-collection',
fields: [
{
@@ -111,7 +113,7 @@ const ExampleCollection = {
As you build your own Block configs, you might want to store them in separate files but retain typing accordingly. To do so, you can import and use Payload's `Block` type:
```js
```ts
import type { Block } from 'payload/types';
```

View File

@@ -31,9 +31,11 @@ keywords: checkbox, fields, config, configuration, documentation, Content Manage
### Example
`collections/ExampleCollection.js`
```js
{
`collections/ExampleCollection.ts`
```ts
import { CollectionConfig } from 'payload/types';
const ExampleCollection: CollectionConfig = {
slug: 'example-collection',
fields: [
{
@@ -43,6 +45,5 @@ keywords: checkbox, fields, config, configuration, documentation, Content Manage
defaultValue: false,
}
]
}
};
```

View File

@@ -55,9 +55,11 @@ The following `prismjs` plugins are imported, enabling the `language` property t
### Example
`collections/ExampleCollection.js`
```js
{
`collections/ExampleCollection.ts
```ts
import { CollectionConfig } from 'payload/types';
const ExampleCollection: CollectionConfig = {
slug: 'example-collection',
fields: [
{
@@ -69,6 +71,5 @@ The following `prismjs` plugins are imported, enabling the `language` property t
}
}
]
}
};
```

View File

@@ -22,9 +22,11 @@ keywords: row, fields, config, configuration, documentation, Content Management
### Example
`collections/ExampleCollection.js`
```js
{
`collections/ExampleCollection.ts`
```ts
import { CollectionConfig } from 'payload/types';
const ExampleCollection: CollectionConfig = {
slug: 'example-collection',
fields: [
{
@@ -39,6 +41,5 @@ keywords: row, fields, config, configuration, documentation, Content Management
],
}
]
}
};
```

View File

@@ -55,10 +55,12 @@ Common use cases for customizing the `date` property are to restrict your field
### Example
`collections/ExampleCollection.js`
`collections/ExampleCollection.ts`
```js
{
```ts
import { CollectionConfig } from 'payload/types';
const ExampleCollection: CollectionConfig = {
slug: 'example-collection',
fields: [
{
@@ -74,6 +76,5 @@ Common use cases for customizing the `date` property are to restrict your field
}
}
]
}
};
```

View File

@@ -44,9 +44,11 @@ Set this property to a string that will be used for browser autocomplete.
### Example
`collections/ExampleCollection.js`
```js
{
`collections/ExampleCollection.ts`
```ts
import { CollectionConfig } from 'payload/types';
const ExampleCollection: CollectionConfig = {
slug: 'example-collection',
fields: [
{
@@ -56,6 +58,5 @@ Set this property to a string that will be used for browser autocomplete.
required: true,
}
]
}
};
```

View File

@@ -39,9 +39,11 @@ Set this property to `true` to hide this field's gutter within the admin panel.
### Example
`collections/ExampleCollection.js`
```js
{
`collections/ExampleCollection.ts`
```ts
import { CollectionConfig } from 'payload/types';
const ExampleCollection: CollectionConfig = {
slug: 'example-collection',
fields: [
{
@@ -65,6 +67,5 @@ Set this property to `true` to hide this field's gutter within the admin panel.
],
}
]
}
};
```

View File

@@ -50,9 +50,11 @@ Set this property to a string that will be used for browser autocomplete.
### Example
`collections/ExampleCollection.js`
```js
{
`collections/ExampleCollection.ts`
```ts
import { CollectionConfig } from 'payload/types';
const ExampleCollection: CollectionConfig = {
slug: 'example-collection',
fields: [
{
@@ -64,6 +66,5 @@ Set this property to a string that will be used for browser autocomplete.
}
}
]
}
};
```

View File

@@ -16,8 +16,10 @@ Fields are defined as an array on Collections and Globals via the `fields` key.
The required `type` property on a field determines what values it can accept, how it is presented in the API, and how the field will be rendered in the admin interface.
**Simple collection with two fields:**
```js
const Pages = {
```ts
import { CollectionConfig } from 'payload/types';
const Page: CollectionConfig = {
slug: 'pages',
fields: [
{
@@ -29,7 +31,7 @@ const Pages = {
type: 'checkbox', // highlight-line
},
],
}
};
```
### Field types
@@ -80,8 +82,10 @@ There are two arguments available to custom validation functions.
| `payload` | If the `validate` function is being executed on the server, Payload will be exposed for easily running local operations. |
Example:
```js
{
```ts
import { CollectionConfig } from 'payload/types';
const Orders: CollectionConfig = {
slug: 'orders',
fields: [
{
@@ -101,27 +105,27 @@ Example:
},
},
],
}
};
```
When supplying a field `validate` function, Payload will use yours in place of the default. To make use of the default field validation in your custom logic you can import, call and return the result as needed.
For example:
```js
```ts
import { text } from 'payload/fields/validations';
const field =
{
name: 'notBad',
type: 'text',
validate: (val, args) => {
if (value === 'bad') {
return 'This cannot be "bad"';
}
// highlight-start
return text(val, args);
// highlight-end
},
}
const field: Field = {
name: 'notBad',
type: 'text',
validate: (val, args) => {
if (val === 'bad') {
return 'This cannot be "bad"';
}
// highlight-start
return text(val, args);
// highlight-end
},
};
```
### Customizable ID
@@ -131,7 +135,7 @@ Users are then required to provide a custom ID value when creating a record thro
Valid ID types are `number` and `text`.
Example:
```js
```ts
{
fields: [
{
@@ -174,7 +178,7 @@ The `condition` function should return a boolean that will control if the field
**Example:**
```js
```ts
{
fields: [
{
@@ -212,21 +216,21 @@ Functions are called with an optional argument object containing:
Here is an example of a defaultValue function that uses both:
```js
```ts
const translation: {
en: 'Written by',
es: 'Escrito por',
en: 'Written by',
es: 'Escrito por',
};
const field = {
name: 'attribution',
type: 'text',
admin: {
// highlight-start
defaultValue: ({ user, locale }) => (`${translation[locale]} ${user.name}`)
// highlight-end
}
};
name: 'attribution',
type: 'text',
admin: {
// highlight-start
defaultValue: ({ user, locale }) => (`${translation[locale]} ${user.name}`)
// highlight-end
}
};
```
<Banner type="success">
@@ -244,7 +248,7 @@ As shown above, you can simply provide a string that will show by the field, but
**Function Example:**
```js
```ts
{
fields: [
{
@@ -262,7 +266,7 @@ As shown above, you can simply provide a string that will show by the field, but
This example will display the number of characters allowed as the user types.
**Component Example:**
```js
```ts
{
fields: [
{
@@ -289,10 +293,8 @@ This component will count the number of characters entered.
You can import the internal Payload `Field` type as well as other common field types as follows:
```js
```ts
import type {
Field,
Validate,
Condition,
} from 'payload/types';
```

View File

@@ -35,9 +35,11 @@ The data structure in the database matches the GeoJSON structure to represent po
### Example
`collections/ExampleCollection.js`
```js
{
`collections/ExampleCollection.ts`
```ts
import { CollectionConfig } from 'payload/types';
const ExampleCollection: CollectionConfig = {
slug: 'example-collection',
fields: [
{
@@ -46,7 +48,7 @@ The data structure in the database matches the GeoJSON structure to represent po
label: 'Location',
},
]
}
};
```
### Querying

View File

@@ -45,9 +45,11 @@ The `layout` property allows for the radio group to be styled as a horizonally o
### Example
`collections/ExampleCollection.js`
```js
{
`collections/ExampleCollection.ts`
```ts
import { CollectionConfig } from 'payload/types';
const ExampleCollection: CollectionConfig = {
slug: 'example-collection',
fields: [
{

View File

@@ -69,26 +69,26 @@ The `filterOptions` property can either be a `Where` query directly, or a functi
**Example:**
```js
const relationshipField = {
name: 'purchase',
type: 'relationship',
relationTo: ['products', 'services'],
filterOptions: ({ relationTo, siblingData }) => {
// returns a Where query dynamically by the type of relationship
if (relationTo === 'products') {
return {
'stock': { is_greater_than: siblingData.quantity }
}
```ts
const relationshipField = {
name: 'purchase',
type: 'relationship',
relationTo: ['products', 'services'],
filterOptions: ({ relationTo, siblingData }) => {
// returns a Where query dynamically by the type of relationship
if (relationTo === 'products') {
return {
'stock': { is_greater_than: siblingData.quantity }
}
}
if (relationTo === 'services') {
return {
'isAvailable': { equals: true }
}
if (relationTo === 'services') {
return {
'isAvailable': { equals: true }
}
},
};
}
},
};
```
You can learn more about writing queries [here](/docs/queries/overview).
@@ -106,7 +106,7 @@ Given the variety of options possible within the `relationship` field type, the
The most simple pattern of a relationship is to use `hasMany: false` with a `relationTo` that allows for only one type of collection.
```js
```ts
{
slug: 'example-collection',
fields: [
@@ -137,7 +137,7 @@ When querying documents in this collection via REST API, you could query as foll
Also known as **dynamic references**, in this configuration, the `relationTo` field is an array of Collection slugs that tells Payload which Collections are valid to reference.
```js
```ts
{
slug: 'example-collection',
fields: [
@@ -176,7 +176,7 @@ This query would return only documents that have an owner relationship to organi
The `hasMany` tells Payload that there may be more than one collection saved to the field.
```js
```ts
{
slug: 'example-collection',
fields: [
@@ -204,7 +204,7 @@ When querying documents, the format does not change for arrays:
#### Has Many - Polymorphic
```js
```ts
{
slug: 'example-collection',
fields: [

View File

@@ -126,9 +126,11 @@ Custom `Leaf` objects follow a similar pattern but require you to define the `Le
### Example
`collections/ExampleCollection.js`
```js
{
`collections/ExampleCollection.ts`
```ts
import { CollectionConfig } from 'payload/types';
const ExampleCollection: CollectionConfig = {
slug: 'example-collection',
fields: [
{
@@ -178,7 +180,7 @@ Custom `Leaf` objects follow a similar pattern but require you to define the `Le
}
}
]
}
};
```
For more examples regarding how to define your own elements and leaves, check out the example [`RichText` field](https://github.com/payloadcms/public-demo/blob/master/src/fields/hero.ts) within the Public Demo source code.
@@ -187,7 +189,7 @@ For more examples regarding how to define your own elements and leaves, check ou
As the Rich Text field saves its content in a JSON format, you'll need to render it as HTML yourself. Here is an example for how to generate JSX / HTML from Rich Text content:
```js
```ts
import React, { Fragment } from 'react';
import escapeHTML from 'escape-html';
import { Text } from 'slate';
@@ -308,7 +310,7 @@ If you want to utilize this functionality within your own custom elements, you c
`customLargeBodyElement.js`:
```js
```ts
import Button from './Button';
import Element from './Element';
import withLargeBody from './plugin';
@@ -338,7 +340,7 @@ The plugin itself extends Payload's built-in `shouldBreakOutOnEnter` Slate funct
If you are building your own custom Rich Text elements or leaves, you may benefit from importing the following types:
```js
```ts
import type {
RichTextCustomElement,
RichTextCustomLeaf,

View File

@@ -21,9 +21,11 @@ keywords: row, fields, config, configuration, documentation, Content Management
### Example
`collections/ExampleCollection.js`
```js
{
`collections/ExampleCollection.ts`
```ts
import { CollectionConfig } from 'payload/types';
const ExampleCollection: CollectionConfig = {
slug: 'example-collection',
fields: [
{

View File

@@ -57,10 +57,11 @@ Set to `true` if you'd like this field to be sortable within the Admin UI using
### Example
`collections/ExampleCollection.js`
`collections/ExampleCollection.ts`
```ts
import { CollectionConfig } from 'payload/types';
```js
{
const ExampleCollection: CollectionConfig = {
slug: 'example-collection',
fields: [
{

View File

@@ -34,9 +34,11 @@ Each tab has its own required `label` and `fields` array. You can also optionall
### Example
`collections/ExampleCollection.js`
```js
{
`collections/ExampleCollection.ts`
```ts
import { CollectionConfig } from 'payload/types';
const ExampleCollection: CollectionConfig = {
slug: 'example-collection',
fields: [
{

View File

@@ -46,9 +46,11 @@ Set this property to a string that will be used for browser autocomplete.
### Example
`collections/ExampleCollection.js`
```js
{
`collections/ExampleCollection.ts`
```ts
import { CollectionConfig } from 'payload/types';
const ExampleCollection: CollectionConfig = {
slug: 'example-collection',
fields: [
{

View File

@@ -46,9 +46,11 @@ Set this property to a string that will be used for browser autocomplete.
### Example
`collections/ExampleCollection.js`
```js
{
`collections/ExampleCollection.ts`
```ts
import { CollectionConfig } from 'payload/types';
const ExampleCollection: CollectionConfig = {
slug: 'example-collection',
fields: [
{

View File

@@ -34,9 +34,11 @@ With this field, you can also inject custom `Cell` components that appear as add
### Example
`collections/ExampleCollection.js`
```js
{
`collections/ExampleCollection.ts`
```ts
import { CollectionConfig } from 'payload/types';
const ExampleCollection: CollectionConfig = {
slug: 'example-collection',
fields: [
{

View File

@@ -46,9 +46,11 @@ keywords: upload, images media, fields, config, configuration, documentation, Co
### Example
`collections/ExampleCollection.js`
```js
{
`collections/ExampleCollection.ts`
```ts
import { CollectionConfig } from 'payload/types';
const ExampleCollection: CollectionConfig = {
slug: 'example-collection',
fields: [
{

View File

@@ -33,7 +33,7 @@ Both `graphQL.queries` and `graphQL.mutations` functions should return an object
`payload.config.js`:
```js
```ts
import { buildConfig } from 'payload/config';
import myCustomQueryResolver from './graphQL/resolvers/myCustomQueryResolver';

View File

@@ -29,8 +29,10 @@ At the top of your Payload config you can define all the options to manage Graph
Everything that can be done to a Collection via the REST or Local API can be done with GraphQL (outside of uploading files, which is REST-only). If you have a collection as follows:
```js
const PublicUser = {
```ts
import { CollectionConfig } from 'payload/types';
const PublicUser: CollectionConfig = {
slug: 'public-users',
auth: true, // Auth is enabled
labels: {
@@ -70,8 +72,10 @@ const PublicUser = {
Globals are also fully supported. For example:
```js
const Header = {
```ts
import { GlobalConfig } from 'payload/types';
const Header: GlobalConfig = {
slug: 'header',
fields: [
...

View File

@@ -30,10 +30,11 @@ Additionally, `auth`-enabled collections feature the following hooks:
All collection Hook properties accept arrays of synchronous or asynchronous functions. Each Hook type receives specific arguments and has the ability to modify specific outputs.
`collections/example-hooks.js`
```js
// Collection config
module.exports = {
`collections/exampleHooks.js`
```ts
import { CollectionConfig } from 'payload/types';
const ExampleHooks: CollectionConfig = {
slug: 'example-hooks',
fields: [
{ name: 'name', type: 'text'},
@@ -65,8 +66,10 @@ The `beforeOperation` Hook type can be used to modify the arguments that operati
Available Collection operations include `create`, `read`, `update`, `delete`, `login`, `refresh` and `forgotPassword`.
```js
const beforeOperationHook = async ({
```ts
import { CollectionBeforeOperationHook } from 'payload/types';
const beforeOperationHook: CollectionBeforeOperationHook = async ({
args, // Original arguments passed into the operation
operation, // name of the operation
}) => {
@@ -78,8 +81,10 @@ const beforeOperationHook = async ({
Runs before the `create` and `update` operations. This hook allows you to add or format data before the incoming data is validated.
```js
const beforeValidateHook = async ({
```ts
import { CollectionBeforeOperationHook } from 'payload/types';
const beforeValidateHook: CollectionBeforeValidateHook = async ({
data, // incoming data to update or create with
req, // full express request
operation, // name of the operation ie. 'create', 'update'
@@ -93,8 +98,10 @@ const beforeValidateHook = async ({
Immediately following validation, `beforeChange` hooks will run within `create` and `update` operations. At this stage, you can be confident that the data that will be saved to the document is valid in accordance to your field validations. You can optionally modify the shape of data to be saved.
```js
const beforeChangeHook = async ({
```ts
import { CollectionBeforeChangeHook } from 'payload/types';
const beforeChangeHook: CollectionBeforeChangeHook = async ({
data, // incoming data to update or create with
req, // full express request
operation, // name of the operation ie. 'create', 'update'
@@ -108,8 +115,10 @@ const beforeChangeHook = async ({
After a document is created or updated, the `afterChange` hook runs. This hook is helpful to recalculate statistics such as total sales within a global, syncing user profile changes to a CRM, and more.
```js
const afterChangeHook = async ({
```ts
import { CollectionAfterChangeHook } from 'payload/types';
const afterChangeHook: CollectionAfterChangeHook = async ({
doc, // full document data
req, // full express request
operation, // name of the operation ie. 'create', 'update'
@@ -122,8 +131,10 @@ const afterChangeHook = async ({
Runs before `find` and `findByID` operations are transformed for output by `afterRead`. This hook fires before hidden fields are removed and before localized fields are flattened into the requested locale. Using this Hook will provide you with all locales and all hidden fields via the `doc` argument.
```js
const beforeReadHook = async ({
```ts
import { CollectionBeforeReadHook } from 'payload/types';
const beforeReadHook: CollectionBeforeReadHook = async ({
doc, // full document data
req, // full express request
query, // JSON formatted query
@@ -136,8 +147,10 @@ const beforeReadHook = async ({
Runs as the last step before documents are returned. Flattens locales, hides protected fields, and removes fields that users do not have access to.
```js
const afterReadHook = async ({
```ts
import { CollectionAfterReadHook } from 'payload/types';
const afterReadHook: CollectionAfterReadHook = async ({
doc, // full document data
req, // full express request
query, // JSON formatted query
@@ -151,8 +164,10 @@ const afterReadHook = async ({
Runs before the `delete` operation. Returned values are discarded.
```js
const beforeDeleteHook = async ({
```ts
import { CollectionBeforeDeleteHook } from 'payload/types';
const beforeDeleteHook: CollectionBeforeDeleteHook = async ({
req, // full express request
id, // id of document to delete
}) => {...}
@@ -162,8 +177,10 @@ const beforeDeleteHook = async ({
Runs immediately after the `delete` operation removes records from the database. Returned values are discarded.
```js
const afterDeleteHook = async ({
```ts
import { CollectionAfterDeleteHook } from 'payload/types';
const afterDeleteHook: CollectionAfterDeleteHook = async ({
req, // full express request
id, // id of document to delete
doc, // deleted document
@@ -174,8 +191,10 @@ const afterDeleteHook = async ({
For auth-enabled Collections, this hook runs after successful `login` operations. You can optionally modify the user that is returned.
```js
const beforeLoginHook = async ({
```ts
import { CollectionBeforeLoginHook } from 'payload/types';
const beforeLoginHook: CollectionBeforeLoginHook = async ({
req, // full express request
user, // user being logged in
token, // user token
@@ -188,8 +207,10 @@ const beforeLoginHook = async ({
For auth-enabled Collections, this hook runs after successful `login` operations. You can optionally modify the user that is returned.
```js
const afterLoginHook = async ({
```ts
import { CollectionAfterLoginHook } from 'payload/types';
const afterLoginHook: CollectionAfterLoginHook = async ({
req, // full express request
}) => {...}
```
@@ -198,8 +219,10 @@ const afterLoginHook = async ({
For auth-enabled Collections, this hook runs after `logout` operations.
```js
const afterLogoutHook = async ({
```ts
import { CollectionAfterLogoutHook } from 'payload/types';
const afterLogoutHook: CollectionAfterLogoutHook = async ({
req, // full express request
}) => {...}
```
@@ -208,8 +231,10 @@ const afterLogoutHook = async ({
For auth-enabled Collections, this hook runs after `refresh` operations.
```js
const afterRefreshHook = async ({
```ts
import { CollectionAfterRefreshHook } from 'payload/types';
const afterRefreshHook: CollectionAfterRefreshHook = async ({
req, // full express request
res, // full express response
token, // newly refreshed user token
@@ -220,8 +245,10 @@ const afterRefreshHook = async ({
For auth-enabled Collections, this hook runs after `me` operations.
```js
const afterMeHook = async ({
```ts
import { CollectionAfterMeHook } from 'payload/types';
const afterMeHook: CollectionAfterMeHook = async ({
req, // full express request
response, // response to return
}) => {...}
@@ -231,8 +258,10 @@ const afterMeHook = async ({
For auth-enabled Collections, this hook runs after successful `forgotPassword` operations. Returned values are discarded.
```js
const afterLoginHook = async ({
```ts
import { CollectionAfterForgotPasswordHook } from 'payload/types';
const afterLoginHook: CollectionAfterForgotPasswordHook = async ({
req, // full express request
user, // user being logged in
token, // user token
@@ -245,7 +274,7 @@ const afterLoginHook = async ({
Payload exports a type for each Collection hook which can be accessed as follows:
```js
```ts
import type {
CollectionBeforeOperationHook,
CollectionBeforeValidateHook,
@@ -262,7 +291,4 @@ import type {
CollectionAfterMeHook,
CollectionAfterForgotPasswordHook,
} from 'payload/types';
// Use hook types here...
}
```

View File

@@ -26,8 +26,10 @@ Field-level hooks offer incredible potential for encapsulating your logic. They
## Config
Example field configuration:
```js
{
```ts
import { CollectionConfig } from 'payload/types';
const ExampleCollection: CollectionConfig = {
name: 'name',
type: 'text',
// highlight-start
@@ -77,7 +79,7 @@ All field hooks can optionally modify the return value of the field before the o
Payload exports a type for field hooks which can be accessed and used as follows:
```js
```ts
import type { FieldHook } from 'payload/types';
// Field hook type is a generic that takes three arguments:

View File

@@ -19,9 +19,10 @@ Globals feature the ability to define the following hooks:
All Global Hook properties accept arrays of synchronous or asynchronous functions. Each Hook type receives specific arguments and has the ability to modify specific outputs.
`globals/example-hooks.js`
```js
// Global config
module.exports = {
```ts
import { GlobalConfig } from 'payload/types';
const ExampleHooks: GlobalConfig = {
slug: 'header',
fields: [
{ name: 'title', type: 'text'},
@@ -40,8 +41,10 @@ module.exports = {
Runs before the `update` operation. This hook allows you to add or format data before the incoming data is validated.
```js
const beforeValidateHook = async ({
```ts
import { GlobalBeforeValidateHook } from 'payload/types'
const beforeValidateHook: GlobalBeforeValidateHook = async ({
data, // incoming data to update or create with
req, // full express request
originalDoc, // original document
@@ -54,8 +57,10 @@ const beforeValidateHook = async ({
Immediately following validation, `beforeChange` hooks will run within the `update` operation. At this stage, you can be confident that the data that will be saved to the document is valid in accordance to your field validations. You can optionally modify the shape of data to be saved.
```js
const beforeChangeHook = async ({
```ts
import { GlobalBeforeChangeHook } from 'payload/types'
const beforeChangeHook: GlobalBeforeChangeHook = async ({
data, // incoming data to update or create with
req, // full express request
originalDoc, // original document
@@ -68,8 +73,10 @@ const beforeChangeHook = async ({
After a global is updated, the `afterChange` hook runs. Use this hook to purge caches of your applications, sync site data to CRMs, and more.
```js
const afterChangeHook = async ({
```ts
import { GlobalAfterChangeHook } from 'payload/types'
const afterChangeHook: GlobalAfterChangeHook = async ({
doc, // full document data
req, // full express request
}) => {
@@ -81,8 +88,10 @@ const afterChangeHook = async ({
Runs before `findOne` global operation is transformed for output by `afterRead`. This hook fires before hidden fields are removed and before localized fields are flattened into the requested locale. Using this Hook will provide you with all locales and all hidden fields via the `doc` argument.
```js
const beforeReadHook = async ({
```ts
import { GlobalBeforeReadHook } from 'payload/types'
const beforeReadHook: GlobalBeforeReadHook = async ({
doc, // full document data
req, // full express request
}) => {...}
@@ -92,8 +101,10 @@ const beforeReadHook = async ({
Runs as the last step before a global is returned. Flattens locales, hides protected fields, and removes fields that users do not have access to.
```js
const afterReadHook = async ({
```ts
import { GlobalAfterReadHook } from 'payload/types'
const afterReadHook: GlobalAfterReadHook = async ({
doc, // full document data
req, // full express request
findMany, // boolean to denote if this hook is running against finding one, or finding many (useful in versions)
@@ -104,7 +115,7 @@ const afterReadHook = async ({
Payload exports a type for each Global hook which can be accessed as follows:
```js
```ts
import type {
GlobalBeforeValidateHook,
GlobalBeforeChangeHook,
@@ -112,7 +123,4 @@ import type {
GlobalBeforeReadHook,
GlobalAfterReadHook,
} from 'payload/types';
// Use hook types here...
}
```

View File

@@ -28,10 +28,11 @@ You can gain access to the currently running `payload` object via two ways:
You can import or require `payload` into your own files after it's been initialized, but you need to make sure that your `import` / `require` statements come **after** you call `payload.init()`—otherwise Payload won't have been initialized yet. That might be obvious. To us, it's usually not.
Example:
```js
```ts
import payload from 'payload';
import { CollectionAfterChangeHook } from 'payload/types';
const afterChangeHook = async () => {
const afterChangeHook: CollectionAfterChangeHook = async () => {
const posts = await payload.find({
collection: 'posts',
});
@@ -43,8 +44,8 @@ const afterChangeHook = async () => {
Payload is available anywhere you have access to the Express `req` - including within your access control and hook functions.
Example:
```js
const afterChangeHook = async ({ req: { payload }}) => {
```ts
const afterChangeHook: CollectionAfterChangeHook = async ({ req: { payload }}) => {
const posts = await payload.find({
collection: 'posts',
});
@@ -319,3 +320,25 @@ const result = await payload.updateGlobal({
showHiddenFields: true,
})
```
## TypeScript
Local API calls also support passing in a generic. This is especially useful if you generate your TS types using a [generate types script](/docs/typescript/generate-types).
Here is an example of usage:
```ts
// Our generated types
import { Post } from './payload-types'
// Add Post types as generic to create function
const post: Post = await payload.create<Post>({
collection: 'posts',
// Data will now be typed as Post and give you type hints
data: {
title: 'my title',
description: 'my description',
},
})
```

View File

@@ -83,11 +83,10 @@ After all plugins are executed, the full config with all plugins will be sanitiz
Here is an example for how to automatically add a `lastModifiedBy` field to all Payload collections using a Plugin written in TypeScript.
```js
import { Config } from 'payload/config';
import { CollectionConfig } from 'payload/dist/collections/config/types';
```ts
import { Config, Plugin } from 'payload/config';
const addLastModified = (incomingConfig: Config): Config => {
const addLastModified: Plugin = (incomingConfig: Config): Config => {
// Find all incoming auth-enabled collections
// so we can create a lastModifiedBy relationship field
// to all auth collections

View File

@@ -37,7 +37,7 @@ Because _**you**_ are in complete control of who can do what with your data, you
Before running in Production, you need to have built a production-ready copy of the Payload Admin panel. To do this, Payload provides the `build` NPM script. You can use it by adding a `script` to your `package.json` file like this:
`package.json`:
```js
```json
{
"name": "project-name-here",
"scripts": {

View File

@@ -16,8 +16,10 @@ Payload provides an extremely granular querying language through all APIs. Each
For example, say you have a collection as follows:
```js
const Post = {
```ts
import { CollectionConfig } from 'payload/types';
const Post: CollectionConfig = {
slug: 'posts',
fields: [
{

View File

@@ -24,7 +24,7 @@ All collection `find` queries are paginated automatically. Responses are returne
| nextPage | `number` of next page, `null` if it doesn't exist |
**Example response:**
```js
```json
{
// Document Array // highlight-line
"docs": [

View File

@@ -89,9 +89,11 @@ Each endpoint object needs to have:
Example:
```js
```ts
import { CollectionConfig } from 'payload/types';
// a collection of 'orders' with an additional route for tracking details, reachable at /api/orders/:id/tracking
const Orders = {
const Orders: CollectionConfig = {
slug: 'orders',
fields: [ /* ... */ ],
// highlight-start

View File

@@ -55,38 +55,40 @@ _An asterisk denotes that a property above is required._
**Example Upload collection:**
```js
const Media = {
slug: "media",
```ts
import { CollectionConfig } from 'payload/types';
const Media: CollectionConfig = {
slug: 'media',
upload: {
staticURL: "/media",
staticDir: "media",
staticURL: '/media',
staticDir: 'media',
imageSizes: [
{
name: "thumbnail",
name: 'thumbnail',
width: 400,
height: 300,
crop: "centre",
crop: 'centre',
},
{
name: "card",
name: 'card',
width: 768,
height: 1024,
crop: "centre",
crop: 'centre',
},
{
name: "tablet",
name: 'tablet',
width: 1024,
// By specifying `null` or leaving a height undefined,
// the image will be sized to a certain width,
// but it will retain its original aspect ratio
// and calculate a height automatically.
height: null,
crop: "centre",
crop: 'centre',
},
],
adminThumbnail: "thumbnail",
mimeTypes: ["image/*"],
adminThumbnail: 'thumbnail',
mimeTypes: ['image/*'],
},
};
```
@@ -97,17 +99,17 @@ Payload relies on the [`express-fileupload`](https://www.npmjs.com/package/expre
A common example of what you might want to customize within Payload-wide Upload options would be to increase the allowed `fileSize` of uploads sent to Payload:
```js
import { buildConfig } from "payload/config";
```ts
import { buildConfig } from 'payload/config';
export default buildConfig({
collections: [
{
slug: "media",
slug: 'media',
fields: [
{
name: "alt",
type: "text",
name: 'alt',
type: 'text',
},
],
upload: true,
@@ -158,12 +160,14 @@ You can specify how Payload retrieves admin thumbnails for your upload-enabled C
**Example custom Admin thumbnail:**
```js
const Media = {
slug: "media",
```ts
import { CollectionConfig } from 'payload/types';
const Media: CollectionConfig = {
slug: 'media',
upload: {
staticURL: "/media",
staticDir: "media",
staticURL: '/media',
staticDir: 'media',
imageSizes: [
// ... image sizes here
],
@@ -191,13 +195,15 @@ Some example values are: `image/*`, `audio/*`, `video/*`, `image/png`, `applicat
**Example mimeTypes usage:**
```js
const Media = {
slug: "media",
```ts
import { CollectionConfig } from 'payload/types';
const Media: CollectionConfig = {
slug: 'media',
upload: {
staticURL: "/media",
staticDir: "media",
mimeTypes: ["image/*", "application/pdf"], // highlight-line
staticURL: '/media',
staticDir: 'media',
mimeTypes: ['image/*', 'application/pdf'], // highlight-line
},
};
```

View File

@@ -25,8 +25,10 @@ Collections and Globals both support the same options for configuring autosave.
**Example config with versions, drafts, and autosave enabled:**
```js
const Pages = {
```ts
import { CollectionConfig } from 'payload/types';
const Pages: CollectionConfig = {
slug: 'pages',
access: {
read: ({ req }) => {

View File

@@ -81,8 +81,10 @@ You can use the `read` [Access Control](/docs/access-control/collections#read) m
Here is an example that utilizes the `_status` field to require a user to be logged in to retrieve drafts:
```js
const Pages = {
```ts
import { CollectionConfig } from 'payload/types';
const Pages: CollectionConfig = {
slug: 'pages',
access: {
read: ({ req }) => {
@@ -114,8 +116,10 @@ const Pages = {
Here is an example for how to write an access control function that grants access to both documents where `_status` is equal to "published" and where `_status` does not exist:
```js
const Pages = {
```ts
import { CollectionConfig } from 'payload/types';
const Pages: CollectionConfig = {
slug: 'pages',
access: {
read: ({ req }) => {

View File

@@ -77,7 +77,7 @@ _slug_versions
Each document in this new `versions` collection will store a set of meta properties about the version as well as a _full_ copy of the document. For example, a version's data might look like this for a Collection document:
```js
```json
{
"_id": "61cf752c19cdf1b1af7b61f1", // a unique ID of this version
"parent": "61ce1354091d5b3ffc20ea6e", // the ID of the parent document