models/customers.js

import Joi from "joi";
import { Schema, model } from "mongoose";

const customerSchema = new Schema({
  isGold: {
    type: Boolean,
    default: false,
  },
  name: {
    type: String,
    required: true,
  },
  phone: {
    type: String,
    required: true,
    min: 10,
    max: 10,
  },
});

const Customer = model("Customer", customerSchema);

function validateCustomer(customer) {
  const schema = Joi.object({
    name: Joi.string().min(5).max(50).required(),
    phone: Joi.string().min(10).max(10).required(),
    isGold: Joi.boolean(),
  });
  
  return schema.validate(customer);
}

// const _Customer = Customer;
// export { _Customer as Customer };
// export const validate = validateCustomer;

export { Customer, validateCustomer };

index.js

import { connect } from "mongoose";
// import genres from "./routes/genres.js";
import customers from "./routes/customers.js";
import express, { json } from "express";
const app = express();

connect("mongodb://localhost/vidly")
  .then(() => console.log("Connected to mongo db"))
  .catch((err) => console.error("Error while connecting to mongodb "));

app.use(json());
// app.use("/api/genres", genres);
app.use("/api/customers", customers);

const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Listening on port ${port}...`));

routes/customers.js

import express from "express";
import { Customer, validateCustomer } from "../models/customers.js";

const router = express.Router();

router.get("/", async (req, res) => {
  const customers = await Customer.find().sort("name");
  res.send(customers);
});

router.post("/", async (req, res) => {
  const { error } = validateCustomer(req.body);
  if (error) return res.status(400).send(error.details[0].message);

  const customer = new Customer({
    name: req.body.name,
    isGold: req.body.isGold,
    phone: req.body.phone,
  });
  const result = await customer.save();
  res.send(result);
});

router.put("/:id", async (req, res) => {
  const customer = await Customer.findByIdAndUpdate(
    req.params.id,
    {
      isGold: req.body.isGold,
      name: req.body.name,
      phone: req.body.phone,
    },
    {
      new: true,
    }
  );

  if (!customer)
    return res.status(404).send("Customer with given ID not found");

  res.send(customer);
});

router.delete("/:id", async (req, res) => {
  const customer = await Customer.findByIdAndDelete(req.params.id);

  if (!customer)
    return res.status(404).send("Customer with given ID not found");

  res.send(customer);
});

router.get("/:id", async (req, res) => {
  const customer = await Customer.findById(req.params.id);

  if (!customer) return res.send(404).send("Customer with given ID not found");

  res.send(customer);
});

export default router;