kato
kato

Reputation: 196

How to make CRUD in NodeJS but with async and await?

I have to create CRUD but my controller uses a lot of callbacks. I do not know how to use async and await in order to make my code look clean and high-performance. I hope anyone can help me and give me some suggestions.

Below is my controller:

// create new course
export function createCourse (req, res) {
  const course = new Course({
    _id: mongoose.Types.ObjectId(),
    title: req.body.title,
    description: req.body.description,
  });
  
  return course
    .save()
    .then((newCourse) => {
      return res.status(201).json({
        success: true,
        message: 'New course created successfully',
        Course: newCourse,
      });
    })
    .catch((error) => {
        console.log(error);
      res.status(500).json({
        success: false,
        message: 'Server error. Please try again.',
        error: error.message,
      });
    });
}

// Get all course
export function getAllCourse( req, res){
  Course.find()
    .select('_id title description')
    .then((allCourse) => {
      return res.status(200).json({
        success: true,
        message: 'A list of all course',
        Course: allCourse,
      });
    })
    .catch((err) => {
      res.status(500).json({
        success: false,
        message: 'Server error. Please try again.',
        error: err.message,
      });
    });
}

// get single course
export function getSingleCourse(req, res) {
  const id = req.params.courseId;
  Course.findById(id)
    .then((singleCourse) => {
      res.status(200).json({
        success: true,
        message: `More on ${singleCourse.title}`,
        Course: singleCourse,
      });
    })
    .catch((err) => {
      res.status(500).json({
        success: false,
        message: 'This course does not exist',
        error: err.message,
      });
   });
}

// update course
export function updateCourse(req, res) {
  const id = req.params.courseId;
  const updateObject = req.body;
  Course.update({ _id:id }, { $set:updateObject })
    .exec()
    .then(() => {
      res.status(200).json({
        success: true,
        message: 'Course is updated',
        updateCourse: updateObject,
      });
    })
    .catch((err) => {
      res.status(500).json({
        success: false,
        message: 'Server error. Please try again.'
      });
    });
}

// delete a course
export function deleteCourse(req, res) {
  const id = req.params.courseId;
  Course.findByIdAndRemove(id)
    .exec()
    .then(()=> res.status(204).json({
      success: true,
    }))
    .catch((err) => res.status(500).json({
      success: false,
    }));
}

Now I want to replace all callbacks with async and await, how to replace and how to use them more correctly. I appreciate every help.

Upvotes: 1

Views: 687

Answers (3)

kato
kato

Reputation: 196

// Find all car with condition
export async function findAllCar(req, res) {
  const { page, size, name, color, brand } = req.query;
  const { limit, offset } = getPagination(page, size);
  var condition =
    name && color && brand
      ? {
          name: { [Op.iLike]: `%${name}%` },
          color: { [Op.iLike]: `%${color}%` },
          brand: { [Op.iLike]: `%${brand}%` },
        }
      : null;
  try {
    const car = await Car.findAll({ where: condition, offset, limit });
    if (!car) {
      return res.status(404);
    }
    const response = getPagingData(data, page, limit);
    res.status(200).send(response);
  } catch (error) {
    return res.status(500).json({
      success: false,
      message: "Server error. Please try again.",
      error: error.message,
    });
  }
}

// Find single Car
export async function findOne(req, res) {
  try {
    const car = await Car.findById(req.params.car_id);
    if (!car) {
      return res.status(404);
    }
    res.status(200).send(car);
  } catch (error) {
    return res.status(500).json({
      success: false,
      message: "Server error. Please try again.",
      error: error.message,
    });
  }
}

// update car
export async function updateCar(req, res) {
  try {
    const car = await Car.find(
      req.body.name,
      req.body.brand,
      req.params.car_id,
      req.body
    );
    if (!car) {
      return res.status(404).json({
        success: false,
        message: "Duplicate value.",
      });
    }
    res.status(200).json({
      success: true,
      message: "New car updated successfully",
    });
  } catch (error) {
    return res.status(500).json({
      success: false,
      message: "Server error. Please try again.",
      error: error.message,
    });
  }
}

// delete a car
export async function deleteCar(req, res) {
  try {
    const car = await Car.findByIdAndDelete(req.params.car_id);
    if (!car) {
      return res.status(404).send();
    }
    res.send(car);
  } catch (error) {
    return res.status(500).json({
      success: false,
      message: "Server error. Please try again.",
      error: error.message,
    });
  }
}

Upvotes: 0

Apoorva Chikara
Apoorva Chikara

Reputation: 8773

What you are using is promises and they are used to avoid callbacks hell. It is just a way of calling the callbacks: when you use callbacks you pass the cb function on completion of the task, on the other hand, promises to return the object on which you attach the callbacks thus there is no callback hell.

In the given question, you have used chaining of cbs that are good too and async/await is no magic, they are just syntactic sugar on Promises. They make the code more readable and maintainable.

Let's take an example for createCourse:

export async function createCourse (req, res) {
  try {
     const course = new Course({
     _id: mongoose.Types.ObjectId(),
     title: req.body.title,
     description: req.body.description,
     });
  
     const course = await course.save()
     res.status(201).json({
     success: true,
     message: 'New course created successfully',
     course,
     })
    } catch (error) {
        console.log(error);
      res.status(500).json({
        success: false,
        message: 'Server error. Please try again.',
        error: error.message,
      });
    }
}

Note: always use try/catch with async/await

You can follow the same approach for all the other promises. I recommend you to check this for more details.

Upvotes: 1

Sakil
Sakil

Reputation: 652

// create new course
export async function createCourse(req, res) {
    const course = new Course({
        _id: mongoose.Types.ObjectId(),
        title: req.body.title,
        description: req.body.description,
    });

    try {
        let newCourse = await course.save();
        return res.status(201).json({
            success: true,
            message: 'New course created successfully',
            Course: newCourse,
        });
    } catch (error) {
        console.error(error);
        return res.status(500).json({
            success: false,
            message: 'Server error. Please try again.',
            error: error.message,
        });
    }
}

// Get all course
export async function getAllCourse(req, res) {
    try {
        let allCourse = await Course.find().select('_id title description');
        return res.status(200).json({
            success: true,
            message: 'A list of all course',
            Course: allCourse,
        });
    } catch (error) {
        return res.status(500).json({
            success: false,
            message: 'Server error. Please try again.',
            error: error.message,
        });
    }
}

Upvotes: 1

Related Questions