Basic express get and post

PHOTO EMBED

Thu Oct 07 2021 04:44:50 GMT+0000 (UTC)

Saved by @rook12 #javascript

const express = require("express");
const app = express();
const PropertyModel = require("./models/PropertyModel");
const validId = require("./validId");

app.use(express.json());

app.get("/properties", async (req, res) => {
  const properties = await PropertyModel.find({});
  return res.status(200).send(properties);
});

app.get("/properties/:id", async (req, res) => {
  const propertyId = req.params.id;
  if (validId(propertyId)) {
    const property = await PropertyModel.findById(propertyId);
    if (property) {
      return res.status(200).send(property);
    } else {
      return res.status(404).send({ message: "id not found" });
    }
  }
  return res.status(400).send({ message: "id provided is invalid" });
});

app.post("/properties", async (req, res) => {
  const { body } = req;
  const property = new PropertyModel(body);
  await property.save();

  return res.status(200).send(property);
});

module.exports = app;
content_copyCOPY