Wednesday, July 10, 2019

Express : CRUD Application by express

$ mkdir movies-app
$ cd movies-app
$ mkdir server
$ cd server
$ yarn initor$ npm init -y
$ ls
package.json
$ yarn add express body-parser cors mongoose nodemonor$ npm install express body-parser cors mongoose nodemon
  • Body Parser: Responsible to get the body off of network request.
  • Nodemon: Restart the server when it sees changes (for a better dev experience).
  • Cors: Package for providing a Connect/Express middleware that can be used to enable CORS with various options.
  • Mongoose: It's an elegant MongoDB object modeling for node.js
$ls
node_modules package.json yarn.lock
$ node index.js
Node JS application running

1.1. Installing MongoDB

For now, we need to install MongoDB. For this, just type on your terminal:
$ brew install mongodb
$ mkdir -p /data/db
$ brew services start mongodb
$ mongo
> use cinema
$ mkdir db
$ touch index.js
Updating the main file server/index.js we have something like this.
If you take a look at your terminal, you see that nothing changed. This is because when you type node index.js that means node keeps the last set up before it started. If you’d like to restart the application you need to close and open a new one. However, at the beginning of this tutorial, I told you about nodemon, it’s going to restart the server every time when it sees changes in any file of our project. From, now let’s do this.$ nodemon index.js

1.1.1. Creating Movie’s Schema

As we’ve said, we need to create an entity called movies that should be composed of the movies of a cinema. For this, we just need to know the name of the movie and the times the movie is passing on the cinema, and to add an important, but not necessary information, the rating.
$ mkdir models
$ cd models
$ touch movie-model.js

1.2. Creating routes

Here, we’ll create all the CRUD operations and create our REST endpoints. Let’s create two more folders on the server: routes and controllers. In the route folder, let’s create the file movie-router.js and in the controller folder, movie-ctrl.js.
$ mkdir routes controllers
$ touch routes/movie-router.js
$ touch controllers/movie-ctrl.js

1.3. Testing manually our application

To test our application I’d like to introduce two more tools: Postman and Robo 3T. These tools will help us in verify our application working (I won’t explain how to install because it’s easy and you can find this in their own websites).
{
    "name": "Avengers: Endgame",
    "time": ["14:15", "16:00", "21:30", "23:00"],
    "rating": 8.8
}

No comments:

Post a Comment