#Versions feature - how to return doc's current version id?

1 messages · Page 1 of 1 (latest)

pliant sparrow
#

We are using the versions feature with drafts enabled. We need to be able to determine the current version of a doc when retrieving it from the REST / GraphQL API. By default, it doesn't appear that payload explicitly stores any reference to the _versions index to tie a doc in a collection to it's current version.

We have initially tried to solve this with a afterRead hook that lists the versions for a doc, adding the latest version Id when returning it. This works, but has unfortunately had a significant negative impact on performance. When listing docs in a collection, the hook has to do a n+1 database query to get the version ID and hydrate the doc with it.

Is there a better way to do this? Ideally, we would love to have the versionId stored on a doc when the version is created. We can't quite figure out how to do this though. An afterRead hook is hydrating this after the fact but has bad performance. A beforeChange / beforeOperation hook doesn't seem like it would work because the version would not exist yet (?). Is there a performant way to store/retrieve the versionId of a document?

pine pollen
#

Since the queryDrafts method removes information about the version ID https://github.com/payloadcms/payload/blob/3b37f4a7b7c3abde642c9a7ca5d3036eee5a293f/packages/drizzle/src/queryDrafts.ts#L41-L46 it's not possible right now.
You can either optimize your hook - no need to list all the versions for a doc, just do limit: 1 and sort by -updatedAt with a query like where: { parent: id }, or better yet do a direct DB access.
Or patch the queryDrafts method in your database adapter package to a field like _versionID, that'd work perfectly and pretty easy to do but yeah no any native solution. Ideally it'd be something like find({ includeVersionID: true }).