Skip to content

Commit

Permalink
fix fork errors not showing (#552)
Browse files Browse the repository at this point in the history
* fix fork implementation

* format code

* add test

* format code

* add test port

* update

* use ctx.error
  • Loading branch information
techmannih authored Jan 15, 2025
1 parent 3596ee6 commit 4bd8a54
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 2 deletions.
26 changes: 24 additions & 2 deletions fake-snippets-api/routes/api/snippets/create.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export default withRouteSpec({
}),
jsonResponse: z.object({
ok: z.boolean(),
snippet: snippetSchema,
snippet: snippetSchema.optional(),
}),
})(async (req, ctx) => {
let {
Expand All @@ -28,9 +28,24 @@ export default withRouteSpec({
circuit_json,
dts,
} = req.jsonBody

if (!unscoped_name) {
unscoped_name = `untitled-${snippet_type}-${ctx.db.idCounter + 1}`
}

const existingSnippet = ctx.db.snippets.find(
(snippet) =>
snippet.unscoped_name === unscoped_name &&
snippet.owner_name === ctx.auth.github_username,
)

if (existingSnippet) {
return ctx.error(400, {
error_code: "snippet_already_exists",
message: "You have already forked this snippet in your account.",
})
}

const newSnippet: z.input<typeof snippetSchema> = {
snippet_id: `snippet_${ctx.db.idCounter + 1}`,
name: `${ctx.auth.github_username}/${unscoped_name}`,
Expand All @@ -46,7 +61,14 @@ export default withRouteSpec({
dts,
}

ctx.db.addSnippet(newSnippet)
try {
ctx.db.addSnippet(newSnippet)
} catch (error) {
return ctx.error(500, {
error_code: "snippet_creation_failed",
message: `Failed to create snippet: ${error}`,
})
}

return ctx.json({
ok: true,
Expand Down
21 changes: 21 additions & 0 deletions src/components/ViewSnippetHeader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,13 @@ export default function ViewSnippetHeader() {
owner_name: session.github_username,
code: snippet.code,
})

if (!data.ok) {
throw new Error(
data.error || "Unknown error occurred while forking snippet.",
)
}

return data.snippet
},
{
Expand All @@ -51,6 +58,20 @@ export default function ViewSnippetHeader() {
onSuccess?.(forkedSnippet)
},
onError: (error: any) => {
// Check if the error message contains 'already exists'
if (error.message?.includes("already forked")) {
toast({
title: "Snippet already exists",
description: error.message,
variant: "destructive", // You can style this variant differently
})
} else {
toast({
title: "Error",
description: "Failed to fork snippet. Please try again.",
variant: "destructive", // Use destructive variant for errors
})
}
console.error("Error forking snippet:", error)
},
},
Expand Down

0 comments on commit 4bd8a54

Please sign in to comment.