Search⌘ K
AI Features

Implement Route Handlers for GET, PUT, and DELETE

Explore how to implement RESTful API route handlers for GET, PUT, and DELETE methods in Express. Understand how to connect controllers to service layers for CRUD operations, redirect base URLs, and send proper HTTP statuses for resource management.

Let’s allow the API consumer to retrieve, update, or delete a recipe by ID. Don’t forget to test the endpoint with Postman!

Implementing route handlers

Let’s make sure that our files contain the following code.

  1. First, implement the necessary functions in the service layer to perform CRUD operations on the database. Add the following code in the express-recipes/src/services/recipes.js file:
Javascript (babel-node)
const fs = require("fs").promises;
const path = require("path");
const recipesFilePath = path.join(__dirname, "../../db/recipes.json");
const getAll = async () => JSON.parse(await fs.readFile(recipesFilePath));
const get = async (id) => {
const recipes = await getAll();
return recipes.find((recipe) => recipe.id === parseInt(id));
};
const save = async (recipe) => {
const recipes = await getAll();
recipe.id = recipes.length + 1; // Not a robust incrementor mechanism; don't use in production!
recipes.push(recipe);
await fs.writeFile(recipesFilePath, JSON.stringify(recipes));
return recipe;
};
const update = async (id, updated) => {
const recipes = await getAll();
updated.id = parseInt(id);
const updatedRecipes = recipes.map((recipe) => {
return recipe.id === parseInt(id) ? updated : recipe;
});
await fs.writeFile(recipesFilePath, JSON.stringify(updatedRecipes));
return updated;
};
const remove = async (id) => {
const recipes = await getAll();
const newRecipes = recipes
.map((recipe) => {
return recipe.id === parseInt(id) ? null : recipe;
})
.filter((recipe) => recipe !== null);
await fs.writeFile(recipesFilePath, JSON.stringify(newRecipes));
};
module.exports = {
getAll,
get,
save,
update,
remove,
};
  1. Next,
...