Back

Code 500 (Internal Server Error) - Data not saved on Appwrite DB

  • 0
  • Databases
  • Web
Jean-Marie (JM)
11 Jan, 2024, 17:52

Hi Guys, Could someone please help with the below issue? I am keeping getting the following error, while creating a post and trying to save it on my Appwrite DB. User auth and creation works perfect, user is saved on the DB:

"api.ts:117

TypeScript
   POST https://cloud.appwrite.io/v1/databases/65955c1f63e8af139596/collections/65955c743b49830747b8/documents 500 (Internal Server Error)

Error creating post document: AppwriteException: Server Error at Client.<anonymous> (http://localhost:5173/node_modules/.vite/deps/appwrite.js?v=34b59556:850:17) at Generator.next (<anonymous>) at fulfilled (http://localhost:5173/node_modules/.vite/deps/appwrite.js?v=34b59556:488:24)"

my console.log (client side) is showing that the post has been created but is not getting saved to the DB.

Here are my code snippets - React+Vite:

1 - from PostForm.tsx

type PostFormProps = { post?: Models.Document; }

const PostForm = ({ post }: PostFormProps) => {

TypeScript
const { mutateAsync: createPost, isPending: isLoadingCreate } = useCreatePost();
const { user } = useUserContext();
const { toast } = useToast();
const navigate = useNavigate();

// 1. Define your form.

const form = useForm<z.infer<typeof PostValidation>>({ resolver: zodResolver(PostValidation), defaultValues: { caption: post ? post?.caption : "", file: [], location: post ? post?.location : "", tags: post ? post.tags.join(",") : "", }, })

TL;DR
The developer is experiencing a Code 500 (Internal Server Error) when trying to save a post on the Appwrite DB. The error message states that there is an AppwriteException: Server Error. The developer has provided code snippets for context. The issue seems to be with the createPost function in the api.ts file. The post is successfully created but is not being saved to the DB. Solution: 1. Check if the Appwrite server is running properly. 2. Verify the Appwrite database and collection IDs are correct. 3. Check if there are any error logs on the server side that might provide more information about the
Jean-Marie (JM)
11 Jan, 2024, 17:53

// 2. Define a submit handler. async function onSubmit(value: z.infer<typeof PostValidation>) { // Do something with the form values. // ✅ This will be type-safe and validated. const newPost = await createPost({ ...value, userId: user.id, })

TypeScript
if(!newPost) {
    toast({
        title: 'Please try again'
    })
}
navigate('/')

console.log(value)
Jean-Marie (JM)
11 Jan, 2024, 17:53

2 - From queriesAndMutations.ts:

export const useCreatePost = () => { const queryClient = useQueryClient(); return useMutation({ mutationFn: (post: INewPost) => createPost(post), onSuccess: () => { queryClient.invalidateQueries({ queryKey: [QUERY_KEYS.GET_RECENT_POSTS], }); }, }); };

3 - from api.ts:

export async function createPost(post: INewPost) { try { // Upload file to appwrite storage const uploadedFile = await uploadFile(post.file[0]);

TypeScript
  if (!uploadedFile) throw Error;

  // Get file url
  const fileUrl = getFilePreview(uploadedFile.$id);

  if (!fileUrl) {
    await deleteFile(uploadedFile.$id);
    throw Error;
  }
  // Convert tags into array
  const tags = post.tags?.replace(/ /g, "").split(",") || [];

   // Save the post in DB
   const newPost = await databases.createDocument(
    appwriteConfig.databaseId,
    appwriteConfig.postCollectionId,
    ID.unique(),
    {
      creator: post.userId,
    //   likes: likes,
      caption: post.caption,
      imageUrl: fileUrl,
      imageId: uploadedFile.$id,
      location: post.location,
      tags: tags,
    }
  );

  if (!newPost) {
    await deleteFile(uploadedFile.$id);
    // throw Error;
    throw new Error("Failed to create post document.");
  }

  return newPost;


} catch (error) {
    console.error("Error creating post document:", error);
  }

}

// ============================== UPLOAD FILE export async function uploadFile(file: File) { try { const uploadedFile = await storage.createFile( appwriteConfig.storageId, ID.unique(), file );

TypeScript
  return uploadedFile;
} catch (error) {
  console.log(error);
}

}

Jean-Marie (JM)
11 Jan, 2024, 17:53

// ============================== GET FILE URL export function getFilePreview(fileId: string) { try { const fileUrl = storage.getFilePreview( appwriteConfig.storageId, fileId, 2000, 2000, "top", 100, );

TypeScript
  if (!fileUrl) throw Error;

  return fileUrl;
} catch (error) {
  console.log(error);
}

}

// ============================== DELETE FILE export async function deleteFile(fileId: string) { try { await storage.deleteFile(appwriteConfig.storageId, fileId);

TypeScript
  return { status: "ok" };
} catch (error) {
  console.log(error);
}

}

Jean-Marie (JM)
11 Jan, 2024, 17:53

Sorry for the multiple messages, but I wanted to provide the different parts of the code

Reply

Reply to this thread by joining our Discord

Reply on Discord

Need support?

Join our Discord

Get community support by joining our Discord server.

Join Discord

Get premium support

Join Appwrite Pro and get email support from our team.

Learn more