mirror of
https://litchi.icu/ngc2207/judge4c-demo.git
synced 2025-05-18 16:17:25 +00:00
feat: 添加创建代码片段界面内容验证
This commit is contained in:
parent
3474cb11af
commit
a817f718d5
@ -17,3 +17,32 @@ export async function deleteSnippet(id: number) {
|
||||
|
||||
redirect("/");
|
||||
}
|
||||
|
||||
export async function createSnippet(
|
||||
formState: { message: string },
|
||||
formData: FormData
|
||||
) {
|
||||
// Check the user's inputs and make sure they're valid
|
||||
const title = formData.get("title");
|
||||
const code = formData.get("code");
|
||||
if (typeof title !== "string" || title.length < 3) {
|
||||
return {
|
||||
message: "Title must be longer",
|
||||
};
|
||||
}
|
||||
if (typeof code !== "string" || code.length < 10) {
|
||||
return {
|
||||
message: "Code must be longer",
|
||||
};
|
||||
}
|
||||
// Create a new record in the database
|
||||
const snippet = await db.snippet.create({
|
||||
data: {
|
||||
title: title,
|
||||
code: code,
|
||||
},
|
||||
});
|
||||
console.log(snippet);
|
||||
// Redirect the user back to the root route
|
||||
redirect("/");
|
||||
}
|
||||
|
@ -1,26 +1,15 @@
|
||||
import { db } from "@/db";
|
||||
import { redirect } from "next/navigation";
|
||||
"use client";
|
||||
|
||||
import * as actions from "@/actions";
|
||||
import { useActionState } from "react";
|
||||
|
||||
export default function SnippetCreatePage() {
|
||||
async function createSnippet(formData: FormData) {
|
||||
// This needs to be a server action!
|
||||
"use server";
|
||||
// Check the user's inputs and make sure they're valid
|
||||
const title = formData.get("title") as string;
|
||||
const code = formData.get("code") as string;
|
||||
// Create a new record in the database
|
||||
const snippet = await db.snippet.create({
|
||||
data: {
|
||||
title: title,
|
||||
code: code,
|
||||
},
|
||||
});
|
||||
console.log(snippet);
|
||||
// Redirect the user back to the root route
|
||||
redirect("/");
|
||||
}
|
||||
const [formState, action] = useActionState(actions.createSnippet, {
|
||||
message: "",
|
||||
});
|
||||
|
||||
return (
|
||||
<form action={createSnippet}>
|
||||
<form action={action}>
|
||||
<h3 className="font-bold m-3">Create a Snippet</h3>
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="flex gap-4">
|
||||
@ -39,6 +28,13 @@ export default function SnippetCreatePage() {
|
||||
</label>
|
||||
<input name="code" className="border rounded p-2 w-full" id="code" />
|
||||
</div>
|
||||
|
||||
{formState.message ? (
|
||||
<div className="my-2 p-2 bg-red-200 border rounded border-red-400">
|
||||
{formState.message}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<button type="submit" className="rounded p-2 bg-blue-200">
|
||||
Create
|
||||
</button>
|
||||
|
Loading…
Reference in New Issue
Block a user