contentful-utility-suite
Version:
Suite of utilities for Contentful CMS
33 lines (32 loc) • 1.2 kB
JavaScript
import { CONTENTFUL_URL } from "./constants.js";
export function searchEntries(entries, searchString) {
const results = [];
entries.forEach((entry) => {
const { fields, sys } = entry;
const matches = {};
for (const [fieldKey, localizedField] of Object.entries(fields)) {
const matchedLocales = Object.entries(localizedField).filter(([locale, value]) => typeof value === "string" && value.toLocaleLowerCase().includes(searchString.toLocaleLowerCase()));
if (matchedLocales.length > 0) {
matches[fieldKey] = matchedLocales.map(([locale]) => locale);
}
}
let title = undefined;
if (fields.name) {
title = fields.name["en-US"];
}
if (Object.keys(matches).length > 0) {
results.push({
entryId: sys.id,
urn: convertUrnToUrl(sys.urn),
matches,
contentType: sys.contentType.sys.id,
title,
});
}
});
return results;
}
function convertUrnToUrl(urn) {
const pattern = /.*?(spaces\/.*)/;
return urn.replace(pattern, `${CONTENTFUL_URL}/$1`);
}