Skip to content

Commit

Permalink
feat: app api (#4)
Browse files Browse the repository at this point in the history
* feat: vercel prod

* fix: ses removed

* fix: app login return events

* fix: user_email added for get users for a event

* fix: get users api

* fix: updated get users in params

* feat: event creation

* fix: update api

* fix: 🐻 amazon ses added
  • Loading branch information
BharathSanjeeviT authored Feb 26, 2024
1 parent 85b2775 commit b24be2f
Show file tree
Hide file tree
Showing 11 changed files with 63 additions and 171 deletions.
7 changes: 4 additions & 3 deletions src/controllers/adminController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,16 +152,16 @@ const EventLogin = async (req: Request, res: Response, next: NextFunction) => {

/* FOR GETTING USERS FROM A PARTICULAR EVENT */
const GetUsersFromEvent = async (req: Request, res: Response) => {
if (!req.body.admin.is_event_admin) {
if (!req.body.admin.is_event_admin && (req.body.admin.events_id.includes(req.params.event_is))) {
return res
.status(401)
.json({ statusCode: 401, body: { message: "UnAuthorized Request" } });
}

const client = await pool.connect();
const { event_id } = EventIdValidator.parse(req.body);
const { event_id } = EventIdValidator.parse(req.params);
const data = await client.query(getUsersforEvent, [event_id]);

client.release()
return res.status(200).json({
statusCode: 200,
body: { message: "Sucessfull", data: data.rows },
Expand All @@ -182,6 +182,7 @@ const UpdateUserCart = async (req: Request, res: Response) => {
await client.query(insertMissingOnes, [user_email, events_id]);
await client.query(deleteFromCart, [user_email, events_id]);
await client.query(commit);
client.release()

return res.status(200).json({
statusCode: 200,
Expand Down
123 changes: 33 additions & 90 deletions src/controllers/eventController.ts
Original file line number Diff line number Diff line change
@@ -1,110 +1,53 @@
import { Response, Request } from "express";
import { pool } from "../../config/db.js";
import { Events, EventsHome } from "../interfaces/eventInterface.js";
import {
createEvent,
deleteEvent,
getAllEvents,
getEventDetails,
updateEvent,
editEvent
} from "../queries/eventQueries.js";
import { EventIdValidator } from "../validators/eventValidators.js";
const eventProperties = [
"name",
"description",
"tag_line",
"rules",
"img_link",
"fee",
"date",
"team_size",
"youtube",
"instagram",
"first_prize",
"second_prize",
"third_prize",
"is_paid",
];

const GetAllEvents = async (_: Request, res: Response) => {
const client = await pool.connect();
const result = await client.query(getAllEvents);
const events: Array<EventsHome> = result.rows;
client.release();

return res
.status(200)
.json({ status: 200, body: { message: "Sucessfull", events } });
};

const GetSpecificEvent = async (req: Request, res: Response) => {
const id = EventIdValidator.parse(req.params.id);
const client = await pool.connect();
const result = await client.query(getEventDetails, [id]);
const events: Array<Events> = result.rows;
client.release();

return res
.status(200)
.send({ status: 200, body: { message: "Sucessfull", events } });
};

const CreateEvent = async (req: Request, res: Response) => {
const client = await pool.connect();
const eventData = req.body;
const sql_arr = eventProperties.map((prop) => eventData[prop]);
if (eventData.name) {
await client.query(createEvent, sql_arr).then(() => {
client.release();
});

if(req.body.admin.is_super_admin){
const { event_id, name, fee, pass_id} = req.body
const client = await pool.connect()
await client.query(createEvent, [event_id, name, fee, pass_id])
client.release()
return res
.status(200)
.json({ status: 200, body: { message: "Sucessfull" } });
} else
}else
return res
.status(400)
.json({ status: 400, body: { message: "BadRequest" } });
};

const DeleteEvent = async (req: Request, res: Response) => {
const id = EventIdValidator.parse(req.params.id);
if (id) {
const client = await pool.connect();
await client.query(deleteEvent, [id]).then(() => {
client.release();
});
return res
.status(200)
.json({ status: 200, body: { message: "Sucessfull" } });
} else
return res
.status(400)
.json({ status: 400, body: { message: "BadRequest" } });
.status(403)
.json({ status: 403, body: { message: "Not Authorized" } });
};

const UpdateEvent = async (req: Request, res: Response) => {
const id = EventIdValidator.parse(req.params.id);
const client = await pool.connect();
const eventData = { ...req.body };
const sql_arr = eventProperties.map((props) => eventData[props]);
if (id) {
await client.query(updateEvent, [...sql_arr, id]);
client.release();

return res
.status(200)
.json({ status: 200, body: { message: "Sucessfull" } });
} else
if(req.body.admin.is_super_admin || (req.body.admin.events_id.includes(req.body.event_id))){
try{
const { event_id, name, fee, pass_id} = req.body
const client = await pool.connect()
const data = await client.query(editEvent, [event_id, name, fee, pass_id])
client.release()
if(data.rows.length == 1)
return res
.status(200)
.json({ status: 200, body: { message: "Updated Sucessfull" } });
else
return res
.status(500)
.json({ status: 500, body: { message: "Event doesnot exist" } });
} catch(err){
console.log(err)
return res
.status(500)
.json({ status: 500, body: { message: "Event not updated" } });
}
}else
return res
.status(400)
.json({ status: 400, body: { message: "BadRequest" } });
.status(403)
.json({ status: 403, body: { message: "Not Authorized" } });
};

export {
CreateEvent,
DeleteEvent,
GetAllEvents,
GetSpecificEvent,
UpdateEvent,
UpdateEvent
};
3 changes: 3 additions & 0 deletions src/controllers/userController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ const GetUserDetails = async (req: Request, res: Response) => {
const { email } = emailValidator.parse(req.body.user);
const client = await pool.connect();
const result = await client.query(getUserDetails, [email]);
client.release()
return res.status(200).json({
statusCode: 200,
body: { message: "Request Sucessfull", data: result.rows },
Expand Down Expand Up @@ -53,6 +54,7 @@ const GetUserCart = async (req: Request, res: Response) => {
const { email } = emailValidator.parse(req.body.user);
const client = await pool.connect();
const data = await client.query(getCart, [email]);
client.release()
let cartItems: Record<string, Array<cartType>> = {};
data.rows.forEach((event: cartType) => {
if (!cartItems[event.pass_id]) cartItems[event.pass_id] = [];
Expand All @@ -78,6 +80,7 @@ const UpdateUserCart = async (
await client.query(insertMissingOnes, [email, events_id]);
await client.query(deleteFromCart, [email, events_id]);
await client.query(commit);
client.release()

return res.status(200).json({
statusCode: 200,
Expand Down
12 changes: 6 additions & 6 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import cors from "cors";
import { PORT } from "../config/port.js";
import { Admin, Events, Users, Support } from "./routes/index.js";
import errorHandler from "./middlewares/errorHandler.js";
import { AuthourizeUser } from "./middlewares/authHandler.js";
import { AuthourizeAdmin, AuthourizeUser } from "./middlewares/authHandler.js";
import serverless from "serverless-http";

const app = express();
Expand All @@ -22,15 +22,15 @@ app.use(cors(corsOptions));

app.use(express.json());

// app.use(Events.BASE_ROUTE, Events.router);
app.use(Events.BASE_ROUTE, AuthourizeAdmin, Events.router);
app.use(Users.BASE_ROUTE, AuthourizeUser, Users.router);
app.use(Admin.BASE_ROUTE, Admin.router);
app.use(Support.BASE_ROUTE, Support.router);

app.use(errorHandler);

app.listen(PORT, () => {
console.log(`PORT RUNNING ON ${PORT}`);
});
// app.listen(PORT, () => {
// console.log(`PORT RUNNING ON ${PORT}`);
// });

// export const handler = serverless(app);
export const handler = serverless(app);
6 changes: 5 additions & 1 deletion src/middlewares/authHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,10 @@ export const CreateEventAdminToken = async (req: Request, res: Response) => {
const token: string = jwt.sign(tokenData, SECRET);
return res.status(200).json({
statusCode: 200,
body: { message: "Token Generated Sucessfully", token: token },
body: { message: "Token Generated Sucessfully",
token: token ,
event: req.body.events_id,
isAdmin: (req.body.events_id.length === 0)
},
});
};
2 changes: 1 addition & 1 deletion src/middlewares/errorHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ function errorHandler(
},
});
}

console.log(err)
return res.status(500).json({
statusCode: 500,
body: {
Expand Down
2 changes: 1 addition & 1 deletion src/queries/adminQueries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ export const insertAdmin: string =
"INSERT INTO admin (uname, password) VALUES ($1, $2)";
export const getAdminPassword: string =
"SELECT password FROM admin WHERE uname = $1";
export const getUsersforEvent: string = `select u.name, u.phone_no, u.clg_name, ue.is_present, ue.paid from users u join
export const getUsersforEvent: string = `select u.name, u.phone_no, u.clg_name, ue.is_present, ue.paid, u.email from users u join
users_events ue on ue.user_email = u.email where ue.event_id = $1`;
export const insertEvent: string = `insert into events (name, id, fee, pass_id, password) values
($1, $2, $3, $4, $5)`;
Expand Down
62 changes: 6 additions & 56 deletions src/queries/eventQueries.ts
Original file line number Diff line number Diff line change
@@ -1,57 +1,7 @@
export const getAllEvents: string = `
SELECT
event_id,
name,
img_link,
tag_line,
date,
description
FROM events`;
export const getEventDetails: string = `
SELECT
e.event_id,
e.name AS event_name,
e.description,
e.tag_line,
e.rules,
e.img_link,
e.fee,
e.team_size,
e.date,
e.youtube,
e.instagram,
e.first_prize,
e.second_prize,
e.third_prize,
i.name AS incharge_name,
i.id AS incharge_id,
i.phone_no
FROM
events e
LEFT JOIN
incharge_event ie ON e.event_id = ie.event_id
LEFT JOIN
incharges i ON i.id = ie.incharge_id
WHERE
e.event_id = $1;
`;
export const createEvent: string = `INSERT INTO
events (name, description, tag_line, rules, img_link, fee, date, team_size, youtube, instagram, first_prize, second_prize, third_prize, is_paid)
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14)`;
export const deleteEvent: string = "DELETE FROM events WHERE event_id=$1";
export const updateEvent: string = `UPDATE events SET
name = $1,
description = $2,
tag_line = $3,
rules = $4,
img_link = $5,
fee = $6,
date = $7,
team_size = $8,
youtube = $9,
instagram = $10,
first_prize = $11,
second_prize = $12,
third_prize = $13,
is_paid = $14
WHERE event_id=$15`;
events (id, name, fee, pass_id) VALUES ($1, $2, $3, $4)`;
export const editEvent: string = `UPDATE events SET
name = $2,
fee = $3,
pass_id = $4
WHERE id = $1 returning *`;
2 changes: 1 addition & 1 deletion src/routes/adminRoute.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ router.put("/pay-event", AuthourizeAdmin, asyncMiddleware(UpdatePaid));
router.put("/update-cart", AuthourizeAdmin, asyncMiddleware(UpdateUserCart));

router.put("/allow", AuthourizeAdmin, asyncMiddleware(VerifyPaid));
router.get("/get-users", AuthourizeAdmin, asyncMiddleware(GetUsersFromEvent));
router.get("/get-users/:event_id", AuthourizeAdmin, asyncMiddleware(GetUsersFromEvent));

//Comment this while PRODUCTION
router.post("/signup", asyncMiddleware(UserSignUp));
Expand Down
13 changes: 2 additions & 11 deletions src/routes/eventsRoute.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,13 @@
import express from "express";
import { Module } from "../../libs/utils/types/module.js";
import {
CreateEvent,
DeleteEvent,
GetAllEvents,
GetSpecificEvent,
UpdateEvent,
} from "../controllers/eventController.js";
import { CreateEvent, UpdateEvent } from "../controllers/eventController.js";
import asyncMiddleware from "../middlewares/asyncMiddleware.js";

const router = express.Router();
const BASE_ROUTE = "/events";

router.get("/", asyncMiddleware(GetAllEvents));
router.get("/:id", asyncMiddleware(GetSpecificEvent));
router.post("/", asyncMiddleware(CreateEvent));
router.delete("/:id", asyncMiddleware(DeleteEvent));
router.put("/:id", asyncMiddleware(UpdateEvent));
router.put("/", asyncMiddleware(UpdateEvent));

const MODULE: Module = {
router,
Expand Down
2 changes: 1 addition & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,5 @@
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src/**/*", "./jest.config.ts"]
"include": ["src/**/*", "./jest.config.ts", "api/*"]
}

0 comments on commit b24be2f

Please sign in to comment.