Skip to content

Instantly share code, notes, and snippets.

@ajLapid718
Last active January 16, 2020 17:33
Show Gist options
  • Save ajLapid718/e88e9bf05eb6bc851c219fd486c2bc1c to your computer and use it in GitHub Desktop.
Save ajLapid718/e88e9bf05eb6bc851c219fd486c2bc1c to your computer and use it in GitHub Desktop.
// CRUD OPERATION: READ;
// HTTP VERB: GET;
router.get('/', async (req, res, next) => {
try {
// SELECT * FROM students
const students = await Student.findAll();
res.status(200).json(students);
}
catch (error) {
next(error);
}
});
// CRUD OPERATION: READ;
// HTTP VERB: GET;
router.get('/', async (req, res, next) => {
try {
// SELECT * FROM campuses JOIN students ON campuses."id" = students."campusId";
const campuses = await Campus.findAll({ include: [Student] });
res.status(200).json(campuses);
}
catch (error) {
next(error);
}
});
// CRUD OPERATION: READ;
// HTTP VERB: GET;
router.get('/:id', async (req, res, next) => {
try {
// SELECT * FROM students WHERE id = 'req.params.id'
let student = await Student.findById(req.params.id);
if (student) {
res.json(student);
}
else {
res.status(404).send('Student not found');
}
}
catch (error) {
next(error);
}
});
// CRUD OPERATION: CREATE;
// HTTP VERB: POST;
router.post('/', async (req, res, next) => {
try {
// INSERT INTO students ("col1", "col2") VALUES ('val1', 'val2')
let student = await Student.create(req.body);
res.status(201).json(student);
}
catch (err) {
next(err);
}
});
// CRUD OPERATION: UPDATE;
// HTTP VERB: PUT;
router.put('/:id', async (req, res, next) => {
try {
// UPDATE students SET "col1" = 'val1', "col2" = 'val2' WHERE id = req.params.id
let updatedStudentInfo = await Student.update(req.body, {
where: { id: req.params.id },
returning: true,
plain: true,
});
res.status(200).json(updatedStudentInfo[1]);
}
catch (err) {
next(err);
}
});
// CRUD OPERATION: DELETE;
// HTTP VERB: DELETE;
router.delete('/:id', async (req, res, next) => {
try {
// DELETE FROM students WHERE id = req.prams.id
const deleteCount = await Student.destroy({
where: { id: req.params.id },
});
res.sendStatus(204);
}
catch (err) {
next(err);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment