Terakhir diperbaharui: Oct 24, 2020
Refactoring
Refactoring yang akan kita lakukan meliputi:
- Menyederhanakan code yang digunakan untuk membuat koneksi ke MongoDB
- Memisahkan route & handler
Sharing Koneksi Database
Jika kita perhatikan pada code sebelumnya, proses koneksi ke MongoDB dilakukan di setiap handler. Hal ini membuat terjadi banyak duplicated code.
MongoDB driver sendiri sudah dilengkapi dengan mekanisme connection pooling, sehingga koneksi ke database hanya perlu dilakukan sekali.
Kita akan menggunakan object app.locals dari Express.js untuk menyimpan object collection.
Object app.locals memiliki properties yang bersifat local untuk aplikasi. Kita bisa anggap object ini seperti global object yang valuenya bisa diakses dimanapun selama masih di dalam aplikasi Express.js.
Step by Step
- Tambahkan code berikut sebelum route
1// Connect to Database23MongoClient.connect(url, (err, client) => {4 const db = client.db(dbName);5 const notesCollection = db.collection('notes');67 app.locals.notesCollection = notesCollection;8});
- Update semua routes
1const express = require('express');2const { MongoClient, ObjectId } = require('mongodb');3const bodyParser = require('body-parser');45const app = express();6const port = 3001;78// Connection URL9const url = 'mongodb://localhost:27017';10// Database Name11const dbName = 'dinotesDB';1213app.use(bodyParser.urlencoded({ extended: true }));1415// Connect to Database1617MongoClient.connect(url, (err, client) => {18 const db = client.db(dbName);19 const notesCollection = db.collection('notes');2021 app.locals.notesCollection = notesCollection;22});2324// Routes2526app.post('/note', (req, res) => {27 const { notesCollection } = req.app.locals;28 // Insert data to collection29 notesCollection.insertOne(req.body).then((result) => {30 console.log(result);31 });3233 res.status(200).json('Data successfully saved');34});3536app.get('/notes', (req, res) => {37 const { notesCollection } = req.app.locals;3839 // find All Notes40 notesCollection41 .find()42 .toArray()43 .then((result) => {44 res.status(200).json(result);45 });46});4748app.get('/note/:id', (req, res) => {49 const { notesCollection } = req.app.locals;5051 // find Notes based on id52 notesCollection.findOne({ _id: ObjectId(req.params.id) }).then((result) => {53 res.status(200).json(result);54 });55});5657app.put('/note/:id', (req, res) => {58 const { notesCollection } = req.app.locals;59 // update data collection60 notesCollection61 .updateOne({ _id: ObjectId(req.params.id) }, { $set: { title: req.body.title, note: req.body.note } })62 .then((result) => {63 console.log(result);64 });6566 res.status(200).json('Data successfully updated');67});6869app.delete('/note/:id', (req, res) => {70 const { notesCollection } = req.app.locals;7172 // delete data collection73 notesCollection.deleteOne({ _id: ObjectId(req.params.id) }).then((result) => {74 console.log(result);75 });7677 res.status(200).json('Data successfully deleted');78});7980app.listen(port, () => {81 console.log(`Server listening at http://localhost:${port}`);82});
Memutus Koneksi ke MongoDB
Kita tidak perlu mengatur (menyambungkan/memutus) koneksi ke MongoDB secara manual, hal ini sudah ditangani oleh MongoDB driver.
Jadi memutus koneksi ke MongoDB bisa dibilang tidak perlu dilakukan. Tapi jika kamu tetap ingin melakukannya kamu bisa update code server.js menjadi:
1...23// jadikan variable db menjadi global variable45let db;67MongoClient.connect(url, (err, client) => {8 db = client.db(dbName);9 const notesCollection = db.collection('notes');1011 app.locals.notesCollection = notesCollection;12});1314...1516// tambahkan code berikut ini pada baris akhir server.js1718process.on('SIGINT', () => {19 db.close();20 process.exit();21});
Memisahkan Route & Handler
Untuk memudahkan kita mengelola route, kita jadikan route yang ada menjadi sebuah module dengan cara memindahkannya dari api/server.js ke file terpisah.
Step by step
- Buat sebuah file baru bernama route.js di dalam folder api
Struktur folder:
1dinotes-app2 |--api3 |--routes.js4 |--server.js5 |--node_modules6 |--public7 |--src
Kita akan tambahkan express.Router, route handler yang digunakan untuk mengatur route di sebuah aplikasi Express.js.
- Pindahkan semua route ke dari api/server.js ke api/routes.js kemudian ganti app dengan router:
1const express = require('express');2const { ObjectId } = require('mongodb');34const router = express.Router();56router.post('/note', (req, res) => {7 const { notesCollection } = req.app.locals;8 // Insert data to collection9 notesCollection.insertOne(req.body).then((result) => {10 console.log(result);11 });1213 res.status(200).json('Data successfully saved');14});1516router.get('/notes', (req, res) => {17 const { notesCollection } = req.app.locals;1819 // find All Notes20 notesCollection21 .find()22 .toArray()23 .then((result) => {24 res.status(200).json(result);25 });26});2728router.get('/note/:id', (req, res) => {29 const { notesCollection } = req.app.locals;3031 // find Notes based on id32 notesCollection.findOne({ _id: ObjectId(req.params.id) }).then((result) => {33 res.status(200).json(result);34 });35});3637router.put('/note/:id', (req, res) => {38 const { notesCollection } = req.app.locals;39 // update data collection40 notesCollection41 .updateOne({ _id: ObjectId(req.params.id) }, { $set: { title: req.body.title, note: req.body.note } })42 .then((result) => {43 console.log(result);44 });4546 res.status(200).json('Data successfully updated');47});4849router.delete('/note/:id', (req, res) => {50 const { notesCollection } = req.app.locals;5152 // delete data collection53 notesCollection.deleteOne({ _id: ObjectId(req.params.id) }).then((result) => {54 console.log(result);55 });5657 res.status(200).json('Data successfully deleted');58});5960module.exports = router;
- Import module routes ke file server.js
1const express = require('express');2const { MongoClient } = require('mongodb');3const bodyParser = require('body-parser');45const routes = require('./routes');67const app = express();8const port = 3001;910// Connection URL11const url = 'mongodb://localhost:27017';12// Database Name13const dbName = 'dinotesDB';1415app.use(bodyParser.urlencoded({ extended: true }));1617// Connect to Database1819MongoClient.connect(url, (err, client) => {20 const db = client.db(dbName);21 const notesCollection = db.collection('notes');2223 app.locals.notesCollection = notesCollection;24});2526// Routes2728app.use('/', routes);2930app.listen(port, () => {31 console.log(`Server listening at http://localhost:${port}`);32});
Sekarang kita pindahkan semua route handler ke file api/handler.js.
Buat sebuah file bernama handler.js di dalam folder api.
Kemudian pindahkan semua route handler ke file api/handler.js
1/* eslint-disable no-console */2const { ObjectId } = require('mongodb');34exports.addNote = (req, res) => {5 const { notesCollection } = req.app.locals;6 // Insert data to collection7 notesCollection.insertOne(req.body).then((result) => {8 console.log(result);9 });1011 res.status(200).json('Data successfully saved');12};1314exports.getAllNotes = (req, res) => {15 const { notesCollection } = req.app.locals;1617 // find All Notes18 notesCollection19 .find()20 .toArray()21 .then((result) => {22 res.status(200).json(result);23 });24};2526exports.getNote = (req, res) => {27 const { notesCollection } = req.app.locals;2829 // find Notes based on id30 notesCollection.findOne({ _id: ObjectId(req.params.id) }).then((result) => {31 res.status(200).json(result);32 });33};3435exports.updateNote = (req, res) => {36 const { notesCollection } = req.app.locals;37 // update data collection38 notesCollection39 .updateOne({ _id: ObjectId(req.params.id) }, { $set: { title: req.body.title, note: req.body.note } })40 .then((result) => {41 console.log(result);42 });4344 res.status(200).json('Data successfully updated');45};4647exports.deleteNote = (req, res) => {48 const { notesCollection } = req.app.locals;4950 // delete data collection51 notesCollection.deleteOne({ _id: ObjectId(req.params.id) }).then((result) => {52 console.log(result);53 });5455 res.status(200).json('Data successfully deleted');56};
- Update api/routes.js:
1const express = require('express');23const router = express.Router();45const { addNote, getAllNotes, getNote, updateNote, deleteNote } = require('./handler');67router.post('/note', addNote);8router.get('/notes', getAllNotes);9router.get('/note/:id', getNote);10router.put('/note/:id', updateNote);11router.delete('/note/:id', deleteNote);1213module.exports = router;
Sekarang kita memiliki tiga file yang memiliki tugasnya masing-masing:
- handler.js, mengatur semua route handler
- routes.js, mengatur semua route
- server.js, file utama dari server yang bertugas untuk load middleware, module, mengatur koneksi ke database dan menjalankan http server