< Back

Backend: express app

We will create a very simple REST API with express

npm install -g express-generator
express backend
cd backend
yarn

Then let's try the app

$ yarn start
> **yarn start v0.21.3**
> $ node ./bin/www

And head over to http://localhost:3000/ You should see a page that says Express: Welcome to Express

Lets add babel to use ecmascripts new syntax :)

yarn add -D babel-cli babel-preset-es2015 babel-preset-stage-0 babel-plugin-transform-runtime
vi .babelrc

Add the following content

{
  "presets": ["es2015", "stage-0"],
  "plugins": [
    ["transform-runtime", {
      "polyfill": false,
      "regenerator": true
    }]
  ]
}

And edit the package.json file to change the start script so it will use babel instead of node.

    "start": "babel-node ./bin/www"

Try yarn start agains if you like, it should work as before.

Now lets install mongoose dependency

yarn add mongoose

And create a User model

mkdir models
vi models/User.js

Include the following in User.js file

import mongoose from 'mongoose'
const Schema = mongoose.Schema

const schema = Schema({
  created_at: { type: Date, default: Date.now },
  name: { type: String, unique: true, required: true },
  roles: [ { type: String, enum: ['DEV', 'ADMIN'] }]
})
const User = mongoose.model('User', schema)
export default User

Now we will update routes/users.js so that it retrieves the list of users from mongo

import express from 'express'
import mongoose from 'mongoose'
import User from '../models/User'

const router = express.Router()

/* GET users listing. */
router.get('/', async (req, res) => {
  const users = await User.find()
  res.send(users)
})

module.exports = router;

To use promises (and async fn) we need to install

yarn add express-promise

And now we need to edit app.js to include this library and also to connect to mongoose

Just right after the line var app = express() add the following

// promises and mongoose
app.use(require('express-promise')())

import mongoose from 'mongoose'
mongoose.connect(process.env.MONGO_URL || 'mongodb://localhost/docker-e2e')

Notice that this will take the mongo connection URL from an env variable or default to a hardcoded value. This will be useful later since we will need to coordinate how this module connects to a "real" mongo (?)

Now yarn start again and go to http://localhost:3000/users You should just see [] since we don't have any users in mongo.

Lets create some manually

mongo docker-e2e

db.users.insert({ name: 'Socrates', created_at: new Date() })
db.users.insert({ name: 'Platon', created_at: new Date() })
db.users.insert({ name: 'Aristoteles', created_at: new Date() })

Restart the app yarn start and go again to http://localhost:3000/users You should now see

[ 
  {
     "_id": "590df1740b0a7bf7cf0cc4f3",
     "name": "Socrates",
     "roles": [],
     "created_at": "2017-05-06T15:53:24.060Z"
  },
  {
     "_id": "590df1b00b0a7bf7cf0cc4f4",
     "name": "Platon",
     "roles": [],
     "created_at": "2017-05-06T15:54:24.652Z"
  },
 {
    "_id": "590df1b50b0a7bf7cf0cc4f5",
    "name": "Aristoteles",
    "roles": [],
    "created_at": "2017-05-06T15:54:29.884Z"
  }
]

That's it, we are ready for the backend part

< Back | Next >

results matching ""

    No results matching ""