Menggunakan Method Route

Pada modul ini kita akan memperbaiki struktur program agar lebih mudah dibaca dan dimaintenance.

  1. Refactoring dengan menggunakan named function untuk callback dari masing-masing route.
  2. Menggabungkan endpoint route dengan method app.route.

Refactoring

Kita akan beri satu contoh menggunakan named function untuk method get all tours. Buat fungsi dengan nama getAllTours, yang isinya dari callback pada fungsi app.get(‘/api/v1/tours/, …….);

//sebelum refactoring
app.get('/api/v1/tours', (req, res) => {
    res.status(200).json({
        status: 'success',
        results: tours.length ,
        data: {
            tours: tours
        }
    });
});


//sesudah refactoring
const getAllTours = (req, res) => {
    res.status(200).json({
        status: 'success',
        results: tours.length ,
        data: {
            tours: tours
        }
    });
}

app.get('/api/v1/tours', getAllTours);

Berikut kode akhir setelah refactoring

const fs = require('fs');
const express = require('express');

const app = express();

app.use(express.json());

const tours = JSON.parse(fs.readFileSync(`${__dirname}/devdata/tours-simple.json`));

const getAllTours = (req, res) => {
    res.status(200).json({
        status: 'success',
        results: tours.length ,
        data: {
            tours: tours
        }
    });
}

const getTours = (req, res) => {
    const id = req.params.id * 1;
    const tour = tours.find(el => el.id === id);

    if(!tour){
        res.status(404).json({
            status: 'fail',
            message: 'invalid ID'
        });
    }else{
        res.status(200).json({
            status: 'success',
            data: {
                tour: tour
            }
        });
    }

}

const createTour = (req, res) => {
    const newId = tours[tours.length-1].id + 1;
    const newTour = Object.assign({id: newId}, req.body);

    tours.push(newTour);
    fs.writeFile(`${__dirname}/devdata/tours-simple.json`, JSON.stringify(tours), err=>{
        res.status(201).json({
            status: 'success',
            data: {
                tour: newTour
            }
        });
    });
}


const updateTour = (req, res)=> {
    // do validation

    //return to client
    res.status(201).json({
        status: 'success',
        data: {
            tour: 'data updated'
        }
    });
}

const deleteTour = (req, res)=> {
    // do validation

    //return to client
    res.status(204).json({
        status: 'success',
        data: null
    });
}

app.get('/api/v1/tours', getAllTours);
app.get('/api/v1/tours/:id', getTours);
app.post('/api/v1/tours', createTour);
app.patch('/api/v1/tours/:id', updateTour);
app.delete('/api/v1/tours/:id', deleteTour);


const port = 3000;
app.listen(port, ()=>{
    console.log(`Listening on port ${port}...`);
});

Menggunakan method route

Method route digunakan untuk menggabungkan end point url yang sama dan melakukan chaining method. Agar lebih jelas apa yang dimaksud chaining, langsung saja lihat kode dibawah.

Untuk contoh kita akan gabungkan route ‘/api/v1/tours/’ untuk get dan post.

app.route('/api/v1/tours').get(getAllTours).post(createTour);

Berikut kode akhir setelah route digabungkan

const fs = require('fs');
const express = require('express');

const app = express();

app.use(express.json());

const tours = JSON.parse(fs.readFileSync(`${__dirname}/devdata/tours-simple.json`));

const getAllTours = (req, res) => {
    res.status(200).json({
        status: 'success',
        results: tours.length ,
        data: {
            tours: tours
        }
    });
}

const getTours = (req, res) => {
    const id = req.params.id * 1;
    const tour = tours.find(el => el.id === id);

    if(!tour){
        res.status(404).json({
            status: 'fail',
            message: 'invalid ID'
        });
    }else{
        res.status(200).json({
            status: 'success',
            data: {
                tour: tour
            }
        });
    }

}

const createTour = (req, res) => {
    const newId = tours[tours.length-1].id + 1;
    const newTour = Object.assign({id: newId}, req.body);

    tours.push(newTour);
    fs.writeFile(`${__dirname}/devdata/tours-simple.json`, JSON.stringify(tours), err=>{
        res.status(201).json({
            status: 'success',
            data: {
                tour: newTour
            }
        });
    });
}


const updateTour = (req, res)=> {
    // do validation

    //return to client
    res.status(201).json({
        status: 'success',
        data: {
            tour: 'data updated'
        }
    });
}

const deleteTour = (req, res)=> {
    // do validation

    //return to client
    res.status(204).json({
        status: 'success',
        data: null
    });
}

app.route('/api/v1/tours').get(getAllTours).post(createTour);
app.route('/api/v1/tours/:id').get(getTours).patch(updateTour).delete(deleteTour);

const port = 3000;
app.listen(port, ()=>{
    console.log(`Listening on port ${port}...`);
});

Sampai disini, program pada app.js lebih mudah dibaca dan dimaintenance. Pada modul lainnya kita akan lakukan file structuring agar kode lebih mudah dimaintenance.

Sharing is caring:

Leave a Comment