Skip to content

Commit 7ce05e9

Browse files
authored
Merge pull request #20 from rice-apps/admin-get-routes
Admin get routes (They need to be tested)
2 parents cc7e030 + 0fe3968 commit 7ce05e9

27 files changed

+926
-286
lines changed

server/app.ts

Lines changed: 31 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -7,25 +7,30 @@ const port = process.env.PORT;
77

88
const { default: mongoose } = require("mongoose");
99

10-
const uri =
11-
"mongodb+srv://" +
12-
process.env.MONGO_ADMIN_USERNAME +
13-
":" +
14-
process.env.MONGO_ADMIN_PASSWORD +
15-
"@thi-cluster.nkv5u.mongodb.net/thi-behavior?retryWrites=true&w=majority&appName=thi-cluster";
16-
10+
const uri =
11+
"mongodb+srv://" +
12+
process.env.MONGO_ADMIN_USERNAME +
13+
":" +
14+
process.env.MONGO_ADMIN_PASSWORD +
15+
"@thi-cluster.nkv5u.mongodb.net/thi-behavior?retryWrites=true&w=majority&appName=thi-cluster";
1716

1817
async function run() {
1918
try {
20-
await mongoose.connect(uri, {serverSelectionTimeoutMS: 5000});
21-
console.log("Pinged your deployment. You successfully connected to MongoDB!");
19+
await mongoose.connect(uri, { serverSelectionTimeoutMS: 5000 });
20+
console.log(
21+
"Pinged your deployment. You successfully connected to MongoDB!"
22+
);
2223
const app = express();
23-
24+
2425
app.use(cors());
25-
app.use(morgan(':date :method :url :status :res[content-length] - :response-time ms'));
26+
app.use(
27+
morgan(
28+
":date :method :url :status :res[content-length] - :response-time ms"
29+
)
30+
);
2631
app.use(express.json());
27-
app.use('/api', require("./routes"));
28-
32+
app.use("/api", require("./routes"));
33+
2934
app.use([notFoundHandle, responseHandle]);
3035

3136
app.listen(port, () => {
@@ -41,12 +46,18 @@ const notFoundHandle = (req: Request, res: Response, next: NextFunction) => {
4146
success: false,
4247
statusCode: HttpStatus.StatusCodes.NOT_FOUND,
4348
message: HttpStatus.getReasonPhrase(HttpStatus.StatusCodes.NOT_FOUND),
44-
})
45-
}
49+
});
50+
};
4651

47-
const responseHandle = (output: any, req: Request, res: Response, next: NextFunction) => {
52+
const responseHandle = (
53+
output: any,
54+
req: Request,
55+
res: Response,
56+
next: NextFunction
57+
) => {
4858
const { success, statusCode, status, message, ...rest } = output;
49-
const code = statusCode || status || HttpStatus.StatusCodes.INTERNAL_SERVER_ERROR;
59+
const code =
60+
statusCode || status || HttpStatus.StatusCodes.INTERNAL_SERVER_ERROR;
5061
if (success) {
5162
res.status(HttpStatus.StatusCodes.OK).json({ ...output });
5263
return;
@@ -55,7 +66,7 @@ const responseHandle = (output: any, req: Request, res: Response, next: NextFunc
5566
success: success,
5667
statusCode,
5768
message,
58-
...rest
69+
...rest,
5970
});
60-
}
61-
run().catch(console.dir);
71+
};
72+
run().catch(console.dir);

server/controllers/abc.controller.ts

Lines changed: 175 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,175 @@
1+
import { NextFunction, Request, Response } from "express";
2+
import mongoose from "mongoose";
3+
const { Abc, Account } = require("../models");
4+
const fileUpload = require("express-fileupload");
5+
const excelToJson = require("convert-excel-to-json");
6+
const HttpStatus = require("http-status-codes");
7+
const { ErrorResponse } = require("../helper");
8+
9+
class AbcController {
10+
async create(req: Request, res: Response, next: NextFunction) {
11+
// TODO -- get the id of the account that is logged in
12+
try {
13+
const abc = new Abc(req.body);
14+
const savedAbc = await abc.save();
15+
return savedAbc;
16+
} catch (err: any) {
17+
throw err;
18+
}
19+
}
20+
async getAllRecordsByAccount(req: any, res: Response, next: NextFunction) {
21+
const { id } = req.user;
22+
// not sure if account email will be in the body -- method of doing this may be changed in the future
23+
const account = await Account.findById(
24+
id,
25+
"_id password is_admin is_deleted"
26+
).exec();
27+
if (!account || account.is_deleted) {
28+
throw new ErrorResponse({
29+
statusCode: HttpStatus.StatusCodes.BAD_REQUEST,
30+
message: "ACCOUNT NOT FOUND",
31+
});
32+
}
33+
const abcs = await Abc.find({ staff: account._id }).exec();
34+
if (!abcs) {
35+
throw new ErrorResponse({
36+
statusCode: HttpStatus.StatusCodes.NOT_FOUND,
37+
message: `Abcs created by staff ${id} not found.`,
38+
});
39+
}
40+
return abcs;
41+
}
42+
async getRecordByID(req: Request, res: Response, next: NextFunction) {
43+
try {
44+
const id = getId(req);
45+
const abc = await Abc.findById(id);
46+
if (!abc) {
47+
throw new ErrorResponse({
48+
statusCode: HttpStatus.StatusCodes.NOT_FOUND,
49+
message: `Abc with id ${id} not found.`,
50+
});
51+
}
52+
53+
return abc;
54+
} catch (err: any) {
55+
throw err;
56+
}
57+
}
58+
async updateRecordById(req: Request, res: Response, next: NextFunction) {
59+
try {
60+
const id = getId(req);
61+
const newData = req.body;
62+
const updatedAbc = await Abc.findByIdAndUpdate(id, newData);
63+
if (!updatedAbc) {
64+
throw new ErrorResponse({
65+
statusCode: HttpStatus.StatusCodes.NOT_FOUND,
66+
message: `Abc with id ${id} not found.`,
67+
});
68+
}
69+
70+
return updatedAbc;
71+
} catch (err: any) {
72+
throw err;
73+
}
74+
}
75+
async deleteRecordById(req: Request, res: Response, next: NextFunction) {
76+
try {
77+
const id = getId(req);
78+
if (!mongoose.Types.ObjectId.isValid(id)) {
79+
throw new ErrorResponse({
80+
statusCode: HttpStatus.StatusCodes.BAD_REQUEST,
81+
message: `Invalid ID format for abc: ${id}.`,
82+
});
83+
}
84+
const deletedAbc = await Abc.findByIdAndDelete(id);
85+
if (!deletedAbc) {
86+
throw new ErrorResponse({
87+
statusCode: HttpStatus.StatusCodes.NOT_FOUND,
88+
message: `Abc with id ${id} not found.`,
89+
});
90+
}
91+
92+
return deletedAbc;
93+
} catch (err: any) {
94+
throw err;
95+
}
96+
}
97+
async getRecordsByStudentId(
98+
req: Request,
99+
res: Response,
100+
next: NextFunction
101+
) {
102+
try {
103+
const studentId = req.params.studentId;
104+
const records = await Abc.find({ student_id: studentId });
105+
106+
if (!records || records.length === 0) {
107+
return res.status(HttpStatus.StatusCodes.NOT_FOUND).json({
108+
message: `No ABC records found for student ID: ${studentId}.`,
109+
});
110+
}
111+
return res.status(HttpStatus.StatusCodes.OK).json(records);
112+
} catch (err: any) {
113+
next(err);
114+
}
115+
}
116+
117+
async getRecordsByStaffId(req: Request, res: Response, next: NextFunction) {
118+
try {
119+
const staffId = req.params.staffId;
120+
if (!mongoose.Types.ObjectId.isValid(staffId)) {
121+
return res.status(HttpStatus.StatusCodes.BAD_REQUEST).json({
122+
message: `Invalid Staff ID format: ${staffId}.`,
123+
});
124+
}
125+
126+
const records = await Abc.find({ staff: staffId });
127+
128+
if (!records || records.length === 0) {
129+
return res.status(HttpStatus.StatusCodes.NOT_FOUND).json({
130+
message: `No ABC records found for staff ID: ${staffId}.`,
131+
});
132+
}
133+
return res.status(HttpStatus.StatusCodes.OK).json(records);
134+
} catch (err: any) {
135+
next(err);
136+
}
137+
}
138+
139+
async exportRecord(req: any, res: Response, next: NextFunction) {
140+
// TODO: Implement
141+
if (!req.files || Object.keys(req.files).length === 0) {
142+
return res.status(400).send("No files were uploaded.");
143+
}
144+
145+
// The name of the input field (i.e. "sampleFile") is used to retrieve the uploaded file
146+
let record: File = req.files.record;
147+
148+
// Process your file
149+
const result: JSON = excelToJson({
150+
sourceFile: record.name,
151+
});
152+
153+
// for (const key in result) {
154+
// console.log(`${key}: ${result[key]}`);
155+
// }
156+
}
157+
// async importRecord(req: Request, res: Response, next: NextFunction) {
158+
// // TODO: Implement
159+
// }
160+
}
161+
162+
const getId = (req: Request) => {
163+
const id = req.params.id;
164+
165+
if (!mongoose.Types.ObjectId.isValid(id)) {
166+
throw new ErrorResponse({
167+
statusCode: HttpStatus.StatusCodes.BAD_REQUEST,
168+
message: `Invalid ID format for abc: ${id}.`,
169+
});
170+
}
171+
172+
return id;
173+
};
174+
175+
module.exports = new AbcController();

0 commit comments

Comments
 (0)