<file_sep>import ChildSchema from "../models/schema/ChildSchema";

export const CreateChild = async (req, res) => {
  try {
    const { name, sex, father_name, mother_name, dob, district_id } = req.body;
    const file = req.photoUrl;
    let child = new ChildSchema({
      name,
      sex,
      father_name,
      mother_name,
      dob,
      district_id,
      photo: file.url,
    });
    await child.save();
    return res.status(200).json({
      success: true,
      status: 200,
      data: child,
      errors: [],
      message: "Operation performed successfully",
    });
  } catch (error) {
    console.log(error.message);
  }
};

export const GetChildProfiles = async (req, res) => {
  try {
    let child = await ChildSchema.find().populate(
      "district_id",
      "district_name"
    );
    return res.status(200).json({
      success: true,
      status: 200,
      data: child,
      errors: [],
      message: "Child Profile Details fetched successfully",
    });
  } catch (error) {
    console.log(error.message);
  }
};
<file_sep>import DistrictSchema from "../models/schema/DistrictSchema";
import StateSchema from "../models/schema/StateSchema";

export const CreateDistrict = async (req, res) => {
  try {
    const { district_name, state_name } = req.body;
    let state = await StateSchema.findOne({ state_name: state_name });
    if (!state) {
      return res.status(400).json({
        success: false,
        status: 400,
        data: {},
        errors: [
          {
            value: state_name,
            msg: "State is not exist",
            param: "state Id",
            location: "body",
          },
        ],
      });
    }
    let district = await DistrictSchema.findOne({
      district_name: district_name,
    });
    if (district) {
      return res.status(400).json({
        success: false,
        status: 400,
        data: {},
        errors: [
          {
            value: district_name,
            msg: "District name already exist",
            param: "district_name",
            location: "body",
          },
        ],
      });
    }

    district = new DistrictSchema({
      stateId: state._id,
      district_name,
    });
    await district.save();
    return res.status(200).json({
      success: true,
      status: 200,
      data: {},
      errors: [],
      message: "Operation performed successfully",
    });
  } catch (error) {
    console.log(error.message);
  }
};

export const GetDistrict = async (req, res) => {
  try {
    const Id = req.query.state_id;

    let district = await DistrictSchema.find(
      { stateId: Id },
      { _id: 1, district_name: 1 }
    );

    return res.status(200).json({
      success: true,
      status: 200,
      data: district,
      errors: [],
      message: "District data fetched successfully",
    });
  } catch (error) {
    console.log(error.message);
  }
};
<file_sep>import { check, validationResult } from "express-validator";
export const validateRegister = [
  check("name")
    .not()
    .isEmpty()
    .withMessage("Name field cannot be empty")
    .isAlphanumeric()
    .withMessage("Name cannot contain special characters"),

  check("email")
    .not()
    .isEmpty()
    .withMessage("Email field cannot be empty")
    .isEmail()
    .withMessage("Not a valid email"),

  check("password")
    .not()
    .isEmpty()
    .withMessage("Password cannot be empty")
    .isLength({ min: 8 })
    .withMessage(
      "Password must be 8<length, must contain 1 symbol, 1 uppercase, 1 lowercase and 1 number"
    )
    .matches(/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[a-zA-Z\d@$.!%*#?&]/)
    .withMessage(
      "Password must be 8<length, must contain 1 symbol, 1 uppercase, 1 lowercase and 1 number"
    ),
];

export const validateLogin = [
  check("email")
    .not()
    .isEmpty()
    .withMessage("Email cannot be empty")
    .isEmail()
    .withMessage("Not a valid email"),

  check("password")
    .not()
    .isEmpty()
    .withMessage("Password cannot be empty")
    .isLength({ min: 8 })
    .withMessage(
      "Password must be 8<length, must contain 1 symbol, 1 uppercase, 1 lowercase and 1 number"
    )
    .matches(/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[a-zA-Z\d@$.!%*#?&]/)
    .withMessage(
      "Password must be 8<length, must contain 1 symbol, 1 uppercase, 1 lowercase and 1 number"
    ),
];

export const validateState = [
  check("state_name")
    .not()
    .isEmpty()
    .withMessage("State name field cannot be empty")
    .isAlphanumeric()
    .withMessage("State name cannot contain special characters"),
];
export const validateDistrict = [
  check("state_name")
    .not()
    .isEmpty()
    .withMessage("State name field cannot be empty")
    .isAlphanumeric()
    .withMessage("State name cannot contain special characters"),

  check("district_name")
    .not()
    .isEmpty()
    .withMessage("District name field cannot be empty")
    .isAlphanumeric()
    .withMessage("District name cannot contain special characters"),
];
export const validateChild = [
  check("name").not().isEmpty().withMessage("Name field cannot be empty"),
  check("father_name")
    .not()
    .isEmpty()
    .withMessage("Father name field cannot be empty"),

  check("mother_name")
    .not()
    .isEmpty()
    .withMessage("Mother name field cannot be empty"),

  check("dob").not().isEmpty().withMessage("DOB field cannot be empty"),
  check("sex").not().isEmpty().withMessage("Sex field cannot be empty"),

  check("district_id")
    .not()
    .isEmpty()
    .withMessage("District Name field cannot be empty"),
];

export const isRequestValidate = (req, res, next) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({
      success: false,
      status: 400,
      errors: errors.array(),
    });
  }
  next();
};
<file_sep>import StateSchema from "../models/schema/StateSchema";

export const GetState = async (req, res) => {
  try {
    let state = await StateSchema.find();
    return res.status(200).json({
      success: true,
      status: 200,
      data: state,
      errors: [],
      message: "State data fetched successfully",
    });
  } catch (error) {
    console.log(error.message);
  }
};

export const CreateState = async (req, res) => {
  try {
    const { state_name } = req.body;
    let state = await StateSchema.findOne({ state_name: state_name });
    if (state) {
      return res.status(400).json({
        success: false,
        status: 400,
        data: {},
        errors: [
          {
            value: state_name,
            msg: "State name is already exist",
            param: "state_name",
            location: "body",
          },
        ],
        message: "State is already exist",
      });
    }
    state = new StateSchema({
      state_name,
    });
    await state.save();
    return res.status(200).json({
      success: true,
      status: 200,
      data: {},
      errors: [],
      message: "Operation performed successfully",
    });
  } catch (error) {
    console.log(error.message);
  }
};
<file_sep>const cloudinary = require("cloudinary").v2;

cloudinary.config({
  cloud_name: process.env.Cloud_name,
  api_key: process.env.api_key,
  api_secret: process.env.api_secret,
});

const isFileValid = async (req, res, next) => {
  try {
    if (req.files) {
      let isFile = req.files.photo;
      let fileMimeType = isFile.mimetype.split("/")[1];
      if (fileMimeType == "jpg" || fileMimeType == "png") {
        await cloudinary.uploader.upload(isFile.tempFilePath, (err, res) => {
          req.photoUrl = res;
        });
        next();
      }
    } else {
      return res.status(400).json({
        success: false,
        status: 400,
        data: {},
        errors: [
          {
            value: "photo",
            msg: "File extension must be PNG or JPG",
            param: "file",
            location: "file",
          },
        ],
        message: "Not a valid file extension",
      });
    }
  } catch (error) {
    console.log(error.message);
  }
};

export default isFileValid;
<file_sep># Hi , This is <NAME>.

Backend Apis:

running command => npm run test

 (Get)  http://localhost:5001/health  => for checking that server working or not
 (Post)  http://localhost:5001/api/register  => for Register 
 (Post)  http://localhost:5001/api/login  => for Login
 (Get)  http://localhost:5001/api/logout  => for Logout
 (Get)  http://localhost:5001/api/get_state  => for Geting the State Data
 (Post)  http://localhost:5001/api/create/state  => for Createing  the State 
 (Post)  http://localhost:5001/api/create/district => for Createing  the District
 (Get)  http://localhost:5001/api/get_district  => for Geting the District Data
 (Get)  http://localhost:5001/api/get_child_profile  => for Geting the Child Profile Data
 (Post)  http://localhost:5001/api//create/child     =>   for Creating a Child Data
 
 FrontEnd Assignment:
 
 running command => npm start
 
 page 1 routes = http://localhost:3000        => for home page you can see the data table 
 page 2 routes = http://localhost:3000/chart  => for Chart page you can see the chart or data
<file_sep>import mongoose from "mongoose";

const ChildSchema = mongoose.Schema(
  {
    name: {
      type: String,
      required: true,
      trim: true,
    },
    sex: {
      type: String,
      required: true,
      trim: true,
    },
    dob: {
      type: String,
      required: true,
      trim: true,
    },
    father_name: {
      type: String,
      required: true,
      trim: true,
    },
    mother_name: {
      type: String,
      required: true,
      trim: true,
    },
    district_id: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "district",
      required: true,
    },
    photo: {
      type: String,
      required: true,
      trim: true,
    },
  },
  { timestamps: true }
);

export default mongoose.model("child", ChildSchema);
<file_sep>import UserSchema from "../models/schema/UserSchema";
import jwt from "jsonwebtoken";
import bcrypt from "bcrypt";

export const AuthRegister = async (req, res) => {
  try {
    const { name, email, password } = req.body;
    let user = await UserSchema.find({ email: email });
    if (user.length) {
      return res.status(400).json({
        success: false,
        status: 400,
        data: {},
        errors: [
          {
            value: req.body.email,
            msg: "User already exists.",
            param: "email",
            location: "body",
          },
        ],
        message: "Unable to create user",
      });
    }
    const hashPassword = await bcrypt.hash(password, 10);
    user = new UserSchema({
      name,
      email,
      password: <PASSWORD>,
    });
    await user.save();
    res.status(200).json({
      success: true,
      status: 200,
      data: user,
      errors: [],
      message: "User Created Successfully",
    });
  } catch (error) {
    console.log(error.message);
  }
};

export const AuthLogin = async (req, res) => {
  try {
    const { email, password } = req.body;
    let user = await UserSchema.findOne({ email: email });
    if (!user) {
      return res.status(400).json({
        success: false,
        status: 400,
        data: {},
        errors: [
          {
            value: req.body.email,
            msg: "Invalid credentials",
            param: "email",
            location: "body",
          },
        ],
        message: "Invalid credentials",
      });
    }
    const matchPassword = bcrypt.compareSync(password, user.password);
    if (!matchPassword) {
      return res.status(400).json({
        success: false,
        status: 400,
        data: {},
        errors: [
          {
            value: req.body.password,
            msg: "Invalid credentials",
            param: "password",
            location: "body",
          },
        ],
        message: "Invalid credentials",
      });
    }
    const logintoken = jwt.sign({ id: user._id }, process.env.jwt_secret, {
      expiresIn: "1d",
    });
    req.session.logintoken = logintoken;
    res.status(200).json({
      success: true,
      status: 200,
      data: logintoken,
      errors: [],
      message: "Login successfully!",
    });
  } catch (error) {
    console.log(error.message);
  }
};
