Files
payload/packages/plugin-search/src/index.ts
James Mikrut 123125185c fix!: plugin-search with localization enabled (#8938)
The search plugin was incorrectly retrieving all locales, when it should
just be retrieving the locale of the parent document that was actively
being updated.

## BREAKING CHANGES:

If you have a localized Payload config, and you are using the `plugin-search`, we will now automatically localize the `title` field that is injected by the search plugin and this may lead to data loss. To opt out of this new behavior, you can pass `localize: false` to the plugin options.
2024-10-30 11:49:54 -04:00

83 lines
2.7 KiB
TypeScript

import type { CollectionAfterChangeHook, CollectionAfterDeleteHook, Config } from 'payload'
import type { SearchPluginConfig } from './types.js'
import { deleteFromSearch } from './Search/hooks/deleteFromSearch.js'
import { syncWithSearch } from './Search/hooks/syncWithSearch.js'
import { generateSearchCollection } from './Search/index.js'
type CollectionAfterChangeHookArgs = Parameters<CollectionAfterChangeHook>[0]
type CollectionAfterDeleteHookArgs = Parameters<CollectionAfterDeleteHook>[0]
export const searchPlugin =
(incomingPluginConfig: SearchPluginConfig) =>
(config: Config): Config => {
const { collections } = config
// If the user defines `localize` to either true or false, use that
// Otherwise, set it based on if their config has localization enabled or disabled
const shouldLocalize =
typeof incomingPluginConfig.localize === 'boolean'
? incomingPluginConfig.localize
: Boolean(config.localization)
incomingPluginConfig.localize = shouldLocalize
if (collections) {
const pluginConfig: SearchPluginConfig = {
// write any config defaults here
deleteDrafts: true,
syncDrafts: false,
...incomingPluginConfig,
}
// add afterChange and afterDelete hooks to every search-enabled collection
const collectionsWithSearchHooks = config?.collections
?.map((collection) => {
const { hooks: existingHooks } = collection
const enabledCollections = pluginConfig.collections || []
const isEnabled = enabledCollections.indexOf(collection.slug) > -1
if (isEnabled) {
return {
...collection,
hooks: {
...collection.hooks,
afterChange: [
...(existingHooks?.afterChange || []),
async (args: CollectionAfterChangeHookArgs) => {
await syncWithSearch({
...args,
collection: collection.slug,
pluginConfig,
})
},
],
afterDelete: [
...(existingHooks?.afterDelete || []),
async (args: CollectionAfterDeleteHookArgs) => {
await deleteFromSearch({
...args,
pluginConfig,
})
},
],
},
}
}
return collection
})
.filter(Boolean)
return {
...config,
collections: [
...(collectionsWithSearchHooks || []),
generateSearchCollection(pluginConfig),
],
}
}
return config
}