add generic page getter

This commit is contained in:
Hamcha 2023-07-11 12:56:49 +02:00
parent caab95179f
commit ce5c3e33ab
Signed by: hamcha
GPG key ID: 1669C533B8CF6D89
4 changed files with 64 additions and 0 deletions

25
src/lib/mabel-types.ts Normal file
View file

@ -0,0 +1,25 @@
export interface Site {
name: string;
owner: string;
owner_display_name: string;
title: string;
description: string | null;
created_at: string;
modified_at: string | null;
deleted_at: string | null;
}
export interface Post {
id: string;
site: string;
author: string;
author_display_name: string;
slug: string;
title: string;
description: string | null;
tags: string[];
blocks: [];
created_at: string;
modified_at: string | null;
deleted_at: string | null;
}

5
src/lib/url.ts Normal file
View file

@ -0,0 +1,5 @@
import { PUBLIC_DOMAIN } from '$env/static/public';
export function getSiteName(origin: string) {
return origin.substring(0, origin.indexOf(PUBLIC_DOMAIN)).replaceAll('.', '');
}

View file

@ -0,0 +1,14 @@
<script lang="ts">
import type { PageData } from './$types';
export let data: PageData;
</script>
<svelte:head>
<title>{data.site.title} - {data.page.title}</title>
</svelte:head>
<header><h2>{data.site.title}</h2></header>
<h1>{data.page.title}</h1>
by {data.page.author_display_name}

View file

@ -0,0 +1,20 @@
import { error } from '@sveltejs/kit';
import type { PageLoad } from './$types';
import { PUBLIC_API_BASE } from '$env/static/public';
import { getSiteName } from '$lib/url';
import type { Post, Site } from '$lib/mabel-types';
export const load = (async ({ url, params }) => {
const site = getSiteName(url.hostname);
const siteData = await fetch(`${PUBLIC_API_BASE}/sites/${site}`);
if (siteData.status === 404) throw error(404, 'Not Found');
const pageData = await fetch(`${PUBLIC_API_BASE}/posts/${site}/${params.slug}`);
if (pageData.status === 404) throw error(404, 'Not Found');
return {
site: (await siteData.json()) as Site,
page: (await pageData.json()) as Post
};
}) satisfies PageLoad;