Skip to content

Instantly share code, notes, and snippets.

@EarthenLynx
Created April 13, 2020 20:00
Show Gist options
  • Save EarthenLynx/30eb5e12d262222290eded204f528620 to your computer and use it in GitHub Desktop.
Save EarthenLynx/30eb5e12d262222290eded204f528620 to your computer and use it in GitHub Desktop.
CRUD Operations from MongoDB - Recipe database as well as matching images
const Recipe = require("../models/recipe");
const path = require("path");
const fs = require("fs");
const galleryPath = require("../config/paths").galleryPath;
const date = new Date();
// Find the recipe by the given ID and delete it from the database.
const deleteRecipe = function (req, res) {
Recipe.findByIdAndDelete(req.body.recipe_id, (err, data) => {
if (err) {
res.send({
status: 500,
statusText: "error",
msg: "Could not delete recipe in database",
});
}
if (data) {
res.send({
status: 200,
statusText: "success",
msg: `Recipe '${data.recipe_name}' successfully removed!`,
});
// Then delete the old image from the thumbnail gallery, if there is such
let imgUrl = path
.join(galleryPath, "/thumbnails/", data.recipe_name)
.concat(".png");
if (fs.existsSync(imgUrl)) {
fs.unlinkSync(imgUrl);
}
}
if (!data) {
res.send({
status: 404,
statusText: "not found",
msg: `Recipe was not found in db.`,
});
}
});
};
module.exports = deleteRecipe;
const Recipe = require("../models/recipe");
const date = new Date;
// Query the database and return all recipes found.
const getRecipes = function (res) {
Recipe.find({}, (err, recipes) => {
if (err) {
res.send({
status: 500,
statusText: "error",
msg: "An error occured while fetching the recipes",
});
logger.log({
level: 'error',
message: date + ": Error while fetching the recipes: ".concat(err)
});
}
if (!err) {
res.send({
status: 200,
statusText: "success",
msg: `Found ${recipes.length} delicious recipes in database`,
data: recipes,
});
}
});
};
module.exports = getRecipes;
const path = require("path");
// Define the paths used through the app
const galleryPath = path.resolve(__dirname, "../public/img/");
module.exports = {galleryPath};
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const RecipeSchema = new Schema({
recipe_img_url: {type: String, required: true},
recipe_name: {type: String, required: true, max: 40},
recipe_tags: {type: Array, required: false},
recipe_desc: {type: String, required: false, max: 800},
recipe_instructions: {type: Array, required: true},
recipe_dishes_qty: {type: Number, required: true}, // For how many dishes are the ingredients?
recipe_ingredients: {type: Object, required: true},
recipe_time_minutes: {type: Number, required: false}, // Prep. time
recipe_notes: {type: String, required: false, max: 5000}
});
// Export the model
module.exports = mongoose.model("Recipe", RecipeSchema);
const Recipe = require("../models/recipe");
const path = require("path");
const fs = require("fs");
const galleryPath = require("../config/paths").galleryPath;
const date = new Date;
const saveRecipe = function(req, res) {
// Create the urls for the operation
let tempImgUrl = path.join(galleryPath, "/tmp/temp.png")
let newImgUrl = path.join(galleryPath, "/thumbnails/", req.body.recipe_name).concat('.png');
// Save the recipe
let recipe = new Recipe({
recipe_img_url: path.join("/img/thumbnails/", req.body.recipe_name).concat(".png"),
recipe_name: req.body.recipe_name,
recipe_tags: req.body.recipe_tags,
recipe_desc: req.body.recipe_desc,
recipe_instructions: req.body.recipe_instructions,
recipe_dishes_qty: req.body.recipe_dishes_qty,
recipe_ingredients: req.body.recipe_ingredients,
recipe_time_minutes: req.body.recipe_time_minutes,
recipe_notes: req.body.recipe_notes,
});
// TODO: Implement logic that checks if recipe name does already exist.
recipe.save((err) => {
if (err) {
res.send({
status: 500,
statusText: "error",
msg: "Could not save recipe in database."
});
logger.log({
level: 'error',
message: date + ": Error while saving the recipe: ".concat(err)
});
};
if (!err) {
res.send({
status: 200,
statusText: "success",
msg: `Recipe '${req.body.recipe_name}' successfully saved!`
});
}
});
// Create a new file
if(fs.existsSync(tempImgUrl)) {
fs.readFile(tempImgUrl, (err, data) => {
fs.writeFile(newImgUrl, data, (err) => {
if(err) {
logger.log({
level: 'error',
message: date + (": Error while writing the image file: ").concat(err)
});
}
});
});
} else {
logger.log({
level: 'error',
message: date + (": The temporary image has been removed before writing it into the thumbnail folder")
});
}
}
module.exports = saveRecipe;
const Recipe = require("../models/recipe");
const updateRecipe = function(req, res) {
const query = {'_id': req.body.data._id}
Recipe.findOneAndUpdate(query, req.body.data, {upsert: true}, (err, doc) => {
if (err) {
res.send({
status: 500,
statusText: "error",
msg: "Could not modify recipe in database",
});
logger.log({
level: 'error',
message: date + ": Error during the update of the recipe".concat(err)
});
}
if (doc) {
// TODO: Implement the logic that renames the image file accordingly.
res.send({
status: 200,
statusText: "success",
msg: `Recipe '${doc.recipe_name}' successfully updated!`,
});
}
if(!doc) {
res.send({
status: 404,
statusText: "not found",
msg: `You tried to update a recipe that doesn't exist. Are you a ghost??`
});
}
});
}
module.exports = updateRecipe;
const path = require("path");
const fs = require("fs");
const galleryPath = require("../config/paths").galleryPath;
// TODO: Add a placeholder image in case the user uploads none
// TODO: Find out why the app crashes whenever no image to delete was found
const saveImgTemp = function (req) {
let tempImgUrl = path.join(galleryPath, "/tmp/temp.png");
let base64Data = req.body.img.replace(/^data:image\/png;base64,/, "");
// Overwrite the old temp image with the new one.
fs.unlink(tempImgUrl, (err) => {
console.log(err);
fs.appendFile(tempImgUrl, base64Data, "base64", function (err) {
console.log(err);
});
});
};
module.exports = saveImgTemp;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment