-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathroutes.js
More file actions
55 lines (46 loc) · 1.6 KB
/
routes.js
File metadata and controls
55 lines (46 loc) · 1.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
const express = require('express');
const mongoose = require('mongoose');
const { Product } = require('./models/product');
const router = express.Router();
module.exports = { router };
router.get('/', (req, res) => {
res.send('Hello world!');
});
router.get('/products', async (req, res) => {
const { category } = req.query;
if (category) {
const products = await Product.find({ category });
res.render('products/index', { products, category });
}
const products = await Product.find({});
res.render('products/index', { products, category: 'All' });
});
router.get('/products/create', (req, res) => {
res.render('products/create');
});
// get specific product
// pastikan posisi routing ini di paling bawah supaya routing lain tidak dianggap sebagai query parameter
router.get('/products/:id', async (req, res) => {
const product = await Product.findById(req.params.id);
res.render('products/show', { product });
});
// edit specific product
router.get('/products/:id/edit', async (req, res) => {
const product = await Product.findById(req.params.id);
res.render('products/edit', { product });
});
// post routing
router.post('/products', async (req, res) => {
const product = new Product(req.body);
await product.save();
res.redirect(`/products/${product.id}`);
});
router.put('/products/:id', async (req, res) => {
const product = await Product.findByIdAndUpdate(req.params.id, req.body);
res.redirect(`/products/${product._id}`);
});
// delete routing
router.delete('/products/:id', async (req, res) => {
await Product.findByIdAndDelete(req.params.id);
res.redirect('/products');
});