/mongo-db-rest-api-demo

My version of the CodeWorkr Express Mongdb REST API Series

Primary LanguageJavaScript

mongo-db-rest-api-demo

My version of the CodeWorkr Express MongoDB REST API Series.

Setup a MongoDB

  1. goto MLab and setup a databases called cars.
  2. create an admin user.

Step 1

  1. npm init -y
  2. yarn add express
  3. create app.js
  4. add .gitignore
  5. add .jshintrc

Step 2: Add .env

  1. npm install dotenv --save
  2. create .env
  3. I am not adding it to git repo, look at .env.sample

Step 3: Add Logger

Morgan : HTTP request logger middleware for node.js

  1. yarn add morgan
  2. add as middleware

app.use(logger('dev));

Step 4: Add 404 Handler

// Catch 440 Errors and forward them to an error handler 
app.use((req, res, next) => {
    const err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// Error handler function
app.use((err, req, res, next) => {
    const error = app.get('env') === 'development' ? err : {};
    const status = err.status || 500;

    // Respond to client
    res.status(status).json({
        error: {
            message: error.message
        }
    });

    // Respond to ourselves
    console.error(err);
});

Step 5: Add first route

  1. Add route
  2. Launch server
    • node app.js
  3. Launch Postman
    1. Create a New Collection Create a new Collection
    2. https://www.getpostman.com/collections/6b847ee739a8d9cf6c951
    3. Send Get Request Get Request
    4. Success!

Step 6. Create Folders

  1. Create helpers folders
  2. Create controllers folders
  3. Create models folders

Step 7. Install Nodemon

  1. yarn add nodemon
  2. add "start" command to package.json
  3. npm start

Step 8. Add Routes and Controllers

  1. create routes/user.js
  2. refactor app.js to use the user route module
  3. create controllers/user.js
  4. refactor routes/users.js to use the user controller module

Step 9. Mongoose

  1. yarn add mongoose
  2. We can interact with mongoose in 3 different ways:
    1. Callbacks
    2. Promises
    3. Async/Await (Promises)

Step 10. Add POST Route

  1. yarn npm body-parser
  2. add body-parser as Middleware
    • app.use(bodyParser.json());
  3. add users.post route
  4. add users.create_usrer controller
  5. In Postman, make sure to add Headers
    • Content-Type:application/json

Step 11. Added db/seed.js

  1. The seed-db function will populate the mongodb database with starting values.

Step 12. Convert to Promise

  1. Refactored controller/users.js to use a Promise

  2. Fixed depricated error in app.js

    • mongoose.Promise = global.Promise;

Step 13. Make nodemon a devdependency.

  1. yarn add --dev nodemon

Step 14. Convert to Async/Await

  1. Refactored controller/users.js to use Async/Await

Step 15. Install Express-Promise-Router

  1. yarn add express-promise-router

Making it Async

so... async/await doesn't actually make Node.js code synchronous. what it does do is allow you not have to write callbacks or Promise().then().catch() functions so it makes your code verbose

so it will queue up all the calls in order, but some the async processing will return before others depending on how quickly it is processed More links

also, updated example git with file write output

Step 16. Adding more routes

  1. extend routes in routes/users.js, controllers/users.js
  2. now we have a cars route
{
    "cars": [
        {
            "_id": "59e0d615fcdd4965849e4466",
            "seller": "59e011151dc47a3a34f79440",
            "make": "Ford",
            "model": "Flex",
            "year": 2017,
            "price": 39000,
            "__v": 0
        },
        {
            "_id": "59e0d64feed04e6e80cc7d4a",
            "seller": "59e011151dc47a3a34f79440",
            "make": "Ford",
            "model": "Flex",
            "year": 2017,
            "price": 39000,
            "__v": 0
        }
    ]
}

Step 17. Validation

  • express validator
  • joi
    • Object schema description language and validator for JavaScript objects.
    • npm install --save joi
  • validator
  • node validator
  • better validator
    • be simple to use
    • support a number of usage patterns including a fluent interface
    • support re-use of validator parts
    • support deep object and array validation
    • be able to customise the output structure
    • be able to customise failure messages
    • support i18n
    • use the well known validator library for string validation
    • be easily used with both express.js, koa.js and koa@next
    • written in and works with typescript (>= v2.0.0, see Section on Breaking Changes below)
  1. Go with Joi
  2. npm install --save joi