Belajar Membuat Web Menggunakan Framework Express JS (Part 7) - CRUDPRO

Belajar Membuat Web Menggunakan Framework Express JS (Part 7)


Membuat CRUD (Create Read Update Delete) Pada Framework Express JS - Pada tutorial sebelumnya kita sudah belajar Menampilkan Data Menggunakan Datatables Pada Framework Express JS, nah sekarang kita langsung saja ke topik pembahasannya yaitu membuat fitur crud pada framework Express JS

Edit dibagian file views/dashboard/user/index.pug kemudian replace source yang lama dengan source code berikut ini

extends ../layout

block stylesheets
    link(rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/bs4/dt-1.10.20/datatables.min.css")

block content

    .row
        .col-md-12
            .card
                .card-body
                    a.btn.btn-primary(href=`${ route.dashboards.pages.user.create }`) Create
                    br
                    br
                    table.table.table-condensed#DataTable
                        thead
                            tr
                                th.text-center Username
                                th.text-center Email
                                th.text-center
                        tbody

block scripts
    script(type="text/javascript" src="https://cdn.datatables.net/v/bs4/dt-1.10.20/datatables.min.js")
    script.
        function users() {
            jQuery('#DataTable').DataTable({
                ordering : false,
                processing : false,
                serverSide : true,
                buttons : [],
                columns : [
                    {
                        data : 'username',
                        name : 'username',
                        className : 'text-center'
                    },
                    {
                        data : 'email',
                        name : 'email',
                        className : 'text-center'
                    },
                    {
                        data : function(data) {
                            return `
                                <a href="#{route.dashboards.pages.user.edit}/${data.id}" class="btn btn-primary btn-sm"><i class="fa fa-edit"></i></a>
                                <a href="#{route.dashboards.pages.user.destroy}/${data.id}" class="btn btn-danger btn-sm"><i class="fa fa-trash"></i></a>
                            `;
                        },
                        name : 'action',
                        className : 'text-center'
                    }
                ],
                ajax : {
                    url : '#{route.dashboards.pages.user.index}'
                }
            });
        }

        users();

Sehingga akan terlihat seperti ini

Membuat CRUD (Create Read Update Delete) Pada Framework Express JS

1. Membuat Halaman Create Dan Fungsinya

Tambahkan 2 objek rute yang berada di dalam objek user di dalam file routes.js

user : {
    index : dashboardPrefix + '/page/users',
    create : dashboardPrefix + '/page/users/create',
    store : dashboardPrefix + '/page/users/store'
}

Kemudian tambahkan 2 rute tersebut di dalam file web.js

.get(routePrefix.dashboards.pages.user.create, userController.create)
.post(routePrefix.dashboards.pages.user.store,[
    check('username','The username is required.').not().isEmpty(),
    check('email','The email is required.').not().isEmpty(),
    check('email','Invalid email format.').isEmail(),
    check('password', 'Password is required.').not().isEmpty(),
], userController.store)

Lalu buat 2 method berikut di dalam file controller user seperti dibawah ini

exports.create = function(req, res, next) {
    return res.render('dashboard/user/create', {
        title : 'Create User'
    });
}

exports.store = function(req, res, next) {

    const errors = validationResult(req);

    if (!errors.isEmpty()) {
        return res.status(422).json({error : 1, message : errors.mapped() });
    }

    /*
    * Create User With Promise
    */
    var createUser = new Promise(function(resolve) {
        model.User.create({
            username : req.body.username,
            email : req.body.email,
            password : req.body.email
        }).then(callBack => 
            resolve(callBack)
        ).catch(function (err) {
            res.json({
                error   : true,
                message : err.message,
                redirect : false,
            });
        });
    });

    createUser.then(function(callBack) {
        res.json({
            error   : false,
            message : "User was created.",
            redirect : req.body.redirect,
        });
    });
}

Setelah kita membuat fungsinya kita buat viewnya, buat file create.pug, berikut source codenya

extends ../layout

block stylesheets
    //- Todo
block content

    .row
        .col-md-12
            .card
                .card-body
                    form.userForm
                        input(type="hidden" name="redirect" value=`${route.dashboards.pages.user.index}`)
                        .form-group.row
                            label.col-sm-2.col-form-label(for="username") Username
                            .col-sm-10
                                input(type="text" class="form-control" id="username" name="username")
                                <div class="invalid-feedback" id="username-feedback"></div>
                        .form-group.row
                            label.col-sm-2.col-form-label(for="email") Email
                            .col-sm-10
                                input(type="email" class="form-control" id="email" name="email")
                        .form-group.row
                            label.col-sm-2.col-form-label(for="password") Password
                            .col-sm-10
                                input(type="password" class="form-control" id="password" name="password")
                        .row
                            .col-sm-12
                                a.btn.btn-primary(href=`${ route.dashboards.pages.user.index }`) Back
                                .
                                    &nbsp;
                                button.btn.btn-primary(onclick="createUser()" type="button") Save
block scripts
    script.
        function createUser() {

            var usernameInput = jQuery('#username'),
                usernameFeedback = jQuery('#username-feedback');

            var emailInput = jQuery('#email'),
                emailFeedback = jQuery('#email-feedback');

            var passwordInput = jQuery('#password'),
                passwordFeedback = jQuery('#password-feedback');

            jQuery.ajax({
                url : '#{route.dashboards.pages.user.store}',
                dataType : 'json',
                method : 'post',
                data : jQuery('.userForm').serialize(),
                beforeSend : function() {
                    usernameInput.attr('class','form-control');
                    usernameFeedback.html(``);

                    emailInput.attr('class','form-control');
                    emailFeedback.html(``);

                    passwordInput.attr('class','form-control');
                    passwordFeedback.html(``);
                },
                success : function(response) {
                    nativeToast({
                        message: response.message,
                        position: 'top',
                    });

                    if(!response.error) {
                        setTimeout(function() {
                            location.href = response.redirect;
                        }, 800);
                    }
                },
                error : function(error) {

                    nativeToast({
                        message: 'Error the fields.',
                        position: 'top',
                    });

                    var jsonMessage = error.responseJSON.message;

                    if(jsonMessage.username != undefined) {
                        usernameInput.attr('class','form-control is-invalid');
                        usernameFeedback.html(jsonMessage.username.msg);
                    }

                    if(jsonMessage.email != undefined) {
                        emailInput.attr('class','form-control is-invalid');
                        emailFeedback.html(jsonMessage.email.msg);
                    }

                    if(jsonMessage.password != undefined) {
                        passwordInput.attr('class','form-control is-invalid');
                        passwordFeedback.html(jsonMessage.password.msg);
                    }

                }
            })
        }

2. Membuat Halaman Edit Dan Fungsinya

Tambahkan 2 objek rute lagi yang berada di dalam objek user

user : {
    index : dashboardPrefix + '/page/users',
    create : dashboardPrefix + '/page/users/create',
    store : dashboardPrefix + '/page/users/store',
    edit : dashboardPrefix + '/page/users/edit',
    update : dashboardPrefix + '/page/users/update'
}

Kemudian tambahkan 2 rute tersebut di dalam file web.js

.get(routePrefix.dashboards.pages.user.edit + '/:id', userController.edit)
.put(routePrefix.dashboards.pages.user.update + '/:id', [
    check('username','The username is required.').not().isEmpty(),
    check('email','The email is required.').not().isEmpty(),
    check('email','Invalid email format.').isEmail(),
], userController.update)

Lalu buat 2 method berikut di dalam file controller user seperti dibawah ini

exports.edit = function(req, res, next) {
    model.User.findOne({
        where: {
            id : req.params.id
        }
    }).then(callBack => 
        res.render('dashboard/user/edit', {
            title : 'Edit User',
            data : callBack,
            id : req.params.id
        })
    );
}

exports.update = function(req, res, next) {
    const errors = validationResult(req);

    if (!errors.isEmpty()) {
        return res.status(422).json({error : 1, message : errors.mapped() });
    }

    var updateUser = new Promise(function(resolve) {
        if(req.body.password != '') {
            var data = {
                username : req.body.username,
                email : req.body.email,
                password : crypto.createHmac('sha256', process.env.NODE_APP_KEY).update(req.body.password).digest('hex')
            }
        } else {
            var data = {
                username : req.body.username,
                email : req.body.email
            }
        }
        model.User.update(data, {
            where : {
                id : req.params.id
            }
        }).then(callback => {
            res.json({
                error   : false,
                message : "User was updated.",
                redirect : req.body.redirect,
            });
        });
    });

    updateUser.then(function(callBack) {
        res.json({
            error   : false,
            message : "User was updated.",
            redirect : req.body.redirect,
        });
    });
}

Setelah kita membuat fungsinya kita buat viewnya, buat file edit.pug, berikut source codenya

extends ../layout

block stylesheets
    //- Todo
block content

    .row
        .col-md-12
            .card
                .card-body
                    form.userForm
                        input(type="hidden" name="redirect" value=`${route.dashboards.pages.user.index}`)
                        .form-group.row
                            label.col-sm-2.col-form-label(for="username") Username
                            .col-sm-10
                                input(type="text" class="form-control" id="username" name="username" value=`${data.username}`)
                                <div class="invalid-feedback" id="username-feedback"></div>
                        .form-group.row
                            label.col-sm-2.col-form-label(for="email") Email
                            .col-sm-10
                                input(type="email" class="form-control" id="email" name="email" value=`${data.email}`)
                        .form-group.row
                            label.col-sm-2.col-form-label(for="password") Password
                            .col-sm-10
                                input(type="password" class="form-control" id="password" name="password")
                        .row
                            .col-sm-12
                                a.btn.btn-primary(href=`${ route.dashboards.pages.user.index }`) Back
                                .
                                    &nbsp;
                                button.btn.btn-primary(onclick="createUser()" type="button") Save
block scripts
    script.
        function createUser() {

            var usernameInput = jQuery('#username'),
                usernameFeedback = jQuery('#username-feedback');

            var emailInput = jQuery('#email'),
                emailFeedback = jQuery('#email-feedback');

            var passwordInput = jQuery('#password'),
                passwordFeedback = jQuery('#password-feedback');

            jQuery.ajax({
                url : '#{route.dashboards.pages.user.update}/#{id}',
                dataType : 'json',
                method : 'put',
                data : jQuery('.userForm').serialize(),
                beforeSend : function() {
                    usernameInput.attr('class','form-control');
                    usernameFeedback.html(``);

                    emailInput.attr('class','form-control');
                    emailFeedback.html(``);

                    passwordInput.attr('class','form-control');
                    passwordFeedback.html(``);
                },
                success : function(response) {
                    nativeToast({
                        message: response.message,
                        position: 'top',
                    });
                },
                error : function(error) {

                    nativeToast({
                        message: 'Error the fields.',
                        position: 'top',
                    });

                    var jsonMessage = error.responseJSON.message;

                    if(jsonMessage.username != undefined) {
                        usernameInput.attr('class','form-control is-invalid');
                        usernameFeedback.html(jsonMessage.username.msg);
                    }

                    if(jsonMessage.email != undefined) {
                        emailInput.attr('class','form-control is-invalid');
                        emailFeedback.html(jsonMessage.email.msg);
                    }

                    if(jsonMessage.password != undefined) {
                        passwordInput.attr('class','form-control is-invalid');
                        passwordFeedback.html(jsonMessage.password.msg);
                    }

                }
            })
        }

3. Membuat Fungsi Hapus Data

Tambahkan 1 objek rute delete di dalam objek user

user : {
    index : dashboardPrefix + '/page/users',
    create : dashboardPrefix + '/page/users/create',
    store : dashboardPrefix + '/page/users/store',
    edit : dashboardPrefix + '/page/users/edit',
    update : dashboardPrefix + '/page/users/update',
    destroy : dashboardPrefix + '/page/users/destroy'
}

Kemudian tambahkan 1 rute tersebut di dalam file web.js

.get(routePrefix.dashboards.pages.user.destroy + '/:id', userController.destroy)

Jika sudah membuat route tersebut selanjutnya tambahkan method di bawah ini ke dalam file user controller

exports.destroy = function(req, res, next) {
    model.User.destroy({
        where : {
            id : req.params.id
        }
    }).then(callback => {
        res.redirect(routePrefix.dashboards.pages.user.index);
    });
}