fix: prevent duplicate tags

This commit is contained in:
Derrick Hammer 2023-12-27 11:41:13 -05:00
parent 3ca61c2b7a
commit f3c38dea8e
Signed by: pcfreak30
GPG Key ID: C997C339BE476FF2
1 changed files with 43 additions and 7 deletions

View File

@ -11,7 +11,6 @@ interface GenerateMetaTagsParams {
ogType?: "website" | "article"; ogType?: "website" | "article";
parentMeta?: ServerRuntimeMetaArgs; parentMeta?: ServerRuntimeMetaArgs;
} }
export function generateMetaTags({ export function generateMetaTags({
title, title,
description, description,
@ -19,14 +18,44 @@ export function generateMetaTags({
ogType = "website", ogType = "website",
parentMeta, parentMeta,
}: GenerateMetaTagsParams) { }: GenerateMetaTagsParams) {
let parentMetaMerged: ServerRuntimeMetaDescriptor[] = []; const metaTags: Record<string, ServerRuntimeMetaDescriptor> = {};
if (parentMeta?.matches) { // Helper function to generate a unique key for each meta tag
parentMetaMerged = parentMeta?.matches.flatMap((match) => match.meta ?? []); const generateKey = (tag: ServerRuntimeMetaDescriptor): string => {
} if ("name" in tag && tag.name) {
return `name:${tag.name}`;
}
if ("property" in tag && tag.property) {
return `property:${tag.property}`;
}
if ("httpEquiv" in tag && tag.httpEquiv)
return `httpEquiv:${tag.httpEquiv}`;
if ("charSet" in tag) {
return "charSet";
}
if ("title" in tag) {
return "title";
}
if ("script:ld+json" in tag) {
return "script:ld+json";
}
if ("tagName" in tag && tag.tagName) {
return `tagName:${tag.tagName}`;
}
// Fallback for complex or unknown types - convert to JSON string
return `unknown:${JSON.stringify(tag)}`;
};
return [ // Merge parent meta tags
...parentMetaMerged, parentMeta?.matches?.forEach((match) => {
match.meta?.forEach((tag) => {
const key = generateKey(tag);
metaTags[key] = tag;
});
});
// Define new meta tags and add or overwrite them in the metaTags object
const newMetaTags: ServerRuntimeMetaDescriptor[] = [
{ title }, { title },
{ name: "title", content: title }, { name: "title", content: title },
{ name: "description", content: description }, { name: "description", content: description },
@ -35,4 +64,11 @@ export function generateMetaTags({
{ name: "og:image", content: imageUrl }, { name: "og:image", content: imageUrl },
{ name: "og:type", content: ogType }, { name: "og:type", content: ogType },
]; ];
newMetaTags.forEach((tag) => {
const key = generateKey(tag);
metaTags[key] = tag;
});
return Object.values(metaTags);
} }