我有一台 Ghost 服务器,然后我有一个带有 sveltekit 的服务器。在我的幽灵中,我已将网站设为私有,因此我只能通过 API 访问。我已经设置了集成并收到了 API 令牌。当我尝试文档中的示例代码时,我无法获取帖子。我不确定我错过了什么。当我尝试导入 SDK 时,它在我的代码中出现错误。
这是代码:
<script context='module'>
import GhostContentAPI from '@tryghost/content-api';
// const GhostContentAPI = require('@tryghost/content-api');
const GHOST_URL = 'http://blog.nafuna.tv';
const GHOST_KEY = '87f6096411ae42f96df2615620';
const GHOST_VERSION = 'v4';
export async function load() {
const api = GhostContentAPI({
url: GHOST_URL,
key: GHOST_KEY,
version: GHOST_VERSION})
const postsJson = await api.posts.browse({limit: 5, include: 'tags,authors'});
return {
props: {
postsJson: postsJson
}
}
}
</script>
<script lang="ts">
import type { PageData } from './$types';
// export let postsJson;
export let data: PageData;
</script>
这是我的解决方案,使用 Svelte v3.59、TypeScript v5.04、TryGhost/content-api v1.11、@types/TryGhost v1.3.11
+布局.ts
import GhostContentAPI from '@tryghost/content-api';
/** @type {import('./$types').PageServerLoad} */
export async function load() {
const GHOST_URL = 'https://ghost.address';
const GHOST_KEY = 'authentication_key';
const GHOST_VERSION = 'v5.0';
const api = GhostContentAPI({
url: GHOST_URL,
key: GHOST_KEY,
version: GHOST_VERSION
});
try {
const postsJson = await api.posts.browse({limit: 5, include: ['tags', 'authors']});
return {
posts: postsJson.map((post) => ({
title: post.title? post.title : 'No title',
slug: post.slug!,
updated_at: post.updated_at!,
feature_image: post.feature_image? post.feature_image : 'https://ghost.address/placeholder.png',
feature_image_alt: post.feature_image_alt? post.feature_image_alt : '',
excerpt: post.excerpt? post.excerpt : '',
tags: post.tags!.map(tag => tag.name),
authors: post.authors?.map(author => author.name) || ['Unknown author'],
})),
};
} catch (error) {
console.error(error);
}
}
此数据被传递到 +page.svelte(也可以是+layout.svelte)
<script>
import Post from "$lib/components/Post.svelte";
export let data;
</script>
{#each data.posts ?? [] as post}
<Post {...post} />
{/each}
正如你所看到的,它是由 Post 组件呈现的 后.svelte
<script lang="ts">
export let title: string,
slug: string,
feature_image: string,
feature_image_alt: string,
updated_at: string,
tags: (string | undefined)[],
authors: string[],
excerpt: string;
const date = new Date(updated_at);
const time = date.toLocaleTimeString('pl-PL', {
day: 'numeric',
month: 'numeric',
year: 'numeric',
hour: '2-digit',
minute: '2-digit'
});
</script>
<a id="post" data-sveltekit-preload-data="hover" href={`/blog/${slug}`}>
<img loading="lazy" src={feature_image} alt={feature_image_alt} />
<div id="post-text">
<h1>{title}</h1>
<p id="post-text-p">{@html excerpt}</p>
<div id="info">
{#each authors as author}
<p>{author}</p>
{/each}
<p>{time}</p>
</div>
</div>
</a>