I am making a code snippet web app. Basically you can upload snippets and organize them, etc. I am having trouble deciding how to store the code.
Currently, I am using express to create an API to connect to the frontend. I am inserting whatever code was inputted in the textarea, and saving it in plaintext to mongodb.
let snippet = new Snippet({
title: req.body.title,
code: req.body.code,
creator: req.body.creator,
createdDate: date,
updatedDate: date,
collections: req.body.collections,
});
await snippet.save((error, Snippet) => {
if (error) {
console.log(
"postSnippet(): Failed to save snippet to database. Error: " +
error
);
return res
.status(500)
.json({ message: "Failed to save snippet to database" });
} else {
console.log("postSnippet(): Snippet created.");
return res
.status(201)
.json({ message: "Snippet created", snippet });
}
});
When I paste the code on the UI frontend, it displays just fine. But for some reason, when I try to get the raw code in a seperate file, all the line breaks dont work.
export const fetchRawSnippet = async (req, res) => {
let snippetUrl = req.params.slug;
if (snippetUrl) {
try {
const fetchSnippets = await Snippet.findOne({ slug: snippetUrl });
if (fetchSnippets) {
res.send(fetchSnippets.code);
return res.status(200).json(fetchSnippets.code);
} else {
return res
.status(404)
.json({ message: "Could not find snippet" });
}
} catch (e) {}
} else {
return res.status(404).json({ message: "slug not provided" });
}
};
I am wondering if its a better idea to use GitHub Gists API to host the snippets... Im not sure. Can someone just guide me in the right direction about the best way to go about code storage.