Created
August 20, 2025 08:45
-
-
Save manabuyasuda/ac01fe988ee7178220e88c88e3fd6e06 to your computer and use it in GitHub Desktop.
generateMetadataにあるparentを扱いやすくするヘルパー関数
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * 親セグメントから特定のメタデータを取得する | |
| * 指定されたプロパティの存在するフィールドのみをフィルタリングして取得する | |
| * @param parentMetadata 親セグメントから取得するメタデータ | |
| * @param propertyName 取得したいプロパティ名('openGraph', 'alternates'など) | |
| * @example | |
| * import type { Metadata, ResolvingMetadata } from 'next'; | |
| * import { getParentMetadataProperty } from '@/lib/metadata/helpers'; | |
| * | |
| * export async function generateMetadata( | |
| * { params }: { params: Promise<{ lang: string; id: string }> }, | |
| * parent: ResolvingMetadata, | |
| * ): Promise<Metadata> { | |
| * const { lang, id } = await params; | |
| * const pageUrl = buildAbsoluteUrl([lang, 'article', id]); | |
| * | |
| * return { | |
| * openGraph: { | |
| * // ogp画像やlocaleなどをコピーして上書きする | |
| * ...await getParentMetadataProperty(parent, 'openGraph'), | |
| * type: 'website', // 親のtypeを上書き | |
| * url: pageUrl, // ページ固有のURLを追加 | |
| * }, | |
| * alternates: { | |
| * // languagesでhreflangを指定しているのでコピーする | |
| * ...await getParentMetadataProperty(parent, 'alternates'), | |
| * canonical: pageUrl, // canonicalを追加/上書き | |
| * }, | |
| * }; | |
| * } | |
| */ | |
| export async function getParentMetadataProperty<K extends keyof Metadata>( | |
| parentMetadata: ResolvingMetadata, | |
| propertyName: K, | |
| ): Promise<Partial<NonNullable<Metadata[K]>>> { | |
| const resolved = await parentMetadata; | |
| const parentProperty = resolved[propertyName]; | |
| if (!parentProperty || typeof parentProperty !== 'object') { | |
| return {}; | |
| } | |
| // 存在するフィールドを動的にフィルタリングして取得 | |
| const result: Record<string, unknown> = {}; | |
| for (const [key, value] of Object.entries(parentProperty)) { | |
| // 値が存在する場合のみ取得 | |
| if (value !== undefined && value !== null) { | |
| result[key] = value; | |
| } | |
| } | |
| return result as Partial<NonNullable<Metadata[K]>>; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment