Skip to content

Commit

Permalink
feat(og-image): ✨ add og-image for posts that have cover
Browse files Browse the repository at this point in the history
  • Loading branch information
BeiyanYunyi committed Sep 7, 2024
1 parent 4fcc832 commit 4cce346
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 1 deletion.
7 changes: 6 additions & 1 deletion src/components/BlogPost.astro
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import ArticleTime from '@components/ArticleTime.astro';
import BaseLayout from '../layouts/BaseLayout.astro';
import { Image } from 'astro:assets';
import type { CollectionEntry } from 'astro:content';
import svgPathToName from '@utils/svgPathToName';
export type Props = {
remarkPluginFrontmatter: any;
Expand All @@ -18,7 +19,11 @@ export type Props = {
const { title, slug, remarkPluginFrontmatter, description, tag, date, image } = Astro.props;
---

<BaseLayout title={title} description={description} image={image?.src}>
<BaseLayout
title={title}
description={description}
image={image?.src ? `/og-image/${svgPathToName(image?.src)}.png` : '/头像方.png'}
>
<div class="flex">
<div class="flex-grow min-w-0">
<article class="prose prose-neutral dark:prose-invert max-w-full card overflow-clip">
Expand Down
22 changes: 22 additions & 0 deletions src/pages/og-image/[...slug].png.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import svgPathToName from '@utils/svgPathToName';
import type { APIRoute, GetStaticPaths } from 'astro';
import { getCollection, type CollectionEntry } from 'astro:content';
import sharp from 'sharp';

export const getStaticPaths = (async () => {
const blogEntries = await getCollection('posts');
return blogEntries
.filter((i) => !!i.data.image)
.map((entry) => ({
params: { slug: svgPathToName(entry.data.image!.src) },
props: entry,
}));
}) satisfies GetStaticPaths;

export const GET: APIRoute<CollectionEntry<'posts'>> = async ({ props }) => {
const image = await sharp(`./dist${props.data.image!.src}`)
.resize(1200, 630, { fit: 'contain' })
.png()
.toBuffer();
return new Response(image.buffer);
};
5 changes: 5 additions & 0 deletions src/utils/svgPathToName.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
const svgNameReg = /[. \w-]+(?=\.svg)/;

const svgPathToName = (path: string) => svgNameReg.exec(path)![0];

export default svgPathToName;

0 comments on commit 4cce346

Please sign in to comment.