Artikel ini akan membahas contoh pembuatan REST API menggunakan Express.js, Mongoose dan Babel. Resource atau endpoint yang dibuat adalah users. Kita hanya akan membuat metode pendaftaran user sederhana. Kita akan menggunakan pola repository.

  1. Install paket yang dibutuhkan:
yarn add express mongoose mongodb
yarn add --dev @babel/cli @babel/core @babel/node @babel/preset-env nodemon

2. Buat struktur folder

.
├── package.json
├── src
│   ├── controllers
│   │   └── UserController.js
│   ├── index.js
│   ├── models
│   │   ├── repositories
│   │   │   └── UserRepository.js
│   │   └── User.js
│   └── routes
│       ├── index.js
│       └── users.js
└── yarn.lock

5 directories, 8 files

3. User Model User.js

import mongoose from 'mongoose';

const { Schema } = mongoose;

const schema = new Schema({
  email: {
    type: String
  },
  password: {
    type: String
  }
});

const User = mongoose.model('User', schema);
export default User;

4. User Repository UserRepository.js

Buat folder repositories di dalam folder models, kemudian buat UserRepository.js

import User from '../User';

class UserRepository {

  constructor(model) {
    this.model = model;
  }

  create(object) {
    return this.model.create(object);
  }
}

export default new UserRepository(User);

Lalu buat UserController.js di folder controllers.

5. User Controller UserController.js

import UserRepository from '../models/repositories/UserRepository';

function createUser(req, res) {
  const user = req.body;

  UserRepository.create(user)
    .then((newUser) => {
      res.json(newUser);
    }).catch((errors) => {
      res.status(500).json({
        errors,
      });
    });
}

export default { createUser };

Setelah itu kita daftarkan rutenya di folder routes /users.js

6. User Route users.js

import express from 'express';
import UserController from '../controllers/UserController';

const router = express.Router();

router.post('/', UserController.createUser);

export default router;

Dan index.js dalam routes

import express from 'express';
import users from './users';

const router = express.Router();

router.use(express.json());

router.use('/users', users);

export default router;

Terakhir kita buat index.js di dalam src

7. Server Aplikasi index.js

import express from 'express';
import mongoose from 'mongoose';

import routes from './routes';

mongoose.Promise = global.Promise;

const app = express();

app.use('/', routes);

mongoose.connect('mongodb://localhost:27017/db')
  .then(() => {
    console.log('mongodb started.');
    app.listen(8000, () => {
      console.log('Server started on 8000');
    });
  }).catch(() => {
    console.log('Mongodb connection failed.');
  })

8. Perintah untuk menjalankan server

nodemon -w src -x "babel-node src --presets @babel/env"

Kita bisa menambahkannya ke dalam npm-scripts di package.json

{
  "name": "exercise",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "dependencies": {
    "express": "^4.17.1",
    "mongodb": "^3.2.7",
    "mongoose": "^5.6.2",
    "nodemon": "^1.19.1"
  },
  "devDependencies": {
    "@babel/cli": "^7.4.4",
    "@babel/core": "^7.4.5",
    "@babel/node": "^7.4.5",
    "@babel/preset-env": "^7.4.5"
  },
  "scripts": {
    "start": "nodemon -w src -x \"babel-node src --presets @babel/env\""
  }
}

Itu tadi latihan express.js, mongoose dan babel menggunakan REST API sederhana.

Keseluruhan kode bisa dilihat di https://github.com/yoiso/exercise-express