Skip to main content

Sample CRUD

Here we looking through Employee crud setup ual devices. :::

Folder Structure



pages/
├── employees/
│ └── create.js
│ └── create.module.scss
│ └── edit.js
│ └── edit.module.scss
│ └── index.js
│ └── index.module.scss


Listing


<Table
urlParam={url}
fieldNames={['name', 'email', 'phone']}
section="employee"
addButtonPlaceholder="Employee"
deleteCondition={{ checkCondition: false}}
/>

Create

for create we can use common slice api we can pass the data as apiData data.apiData = apiData; data.actionUrl = 'employee'; passing action url like this data.actionMethod = 'post'; and passing the api method like this


const apiData = {
name: data.name,
email: data.email,
phone: data.phone,
designation: data.designation.value,
skills,
status: data.status.value,
role: data.role.value,
};
data.designation = data.designation.value;
data.actionUrl = 'employee';
data.actionMethod = 'post';
data.apiData = apiData;
dispatch(Entry(data)).then((resp) => {
setSubmitting(false);
if (resp.payload.code === 200) {
navigate(-1);
} else if (resp.payload.code === 401 || resp.payload.code === 400) {
setError(resp.payload.message);
} else {
setError('Something went wrong!');
}
});
}


Edit

for edit we can use common slice api we can pass the data as apiData data.apiData = apiData; data.actionUrl = 'employee'; passing action url like this data.actionMethod = 'patch'; and passing the api method like this


const apiData = {
name: data.name,
email: data.email,
phone: data.phone,
designation: data.designation.value ? data.designation.value : defaultDesignation,
skills,
status: data.status.value ? data.status.value : defaultStatus,
};
data.actionUrl = `employee/${Decrypt(params.empId)}`;
data.actionMethod = 'patch';
data.updationData = apiData;
dispatch(Entry(data)).then((resp) => {
setSubmitting(false);
if (resp.payload.code === 200) {
navigate('/employee');
toast.success('User updation successfull');
} else if (resp.payload.code === 401 || resp.payload.code === 400) {
setError(resp.payload.message);
toast.error('Error');
} else {
navigate(-1);
}
});
}

Delete

      const actionData = {
actionUrl: `${section}/${params.data.id}`,
actionMethod: 'delete',
};
dispatch(Entry(actionData)).then((resp) => {
if (resp.payload.code === 400) {
confirmAlert({
title: 'Oops! Cant Delete!',
message: resp.payload.message,
buttons: [
{
label: 'Ok',
},
],
});
} else {
setDeletedUser(`data last deleted is ${params.data.id}`);
}
});

Sample Crud api Setup

Additional setup is required for Cordova to support programmatic builds. This section is not necessary for Capacitor.

Backend node api setup first we setup routings in routes folder


const express = require('express');
const auth = require('../../middlewares/auth');
const validate = require('../../middlewares/validate');
const employeevalidation = require('../../validations/employee.validation');
const employeeController = require('../../controllers/employee.controller');

const router = express.Router();

router
.route('/')
.post(validate(employeevalidation.createEmployee), employeeController.createEmployee)
.get(auth('getUsers'), validate(employeevalidation.getEmployees), employeeController.getEmployees);

router
.route('/:employeeId')
.get(validate(employeevalidation.getEmployee), employeeController.getEmployee)
.patch(validate(employeevalidation.updateEmployee), employeeController.updateEmployee)
.delete(auth('manageUsers'), validate(employeevalidation.deleteEmployee), employeeController.deleteEmployee);

module.exports = router;

second step we writting controllers post,get,patch,delete crud .


const httpStatus = require('http-status');
const pick = require('../utils/pick');
const ApiError = require('../utils/ApiError');
const catchAsync = require('../utils/catchAsync');
const { employeeService } = require('../services');
const { crud } = require('../services');

const createEmployee = catchAsync(async (req, res) => {
const user = await crud.createEntry(req.body, 'employee');
res.status(httpStatus.CREATED).send({ success: true, code: 200, user });
});

const getEmployees = catchAsync(async (req, res) => {
const daterange = pick(req.query, ['daterange']);
const filter = pick(req.query, ['active']);
const options = pick(req.query, ['sortBy', 'limit', 'page', 'searchBy']);
if (Object.keys(daterange).length) {
const dateranges = JSON.parse(daterange.daterange);
const fromDate = new Date(dateranges.startDate);
const toDate = new Date(dateranges.endDate);
filter.createdAt = { $lte: toDate, $gte: fromDate };
}
const result = await employeeService.queryEmployees(filter, options);
res.send(result);
});

const getEmployee = catchAsync(async (req, res) => {
const user = await employeeService.getEmployeeById(req.params.employeeId);
if (!user) {
throw new ApiError(httpStatus.NOT_FOUND, 'User not found');
}
res.send(user);
});

const updateEmployee = catchAsync(async (req, res) => {
const user = await employeeService.updateEmployeeById(req.params.employeeId, req.body);
res.send({ success: true, code: 200, user });
});

const deleteEmployee = catchAsync(async (req, res) => {
await employeeService.deleteEmployeeById(req.params.employeeId);
res.send({ sucess: true, code: 200, msg: 'Deleted Sucessfully' });
});

module.exports = {
createEmployee,
getEmployees,
getEmployee,
updateEmployee,
deleteEmployee,
};


Third step writting services for the controllers


const httpStatus = require('http-status');
const ApiError = require('../utils/ApiError');
const { Employee } = require('../models');

/**
* Create a user
* @param {Object} userBody
* @returns {Promise<User>}
*/
const createEmployee = async (userBody) => {
const checkFlag = 'email'; // email or phone
const checkParam = checkFlag === 'phone' ? userBody.phone : userBody.email;
if (await Employee.checkIfAvailable(checkFlag, checkParam)) {
throw new ApiError(httpStatus.BAD_REQUEST, `${checkFlag} already taken`);
}
return Employee.create(userBody);
};

/**
* Get user by email
* @param {string} email
* @returns {Promise<User>}
*/
const getUserByEmail = async (email) => {
return Employee.findOne({ email });
};

/**
* Query for users
* @param {Object} filter - Mongo filter
* @param {Object} options - Query options
* @param {string} [options.sortBy] - Sort option in the format: sortField:(desc|asc)
* @param {number} [options.limit] - Maximum number of results per page (default = 10)
* @param {number} [options.page] - Current page (default = 1)
* @returns {Promise<QueryResult>}
*/
const queryEmployees = async (filter, options) => {
const users = await Employee.paginate(filter, options);
return users;
};

/**
* Get user by id
* @param {ObjectId} id
* @returns {Promise<User>}
*/
const getEmployeeById = async (id) => {
return Employee.findById(id);
};

/**
* Update user by id
* @param {ObjectId} userId
* @param {Object} updateBody
* @returns {Promise<User>}
*/
const updateEmployeeById = async (userId, updateBody) => {
const user = await getEmployeeById(userId);
if (!user) {
throw new ApiError(httpStatus.NOT_FOUND, 'User not found');
}
const checkFlag = 'email'; // email or phone
const checkParam = checkFlag === 'phone' ? updateBody.phone : updateBody.email;
if (checkParam && (await Employee.checkIfAvailable(checkParam, userId))) {
throw new ApiError(httpStatus.BAD_REQUEST, `${checkFlag} already taken`);
}
Object.assign(user, updateBody);
await user.save();
return user;
};

/**
* Delete user by id
* @param {ObjectId} userId
* @returns {Promise<User>}
*/
const deleteEmployeeById = async (userId) => {
const user = await getEmployeeById(userId);
if (!user) {
throw new ApiError(httpStatus.NOT_FOUND, 'User not found');
}
await user.remove();
return user;
};

module.exports = { createEmployee, queryEmployees, getEmployeeById, getUserByEmail, updateEmployeeById, deleteEmployeeById };