### What?
Adds `populate` property to Local API and REST API operations that can
be used to specify `select` for a specific collection when it's
populated
```ts
const result = await payload.findByID({
populate: {
// type safe if you have generated types
posts: {
text: true,
},
},
collection: 'pages',
depth: 1,
id: aboutPage.id,
})
result.relatedPost // only has text and id properties
```
```ts
fetch('https://localhost:3000/api/pages?populate[posts][text]=true') // highlight-line
.then((res) => res.json())
.then((data) => console.log(data))
```
It also overrides
[`defaultPopulate`](https://github.com/payloadcms/payload/pull/8934)
Ensures `defaultPopulate` doesn't affect GraphQL.
### How?
Implements the property for all operations that have the `depth`
argument.
57 lines
1.6 KiB
TypeScript
57 lines
1.6 KiB
TypeScript
import { getTranslation } from '@payloadcms/translations'
|
|
import httpStatus from 'http-status'
|
|
import { duplicateOperation } from 'payload'
|
|
import { isNumber } from 'payload/shared'
|
|
|
|
import type { CollectionRouteHandlerWithID } from '../types.js'
|
|
|
|
import { headersWithCors } from '../../../utilities/headersWithCors.js'
|
|
import { sanitizeCollectionID } from '../utilities/sanitizeCollectionID.js'
|
|
import { sanitizePopulate } from '../utilities/sanitizePopulate.js'
|
|
import { sanitizeSelect } from '../utilities/sanitizeSelect.js'
|
|
|
|
export const duplicate: CollectionRouteHandlerWithID = async ({
|
|
id: incomingID,
|
|
collection,
|
|
req,
|
|
}) => {
|
|
const { searchParams } = req
|
|
const depth = searchParams.get('depth')
|
|
// draft defaults to true, unless explicitly set requested as false to prevent the newly duplicated document from being published
|
|
const draft = searchParams.get('draft') !== 'false'
|
|
|
|
const id = sanitizeCollectionID({
|
|
id: incomingID,
|
|
collectionSlug: collection.config.slug,
|
|
payload: req.payload,
|
|
})
|
|
|
|
const doc = await duplicateOperation({
|
|
id,
|
|
collection,
|
|
depth: isNumber(depth) ? Number(depth) : undefined,
|
|
draft,
|
|
populate: sanitizePopulate(req.query.populate),
|
|
req,
|
|
select: sanitizeSelect(req.query.select),
|
|
})
|
|
|
|
const message = req.t('general:successfullyDuplicated', {
|
|
label: getTranslation(collection.config.labels.singular, req.i18n),
|
|
})
|
|
|
|
return Response.json(
|
|
{
|
|
doc,
|
|
message,
|
|
},
|
|
{
|
|
headers: headersWithCors({
|
|
headers: new Headers(),
|
|
req,
|
|
}),
|
|
status: httpStatus.OK,
|
|
},
|
|
)
|
|
}
|