Giter Site home page Giter Site logo

maitraysuthar / rest-api-nodejs-mongodb Goto Github PK

View Code? Open in Web Editor NEW
1.1K 22.0 417.0 667 KB

A boilerplate for REST API Development with Node.js, Express, and MongoDB

License: MIT License

JavaScript 96.73% HTML 0.98% CSS 0.35% Shell 1.94%
nodejs express expressjs mongodb rest-api rest api javascript jwt-authentication token-based-authentication

rest-api-nodejs-mongodb's Introduction

Nodejs Expressjs MongoDB Ready-to-use API Project Structure

Author GitHub license GitHub repo size Codacy Badge Codacy Badge Travis (.com)

A ready-to-use boilerplate for REST API Development with Node.js, Express, and MongoDB

Getting started

This is a basic API skeleton written in JavaScript ES2015. Very useful to building a RESTful web APIs for your front-end platforms like Android, iOS or JavaScript frameworks (Angular, Reactjs, etc).

This project will run on NodeJs using MongoDB as database. I had tried to maintain the code structure easy as any beginner can also adopt the flow and start building an API. Project is open for suggestions, Bug reports and pull requests.

Advertise for Job/Work Contract

I am open for a good job or work contract. You can contact me directly on my email ([email protected]) or you can download my CV from my personal website.

Buy me a Coffee

If you consider my project as helpful stuff, You can appreciate me or my hard work and time spent to create this helpful structure with buying me a coffee.

Buy Me A Coffee

Features

  • Basic Authentication (Register/Login with hashed password)
  • Account confirmation with 4 (Changeable) digit OTP.
  • Email helper ready just import and use.
  • JWT Tokens, make requests with a token after login with Authorization header with value Bearer yourToken where yourToken will be returned in Login response.
  • Pre-defined response structures with proper status codes.
  • Included CORS.
  • Book example with CRUD operations.
  • Validations added.
  • Included API collection for Postman.
  • Light-weight project.
  • Test cases with Mocha and Chai.
  • Code coverage with Istanbuljs (nyc).
  • Included CI (Continuous Integration) with Travis CI.
  • Linting with Eslint.

Software Requirements

  • Node.js 8+
  • MongoDB 3.6+ (Recommended 4+)

How to install

Using Git (recommended)

  1. Clone the project from github. Change "myproject" to your project name.
git clone https://github.com/maitraysuthar/rest-api-nodejs-mongodb.git ./myproject

Using manual download ZIP

  1. Download repository
  2. Uncompress to your desired directory

Install npm dependencies after installing (Git or manual download)

cd myproject
npm install

Setting up environments

  1. You will find a file named .env.example on root directory of project.
  2. Create a new file by copying and pasting the file and then renaming it to just .env
    cp .env.example .env
  3. The file .env is already ignored, so you never commit your credentials.
  4. Change the values of the file to your environment. Helpful comments added to .env.example file to understand the constants.

Project structure

.
├── app.js
├── package.json
├── bin
│   └── www
├── controllers
│   ├── AuthController.js
│   └── BookController.js
├── models
│   ├── BookModel.js
│   └── UserModel.js
├── routes
│   ├── api.js
│   ├── auth.js
│   └── book.js
├── middlewares
│   ├── jwt.js
├── helpers
│   ├── apiResponse.js
│   ├── constants.js
│   ├── mailer.js
│   └── utility.js
├── test
│   ├── testConfig.js
│   ├── auth.js
│   └── book.js
└── public
    ├── index.html
    └── stylesheets
        └── style.css

How to run

Running API server locally

npm run dev

You will know server is running by checking the output of the command npm run dev

Connected to mongodb:YOUR_DB_CONNECTION_STRING
App is running ...

Press CTRL + C to stop the process.

Note: YOUR_DB_CONNECTION_STRING will be your MongoDB connection string.

Creating new models

If you need to add more models to the project just create a new file in /models/ and use them in the controllers.

Creating new routes

If you need to add more routes to the project just create a new file in /routes/ and add it in /routes/api.js it will be loaded dynamically.

Creating new controllers

If you need to add more controllers to the project just create a new file in /controllers/ and use them in the routes.

Tests

Running Test Cases

npm test

You can set custom command for test at package.json file inside scripts property. You can also change timeout for each assertion with --timeout parameter of mocha command.

Creating new tests

If you need to add more test cases to the project just create a new file in /test/ and run the command.

ESLint

Running Eslint

npm run lint

You can set custom rules for eslint in .eslintrc.json file, Added at project root.

Bugs or improvements

Every project needs improvements, Feel free to report any bugs or improvements. Pull requests are always welcome.

License

This project is open-sourced software licensed under the MIT License. See the LICENSE file for more information.

rest-api-nodejs-mongodb's People

Contributors

gitads avatar maitraysuthar avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

rest-api-nodejs-mongodb's Issues

Internal APIs not working

Hi the APIs are not functional.

I setup the .env with mongoDB details and skipped SMTP. But anyhow the functionalities not dependent on SMTP were also breaking when I ran npm test

Please suggest.

RPC instead of REST

How about using RPC?

For example, I developed an RPC implementation for Node.js Wildcard API.

I'd be curious to know what you think about using RPC instead of REST.

[Suggestion]

I guess adding the tests also a plus point in the provided structure?

Form Data

I am sending form data but it didn't get it from server side,

Cannot post array

This is my post request with body as application/json format from postman

`{"title": "test",
        "date": "March 12 12 pm",
       
        
        "status": "Ongoing",
       
		"users": ["1","2"]
}`

But in nodejs when i try to retrieve req.body users am getting only 1 as output but not whole array.

endpoints?

i have successfully installed and started the server, and maybe i missed something somewhere, but how do i actually access the api? i load localhost:3000 and it shows the title and byline that should come up, but what do i add to the url to actually get json back?

Refactor If Statements.

We can refactor these if statements with Guard Clauses

if (!errors.isEmpty()) {
return apiResponse.validationErrorWithData(res, "Validation Error.", errors.array());
}else {
UserModel.findOne({email : req.body.email}).then(user => {
if (user) {
//Compare given password with db's hash.
bcrypt.compare(req.body.password,user.password,function (err,same) {
if(same){
//Check account confirmation.
if(user.isConfirmed){
// Check User's account active or not.
if(user.status) {
let userData = {
_id: user._id,
firstName: user.firstName,
lastName: user.lastName,
email: user.email,
};
//Prepare JWT token for authentication
const jwtPayload = userData;
const jwtData = {
expiresIn: process.env.JWT_TIMEOUT_DURATION,
};
const secret = process.env.JWT_SECRET;
//Generated JWT token with Payload and secret.
userData.token = jwt.sign(jwtPayload, secret, jwtData);
return apiResponse.successResponseWithData(res,"Login Success.", userData);
}else {
return apiResponse.unauthorizedResponse(res, "Account is not active. Please contact admin.");
}
}else{
return apiResponse.unauthorizedResponse(res, "Account is not confirmed. Please confirm your account.");
}
}else{
return apiResponse.unauthorizedResponse(res, "Email or Password wrong.");
}
});
}else{
return apiResponse.unauthorizedResponse(res, "Email or Password wrong.");
}
});
}
} catch (err) {
return apiResponse.ErrorResponse(res, err);
}
}];

Starting out for beginners

Hello!

I'm new to mongo, and I really appreciate the help getting my API started.
I did an npm i, then set my mongo url, and started my mongo service, then ran npm test, but I'm having some "connection refused" errors. Do I have to manually create the databases in mongo?

Thanks

Does not work with Google SMTP

Hi,

I have enabled SMTP on GMAIL and trying to use this code but getting this error while using the following API
http://localhost:3000/api/auth/register

Error: Invalid login: 535-5.7.8 Username and Password not accepted. Learn more at
535 5.7.8  https://support.google.com/mail/?p=BadCredentials c4-c35345.73 - gsmtp 
{
    "status": 0,
    "message": {
        "code": "EAUTH",
        "response": "535-5.7.8 Username and Password not accepted. Learn more at\n535 5.7.8  https://support.google.com/mail/?p=BadCredentials b29-c34543- gsmtp",
        "responseCode": 535,
        "command": "AUTH PLAIN"
    }
}
EMAIL_SMTP_HOST=smtp.gmail.com
EMAIL_SMTP_PORT=465
EMAIL_SMTP_USERNAME=tried both email id and only account name
EMAIL_SMTP_PASSWORD=password goes here
# true for 465, false for other ports
EMAIL_SMTP_SECURE=true

Any idea on how to fix this.

Getting error Error: Cannot find module 'bcrypt'

2021-07-19T09_57_53_633Z-debug.log

I have checked package json file but bcrypt package already available

Error: Cannot find module 'bcrypt'
Require stack:

  • E:\angular\kanhashoft\Node-With-Mongo\test\myproject\controllers\AuthController.js
  • E:\angular\kanhashoft\Node-With-Mongo\test\myproject\routes\auth.js
  • E:\angular\kanhashoft\Node-With-Mongo\test\myproject\routes\api.js
  • E:\angular\kanhashoft\Node-With-Mongo\test\myproject\app.js
  • E:\angular\kanhashoft\Node-With-Mongo\test\myproject\bin\www
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:902:15)
    at Function.Module._load (internal/modules/cjs/loader.js:746:27)
    at Module.require (internal/modules/cjs/loader.js:974:19)
    at require (internal/modules/cjs/helpers.js:92:18)
    at Object. (E:\angular\kanhashoft\Node-With-Mongo\test\myproject\controllers\AuthController.js:7:16)
    at Module._compile (internal/modules/cjs/loader.js:1085:14)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
    at Module.load (internal/modules/cjs/loader.js:950:32)
    at Function.Module._load (internal/modules/cjs/loader.js:790:14)
    at Module.require (internal/modules/cjs/loader.js:974:19)
    at require (internal/modules/cjs/helpers.js:92:18)
    at Object. (E:\angular\kanhashoft\Node-With-Mongo\test\myproject\routes\auth.js:2:24)
    at Module._compile (internal/modules/cjs/loader.js:1085:14)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
    at Module.load (internal/modules/cjs/loader.js:950:32)
    at Function.Module._load (internal/modules/cjs/loader.js:790:14) {
    code: 'MODULE_NOT_FOUND',
    requireStack: [
    'E:\angular\kanhashoft\Node-With-Mongo\test\myproject\controllers\AuthController.js',
    'E:\angular\kanhashoft\Node-With-Mongo\test\myproject\routes\auth.js',
    'E:\angular\kanhashoft\Node-With-Mongo\test\myproject\routes\api.js',
    'E:\angular\kanhashoft\Node-With-Mongo\test\myproject\app.js',
    'E:\angular\kanhashoft\Node-With-Mongo\test\myproject\bin\www'
    ]
    }

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.