Add basic forms and routes

This commit is contained in:
Thilo Hohlt
2024-08-01 18:09:35 +02:00
parent d21e00a0c3
commit b0666f4a8c
20 changed files with 762 additions and 342 deletions

View File

@@ -0,0 +1,103 @@
export const load = async ({ params, fetch, cookies, url, parent }) => {
const searchQuery = url.searchParams.get("article_search_query");
const sortBy = url.searchParams.get("article_sort");
const parameters = new URLSearchParams();
const baseFetchUrl = `http://localhost:3000/article?website_id=eq.${params.websiteId}&select=id,title`;
if (searchQuery) {
parameters.append("title", `ilike.*${searchQuery}*`);
}
switch (sortBy) {
case null:
case "creation-time":
parameters.append("order", "created_at.desc");
break;
case "last-modified":
parameters.append("order", "last_modified_at.desc");
break;
case "title-a-to-z":
parameters.append("order", "title.asc");
break;
case "title-z-to-a":
parameters.append("order", "title.desc");
break;
}
const constructedFetchUrl = `${baseFetchUrl}&${parameters.toString()}`;
const totalArticlesData = await fetch(baseFetchUrl, {
method: "HEAD",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${cookies.get("session_token")}`,
Prefer: "count=exact"
}
});
const totalArticleCount = Number(
totalArticlesData.headers.get("content-range")?.split("/").at(-1)
);
const articlesData = await fetch(constructedFetchUrl, {
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${cookies.get("session_token")}`
}
});
const articles = await articlesData.json();
const { website } = await parent();
return {
totalArticleCount,
articles,
website
};
};
export const actions = {
createArticle: async ({ request, fetch, cookies, params }) => {
const data = await request.formData();
const res = await fetch("http://localhost:3000/article", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${cookies.get("session_token")}`
},
body: JSON.stringify({
website_id: params.websiteId,
title: data.get("title")
})
});
if (!res.ok) {
const response = await res.json();
return { success: false, message: response.message };
}
return { success: true, message: "Successfully created article" };
},
deleteArticle: async ({ request, fetch, cookies }) => {
const data = await request.formData();
const res = await fetch(`http://localhost:3000/article?id=eq.${data.get("id")}`, {
method: "DELETE",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${cookies.get("session_token")}`
}
});
if (!res.ok) {
const response = await res.json();
return { success: false, message: response.message };
}
return { success: true, message: "Successfully deleted article" };
}
};

View File

@@ -0,0 +1,82 @@
<script lang="ts">
import WebsiteEditor from "$lib/components/WebsiteEditor.svelte";
import { sortOptions } from "$lib/utils.js";
import { page } from "$app/stores";
import { enhance } from "$app/forms";
const { data, form } = $props();
</script>
{#if form?.success}
<p>{form.message}</p>
{/if}
{#if form?.success === false}
<p>{form.message}</p>
{/if}
<WebsiteEditor
id={data.website.id}
title={data.website.title}
previewContent={data.home.main_content}
>
<section>
<h2>Create article</h2>
<form method="POST" action="?/createArticle" use:enhance>
<label>
Title:
<input type="text" name="title" />
</label>
<button type="submit">Submit</button>
</form>
</section>
{#if data.totalArticleCount > 0}
<section>
<h2>All articles</h2>
<form method="GET">
<label>
Search:
<input
type="text"
name="article_search_query"
value={$page.url.searchParams.get("article_search_query")}
/>
</label>
<label>
Sort:
<select name="article_sort">
{#each sortOptions as { value, text }}
<option {value} selected={value === $page.url.searchParams.get("article_sort")}
>{text}</option
>
{/each}
</select>
</label>
<button type="submit">Submit</button>
</form>
{#each data.articles as { id, title }}
<article>
<h3>{title}</h3>
<a href="/website/{data.website.id}/articles/{id}">Edit</a>
<details>
<summary>Delete</summary>
<p>
<strong>Caution!</strong>
Deleting this article will irretrievably erase all data.
</p>
<form method="POST" action="?/deleteArticle" use:enhance>
<input type="hidden" name="id" value={id} />
<button type="submit">Permanently delete article</button>
</form>
</details>
</article>
{/each}
</section>
{/if}
</WebsiteEditor>

View File

@@ -0,0 +1,59 @@
import { handleFileUpload } from "$lib/server/utils.js";
export const load = async ({ parent, params, cookies, fetch }) => {
const articleData = await fetch(`http://localhost:3000/article?id=eq.${params.articleId}`, {
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${cookies.get("session_token")}`,
Accept: "application/vnd.pgrst.object+json"
}
});
const article = await articleData.json();
const { website } = await parent();
return { website, article };
};
export const actions = {
default: async ({ fetch, cookies, request, params, locals }) => {
const data = await request.formData();
const coverFile = data.get("cover-image") as File;
const cover = await handleFileUpload(
coverFile,
params.websiteId,
locals.user.id,
cookies.get("session_token"),
fetch
);
if (cover?.success === false) {
return cover;
}
const res = await fetch(`http://localhost:3000/article?id=eq.${params.articleId}`, {
method: "PATCH",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${cookies.get("session_token")}`
},
body: JSON.stringify({
title: data.get("title"),
meta_description: data.get("description"),
meta_author: data.get("author"),
cover_image: cover?.content,
publication_date: data.get("publication-date"),
main_content: data.get("main-content")
})
});
if (!res.ok) {
const response = await res.json();
return { success: false, message: response.message };
}
return { success: true, message: "Successfully updated article" };
}
};

View File

@@ -0,0 +1,62 @@
<script lang="ts">
import { enhance } from "$app/forms";
import WebsiteEditor from "$lib/components/WebsiteEditor.svelte";
import { ALLOWED_MIME_TYPES } from "$lib/utils";
const { data, form } = $props();
</script>
{#if form?.success}
<p>{form.message}</p>
{/if}
{#if form?.success === false}
<p>{form.message}</p>
{/if}
<WebsiteEditor
id={data.website.id}
title={data.website.title}
previewContent={data.article.main_content}
>
<section>
<h2>Edit article</h2>
<form
method="POST"
enctype="multipart/form-data"
use:enhance={() => {
return async ({ update }) => {
await update({ reset: false });
};
}}
>
<label>
Title:
<input type="text" name="title" value={data.article.title} />
</label>
<label>
Description:
<textarea name="description">{data.article.meta_description}</textarea>
</label>
<label>
Author:
<input type="text" name="author" value={data.article.meta_author} />
</label>
<label>
Publication date:
<input type="date" name="publication-date" value={data.article.publication_date} />
</label>
<label>
Cover image:
<input type="file" name="cover-image" accept={ALLOWED_MIME_TYPES.join(", ")} />
</label>
<label>
Main content:
<textarea name="main-content">{data.article.main_content}</textarea>
</label>
<button type="submit">Submit</button>
</form>
</section>
</WebsiteEditor>