Skip to content

Commit

Permalink
validate data and save it correctly
Browse files Browse the repository at this point in the history
  • Loading branch information
clementvt committed Jan 4, 2025
1 parent 8fcbb24 commit 6fdd591
Show file tree
Hide file tree
Showing 10 changed files with 283 additions and 341 deletions.
13 changes: 7 additions & 6 deletions components/dashboard/guild/editor/appInitialiser.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,27 @@
"use client";
import { useWelcomerStore } from "@/state/welcomer";
import { Leaver, Welcomer } from "@prisma/client";
import { useEffect } from "react";

export default function AppInitializer({
module,
guildId,
children,
}: {
module?: Welcomer | Leaver | null;
guildId: string;
module?: Welcomer | Leaver | null;
guildId: string;
children: React.ReactNode;
}) {

const welcomerStore = useWelcomerStore((state) => state.id);
if (!welcomerStore) {
const reset = useWelcomerStore((state) => state.reset);
useEffect(() => {
reset();
useWelcomerStore.setState({
id: module?.id,
guildId: guildId,
channelId: module?.channelId,
content: module?.content,
...module,
});
}
}, [module, guildId, reset]);
return <>{children}</>;
}
2 changes: 1 addition & 1 deletion components/dashboard/guild/editor/editor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export function Editor({ guildId }: { guildId: string }) {
<Divider className="my-4" />
<ContentEditor />
<EmbedEditor />
<SaveButton guildId={guildId}/>
<SaveButton/>
</form>
</div>
<div className="block pb-20 w-full lg:w-1/2 lg:h-full bg-dark-4 lg:overflow-y-auto no-scrollbar">
Expand Down
5 changes: 2 additions & 3 deletions components/dashboard/guild/editor/saveButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,8 @@ import { Button } from "@nextui-org/button";
import { Card, CardBody } from "@nextui-org/card";
import { toast } from "react-toastify";

export default function SaveButton({ guildId }: { guildId: string }) {
export default function SaveButton() {
const store = useWelcomerStore((state) => state);

return (
<Card className="fixed bottom-5">
<CardBody>
Expand All @@ -18,7 +17,7 @@ export default function SaveButton({ guildId }: { guildId: string }) {
const res = await updateWelcomer(store);
if (res?.error) {
toast.error(res.error);
} else {
} else if (res.done) {
toast.success("Welcomer settings updated");
}
}}
Expand Down
151 changes: 85 additions & 66 deletions lib/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,11 +43,6 @@ export async function updateWelcomer(store: WelcomerStore) {
error: "You do not have permission to manage this guild",
};
}
// if (!store.content && store.embeds.length === 0) {
// return {
// error: "You need to add some content or embeds",
// };
// }
if (!store.channelId) {
return {
error: "You need to select a channel",
Expand All @@ -71,43 +66,63 @@ export async function updateWelcomer(store: WelcomerStore) {
},
});

console.log(module);

console.log(store)
for (const embed of store.embeds) {
if (embed.id && embed.welcomerId && module.id != embed.welcomerId) return {
error: "You cannot update an embed that is not in the welcomer",
}
const embedUpdated = await createOrUpdateEmbed(
embed,
module.id,
"welcomer",
"welcomer"
);
if (!embedUpdated) {
return {
error: "An error occurred while updating the welcomer module",
};
}
store.embeds[store.embeds.indexOf(embed)] = embedUpdated;
}
for (const embed of store.deletedEmbeds) {
if (embed.id) {
if (embed.welcomerId && module.id != embed.welcomerId) return {
error: "You cannot delete an embed that is not in the welcomer",
}
await prisma.embed.delete({
where: {
id: embed.id,
welcomerId: module.id,
},
include: {
author: true,
footer: true,
fields: true,
image: true,
}
});
}
}
}
store.deletedEmbeds = [];
for (const field of store.deletedFields) {
if (field.id) {
await prisma.embedField.delete({
where: {
id: field.id,
},
});
}
if (field.embedId && !(field.embedId in store.embeds)) return {
error: "You cannot delete a field that is not in the embed",
}
await prisma.embedField.delete({
where: {
id: field.id,
},
});
}
}
store.deletedFields = [];

revalidatePath(`/app/dashboard/${guildId}/welcome`);

return {
done: true,
};
} catch (error) {
console.log(error);
revalidatePath(`/app/dashboard/${store.guildId}/welcome`);

return {
error: "An error occurred while updating the welcomer module",
};
Expand All @@ -117,15 +132,16 @@ export async function updateWelcomer(store: WelcomerStore) {
export async function createOrUpdateEmbed(
embed: CompleteEmbed,
moduleId: number,
moduleType: "welcomer" | "leaver",
) {
moduleType: "welcomer" | "leaver"
):Promise<CompleteEmbed | null> {
let embedDb;
const createOrUpdateAuthor = {
author: embed.author?.name
? {
upsert: {
where: {
embedId: embed.id,
[`${moduleType}Id`]: moduleId,
},
update: {
name: embed.author?.name,
Expand All @@ -149,6 +165,7 @@ export async function createOrUpdateEmbed(
upsert: {
where: {
embedId: embed.id,
[`${moduleType}Id`]: moduleId,
},
update: {
text: embed.footer?.text,
Expand All @@ -168,6 +185,7 @@ export async function createOrUpdateEmbed(
fields: {
upsert: embed.fields.map((field) => ({
where: {
embedId: embed.id,
id: field.id ?? -1,
},
update: {
Expand All @@ -187,7 +205,7 @@ export async function createOrUpdateEmbed(
const createAuthor = {
author: embed.author?.name
? {
create: {
create: {
name: embed.author?.name,
iconUrl: embed.author?.iconUrl,
url: embed.author?.url,
Expand Down Expand Up @@ -217,52 +235,53 @@ export async function createOrUpdateEmbed(
},
};

console.log(embed);

if (embed.id) {
embedDb = await prisma.embed.update({
where: {
id: embed.id,
},
data: {
title: embed.title,
description: embed.description,
color: embed.color,
timestamp: embed.timestamp,
...createOrUpdateAuthor,
...createOrUpdateFooter,
...createOrUpdateFields,
},
include: {
fields: true,
author: true,
footer: true,
},
});
} else {
embedDb = await prisma.embed.create({
data: {
[`${moduleType}Id`]: moduleId,
title: embed.title,
description: embed.description,
color: embed.color,
timestamp: embed.timestamp,
...createAuthor,
...createFooter,
...createFields,
},
include: {
fields: true,
author: true,
footer: true,
},
});
try {
if (embed.id) {
embedDb = await prisma.embed.update({
where: {
id: embed.id,
},
data: {
title: embed.title,
description: embed.description,
color: embed.color,
timestamp: embed.timestamp,
...createOrUpdateAuthor,
...createOrUpdateFooter,
...createOrUpdateFields,
},
include: {
fields: true,
author: true,
footer: true,
},
});
} else {
embedDb = await prisma.embed.create({
data: {
[`${moduleType}Id`]: moduleId,
title: embed.title,
description: embed.description,
color: embed.color,
timestamp: embed.timestamp,
...createAuthor,
...createFooter,
...createFields,
},
include: {
fields: true,
author: true,
footer: true,
},
});
}
return {
...embedDb,
};
} catch (error) {
console.error(error);
return null;
}

console.log(embedDb);
return {
...embedDb,
};
}

export async function removeWelcomer(guildId: string): Promise<boolean> {
Expand Down
1 change: 1 addition & 0 deletions lib/dal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,7 @@ export async function getUserData() {

export async function getWelcomer(guildId: string): Promise<Welcomer | null> {
try {
console.log("getting welcomer");
if (!(await canUserManageGuild(guildId))) return null;
const welcomer = await prisma.welcomer.findUnique({
where: { guildId },
Expand Down
45 changes: 30 additions & 15 deletions lib/validator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,8 @@ export const MessageEmbedSchema = z.object({
.string()
.optional()
.nullable()
.refine((value) => (value?.length || 0) <= 2048, {
message: "Embed description must be less than 2048 characters.",
.refine((value) => (value?.length || 0) <= 4096, {
message: "Embed description must be less than 4096 characters.",
}),
url: z
.string()
Expand All @@ -78,9 +78,15 @@ export const MessageEmbedSchema = z.object({
])
.optional()
.nullable()
.refine((value) => typeof value === 'number' ? (value || 0) >= 0 && (value || 0) <= 16777215 : true, {
message: "Embed color must be a valid color.",
}),
.refine(
(value) =>
typeof value === "number"
? (value || 0) >= 0 && (value || 0) <= 16777215
: true,
{
message: "Embed color must be a valid color.",
}
),
author: z
.object({
name: z
Expand Down Expand Up @@ -117,9 +123,12 @@ export const MessageEmbedSchema = z.object({
})
.optional()
.nullable()
.refine((value) => (!value?.url || !value?.icon_url) && value?.name, {
message: "Embed author must have the name property set.",
}),
.refine(
(value) => !value || (value?.name && (!value?.icon_url || !value?.url)),
{
message: "Embed author must have the name property set.",
}
),
thumbnail: z
.object({
url: z
Expand Down Expand Up @@ -178,18 +187,24 @@ export const MessageEmbedSchema = z.object({
})
.optional()
.nullable()
.refine((value) => !value || !value.icon_url && value.text, {
.refine((value) => !value || (!value.icon_url && value.text), {
message: "Embed footer must have the text property set.",
}),
fields: z
.array(
z.object({
name: z.string().refine((value) => (value?.length || 0) <= 256, {
message: "Embed field name must be less than 256 characters.",
}),
value: z.string().refine((value) => (value?.length || 0) <= 1024, {
message: "Embed field value must be less than 1024 characters.",
}),
name: z
.string()
.min(1, "Embed field name must be a valid string")
.refine((value) => (value?.length || 0) <= 256, {
message: "Embed field name must be less than 256 characters.",
}),
value: z
.string()
.min(1, "Embed field name must be a valid string")
.refine((value) => (value?.length || 0) <= 1024, {
message: "Embed field value must be less than 1024 characters.",
}),
inline: z.boolean().optional().nullable(),
})
)
Expand Down
Loading

0 comments on commit 6fdd591

Please sign in to comment.