Skip to content

Commit

Permalink
add api for subscribers
Browse files Browse the repository at this point in the history
  • Loading branch information
Nguyen-Duc-Khai committed Dec 12, 2023
1 parent 3c36a8d commit dc824bb
Show file tree
Hide file tree
Showing 7 changed files with 265 additions and 167 deletions.
22 changes: 17 additions & 5 deletions backend/src/controller/subscribers.controller.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,26 @@
const subscribersService = require("../service/subscribers.service");
const catchAsync = require('../utils/catchAsync');
const { Response } = require("../utils/response");
const catchAsync = require("../utils/catchAsync");
const { Response } = require("../utils/response");

const httpStatus = require('http-status');
const httpStatus = require("http-status");

const insertSubscriber = catchAsync(async (req, res) => {
const DTO = await subscribersService.insertSubscriber(req.body);
Response(res, httpStatus.CREATED, DTO.message, DTO.data);
const DTO = await subscribersService.insertSubscriber(req.body);
Response(res, httpStatus.CREATED, DTO.message, DTO.data);
});

const getAllSubscribers = catchAsync(async (req, res) => {
const DTO = await subscribersService.getAllSubscribers();
Response(res, httpStatus.OK, DTO.message, DTO.data);
});

const deleteSubscriber = catchAsync(async (req, res) => {
const DTO = await subscribersService.deleteSubscriber(req.params);
Response(res, httpStatus.OK, DTO.message, DTO.data);
});

exports.subscribersController = {
insertSubscriber,
getAllSubscribers,
deleteSubscriber,
};
21 changes: 20 additions & 1 deletion backend/src/repository/subscribers.repository.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,23 @@ const insertNewSubscriber = async (email) => {
return subscriber;
};

module.exports = { findExistedSubscriber, insertNewSubscriber };
const getAllSubscribers = async () => {
const subscribers = await SubscriberModel.find();
return subscribers;
};

const findSubscriberById = async (id) => {
return await SubscriberModel.findOne({ _id: id });
};

const deleteSubscriberById = async (id) => {
return await SubscriberModel.findByIdAndDelete(id);
};

module.exports = {
findExistedSubscriber,
insertNewSubscriber,
getAllSubscribers,
deleteSubscriberById,
findSubscriberById,
};
11 changes: 6 additions & 5 deletions backend/src/routes/v1/subscribers.route.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
const express = require("express");
const router = express.Router();
const { celebrate, Joi, Segments } = require("celebrate");
const httpStatus = require("http-status");

const {DefaultResponse} = require("../../utils/DefaultResponse");

const {
subscribersController,
Expand All @@ -12,8 +9,8 @@ const {
var insertSubscriberValidationSchema = {
[Segments.BODY]: Joi.object().keys({
email: Joi.string().required().email().messages({
'email': 'Email is required and follow pattern [email protected]',
})
email: "Email is required and follow pattern [email protected]",
}),
}),
};

Expand All @@ -23,4 +20,8 @@ router.post(
subscribersController.insertSubscriber
);

router.get("/", subscribersController.getAllSubscribers);

router.delete("/:id", subscribersController.deleteSubscriber);

module.exports = router;
84 changes: 64 additions & 20 deletions backend/src/service/subscribers.service.js
Original file line number Diff line number Diff line change
@@ -1,35 +1,79 @@
const subscribersRepository = require("../repository/subscribers.repository");
const ApiError = require("../utils/ApiError");
const httpStatus = require('http-status');
const httpStatus = require("http-status");

const insertSubscriber = async ({ email }) => {
try {
const existSubscriber =
await subscribersRepository.findExistedSubscriber(email);
try {
const existSubscriber = await subscribersRepository.findExistedSubscriber(
email
);

console.log(existSubscriber);
console.log(existSubscriber);

if (existSubscriber) {
throw new ApiError(httpStatus.BAD_REQUEST, "Email address subscribed already");
}
if (existSubscriber) {
throw new ApiError(
httpStatus.BAD_REQUEST,
"Email address subscribed already"
);
}

const response = await subscribersRepository.insertNewSubscriber(email);
const response = await subscribersRepository.insertNewSubscriber(email);

return {
message: `Insert subscriber success with id ${response._id}`,
data: response
}
} catch (error) {
let statusCode = httpStatus.INTERNAL_SERVER_ERROR;
return {
message: `Insert subscriber success with id ${response._id}`,
data: response,
};
} catch (error) {
let statusCode = httpStatus.INTERNAL_SERVER_ERROR;

if (error.statusCode) {
statusCode = error.statusCode;
}
if (error.statusCode) {
statusCode = error.statusCode;
}

throw new ApiError(statusCode, error.message);
}
throw new ApiError(statusCode, error.message);
}
};

const getAllSubscribers = async () => {
try {
const subscribers = await subscribersRepository.getAllSubscribers();

return {
message: "Get subscribers successfull",
data: subscribers,
};
} catch (error) {
let statusCode = httpStatus.INTERNAL_SERVER_ERROR;

if (error.statusCode) {
statusCode = error.statusCode;
}

throw new ApiError(statusCode, error.message);
}
};

const deleteSubscriber = async ({ id }) => {
try {
const res = await subscribersRepository.deleteSubscriberById(id);

return {
message: "Delete successfull",
data: res,
};
} catch (error) {
let statusCode = httpStatus.INTERNAL_SERVER_ERROR;

if (error.statusCode) {
statusCode = error.statusCode;
}

throw new ApiError(statusCode, error.message);
}
};

module.exports = {
insertSubscriber,
getAllSubscribers,
deleteSubscriber,
};
28 changes: 18 additions & 10 deletions dashboard/src/components/MainMenu.jsx
Original file line number Diff line number Diff line change
@@ -1,35 +1,43 @@
import { useState } from 'react';
import "../styles/main_menu.style.css";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faHouse, faDownload, faGear } from "@fortawesome/free-solid-svg-icons";
import { faHouse, faGear } from "@fortawesome/free-solid-svg-icons";
import {
StyledMainMenuItemText,
StyledMainMenuText,
} from "../style_components/StyledText";
import { Link } from "react-router-dom";

function MainMenu() {

const handleChangeMenuItem = (e) => {
const menuItems = document.querySelectorAll(".main_menu .main_menu_container a .menu_item");

menuItems.forEach(item => item.classList.remove("active"));
e.currentTarget.children[0].classList.add("active");
}
const menuItems = document.querySelectorAll(
".main_menu .main_menu_container a .menu_item"
);

menuItems.forEach((item) => item.classList.remove("active"));
e.currentTarget.children[0].classList.add("active");
};

return (
<div className="main_menu">
<StyledMainMenuText>Main Menu</StyledMainMenuText>

<div className="main_menu_container">
<Link to="/dashboard" style={{ width: "100%" }} onClick={(e) => handleChangeMenuItem(e)}>
<Link
to="/dashboard"
style={{ width: "100%" }}
onClick={(e) => handleChangeMenuItem(e)}
>
<div className="menu_item active">
<FontAwesomeIcon icon={faHouse} />
<StyledMainMenuItemText>Dashboard</StyledMainMenuItemText>
</div>
</Link>

<Link to="/settings" style={{ width: "100%" }} onClick={(e) => handleChangeMenuItem(e)}>
<Link
to="/settings"
style={{ width: "100%" }}
onClick={(e) => handleChangeMenuItem(e)}
>
<div className="menu_item">
<FontAwesomeIcon icon={faGear} />
<StyledMainMenuItemText>Settings</StyledMainMenuItemText>
Expand Down
42 changes: 29 additions & 13 deletions dashboard/src/config/axios.jsx
Original file line number Diff line number Diff line change
@@ -1,25 +1,41 @@
import axios from 'axios';
import axios from "axios";

const API_URL = import.meta.env.VITE_API_URL;

const axiosConfig = {
baseURL: API_URL,

baseURL: API_URL,
};

const instance = axios.create(axiosConfig);

instance.insertSubscriberHandler = async (email) => {
return (await instance.post('subscribers',
{
email: email
},
{
headers: {
'Content-Type': 'application/json'
return await instance.post(
"subscribers",
{
email: email,
},
{
headers: {
"Content-Type": "application/json",
},
}
}))
}
);
};

instance.getSubscribersHandler = async () => {
return await instance.get("subscribers", {
headers: {
"Content-Type": "application/json",
},
});
};

instance.deleteSubscribersByIdHandler = async (id) => {
return await instance.delete(`subscribers/${id}`, {
headers: {
"Content-Type": "application/json",
},
});
};

export const Axios = instance;
export const Axios = instance;
Loading

0 comments on commit dc824bb

Please sign in to comment.