Preview:
var express = require('express');
var router = express.Router();
const multer  = require('multer')
const fs = require('fs')
const storage2 = require('node-persist');
const auth = require('../middleware/auth')
var jwt = require('jsonwebtoken');
const path = require('path');



const saveuser = require('../model/user');
const saveUserDetails = require('../model/userDetail');

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'uploads/')
  },
  filename: function (req, file, cb) {
    cb(null, `${Date.now()}_${file.originalname}`)
  }
})

const upload = multer(
  { storage: storage }
)

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});


const saveUserData = async (req,res,next) =>{

  try {

    const saveUser = new saveuser({
      email: req.body.email,
      password: req.body.password
    })

    const users = await saveUser.save();

    const userID = users._id;

    const saveDetila = new saveUserDetails({
      user_id: userID,
      name: req.body.name,
      phone: req.body.phone,
      country: req.body.country,
      file: req.file.filename,
    })

    const detils = await saveDetila.save();


    res.status(200).json({
      status: 'success',
      users,
      detils

    })
    
  } catch (error) {
    if (req.file && req.file.path && fs.existsSync(req.file.path)) {
      fs.unlinkSync(req.file.path);
    }
    if(error.name === 'ValidationError'){
      if (req.file && req.file.path && fs.existsSync(req.file.path)) {
        fs.unlinkSync(req.file.path);
      }
      const validationError = {};
      for(const key in error.errors){
        validationError[key] = error.errors[key].message;
      }
      return res.status(400).json({
        error: validationError
      })
    }
    res.send(500).json({
      massage: 'Server Error'
    })

  }

}


const checkUser = async (req,res,next) => {

  try {

    const {email,password} = req.body

    const findUser = await saveuser.find({email: email});

    if(!findUser){
      res.send(201).json({
        status: 'error',
        message: 'Email is not Found'
      })
    }

    if(findUser){

      const passwordCheck = await saveuser.find({password: password});

      if(!passwordCheck){
        res.send(201).json({
          status: 'error',
          message: 'Wrong Password'
        })
      } else {

        const storeData = findUser.toString();
        await storage2.init('');
        await storage2.setItem(storeData,'user');
        var token = jwt.sign({ _id: findUser[0]._id }, 'shhhhh');

        res.status(200).json({
          status: 'success',
          message: 'login Successfully',
          token
        })

      }

    }

    
  } catch (error) {
     
    if(error) throw error;

    res.send(500).json({
      massage: 'Server Error'
    })
    
  }

}


const userList = async (req,res,next) => {
  try {

    const query = {};

    if(req.query.email){
      query.email = { $regex: new RegExp(req.query.email,'i')};
    }

    if(req.query.name){
      query.name = {$regex: new RegExp(req.query.name,'i')};
    }

    if(req.query.phone){
      query.phone = req.query.phone
    }

    if(req.query.country){
      req.query = {$regex: new RegExp(req.query.country,'i')};
    }

    const page = parseInt(req.query.page) || 1;
    const pageSize = parseInt(req.query.pageSize) || 5;

    const Listuser = await saveUserDetails.aggregate([
      {
        $match: query
      },
      {
        $lookup: {
          from: "users",
          localField: "user_id",
          foreignField: "_id",
          as: "user",
        },
      },
      {
        $skip: (page - 1) * pageSize,
      },
      {
        $limit: pageSize
      }
    ])

    res.status(200).json({
      status: 'success',
      Listuser
    });
    
  } catch (error) {
    
    res.send(500).json({
      massage: 'Server Error'
    })

  }
}

const updateUser = async (req, res, next) => {
  try {
    const userid = req.params.id;

    const getuserDetila = await saveUserDetails.findOne({ user_id: userid });

    if (!getuserDetila) {
      return res.status(400).json({
        status: 'error',
        message: 'User not found'
      });
    }

    if (getuserDetila.file) {
      const filePath = path.join('uploads/', getuserDetila.file);
      if (fs.existsSync(filePath)) {
        fs.unlinkSync(filePath);
      }
    }

    const userData = await saveuser.findByIdAndUpdate(
      userid,
      {
        email: req.body.email,
        password: req.body.password
      },
      { new: true }
    );

    const userDetails = await saveUserDetails.findOneAndUpdate(
      { user_id: userid },
      {
        name: req.body.name,
        phone: req.body.phone,
        country: req.body.country,
        file: req.file.filename,
      },
      {
        new: true
      }
    );

    res.status(200).json({
      status: 'Success',
      userData,
      userDetails,
    });
  } catch (error) {
    if (req.file && req.file.path && fs.existsSync(req.file.path)) {
      fs.unlinkSync(req.file.path);
    }
    console.error(error); // Log the actual error for debugging
    res.status(500).json({
      status: 'error',
      message: error.message // Send the actual error message
    });
  }
};


const deleteUser = async (req, res, next) => {
  try {
    const userid = req.params.id;

    const getUserDetails = await saveUserDetails.findOne({ user_id: userid });

    if (!getUserDetails) {
      return res.status(400).json({
        status: 'error',
        message: 'User not found'
      });
    }

    if (getUserDetails.file) {
      const filePath = path.join('uploads/', getUserDetails.file);
      if (fs.existsSync(filePath)) {
        fs.unlinkSync(filePath);
      }
    }

    await saveuser.findByIdAndDelete(userid);
    await saveUserDetails.findOneAndDelete({ user_id: userid });

    res.status(200).json({
      status: 'Success',
      message: 'User deleted successfully'
    });
  } catch (error) {
    console.error(error); // Log the actual error for debugging
    res.status(500).json({
      status: 'error',
      message: error.message // Send the actual error message
    });
  }
};







router.post('/createUser', upload.single('file'),saveUserData)
router.post('/loginUser', checkUser)
router.get('/getData', auth,userList)
router.put('/updateData/:id', auth,upload.single('file'),updateUser)

module.exports = router;
downloadDownload PNG downloadDownload JPEG downloadDownload SVG

Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!

Click to optimize width for Twitter