Giter VIP home page Giter VIP logo

node-mongoose-setup's Introduction

REST API Setup Nodejs MongoDB

example workflow name Build Status Maintainability FOSSA Status PRs Welcome GitHub issues GitHub stars Twitter

Installation

Setup is super easy. Clone the repository -

git clone https://github.com/sunilksamanta/node-mongoose-setup
cd node-mongoose-setup
npm install

Create an .env file at the root of your project with the following.

MONGO_URL=YOUR_MONGO_URL
PORT=5000[YOUR_DESIRED_PORT]
NODE_ENV=YOUR_APP_ENVIRONMENT[production/development]
JWT_SECRET=YOUR_JWT_SECRET_STRING

An example file .env.example is included.

Your project is ready. Now start the project.

npm start

Go to http://localhost:5000. You should see a default welcome page.

Your API base path is http://localhost:5000/api.

First create some accounts to get started with the authentication.

Authentication

JWT authentication is added in this project. User model is defined in models/User.js. For Register, Login, Logout use these urls —

    [POST] api/auth/register
    [POST] api/auth/login
    [GET] api/auth/logout

Features

  1. Controller, Model & Service oriented architecture

  2. Auth with JWT & Db Store

  3. Async/Await support

  4. User Module

  5. Post Module (Sample CRUD)

  6. Media Upload

  7. Centralized Http Response

  8. Error Handler

  9. .env support

  10. Multi Environment config setup

  11. Autobind Methods

  12. Built in Pagination

Directory Structure of the Project

├─ .env
├─ .gitignore
├─ config
│  ├─ config.js
│  ├─ database.js
│  ├─ routes.js
│  └─ server.js
├─ index.js
├─ package.json
├─ system
└─ src
  ├─ controllers
  │  ├─ AuthController.js
  │  ├─ MediaController.js
  │  └─ PostController.js
  ├─ helpers
  ├─ models
  │  ├─ Auth.js
  │  ├─ Media.js
  │  ├─ Post.js
  │  └─ User.js
  ├─ routes
  │  ├─ auth.js
  │  ├─ media.js
  │  └─ post.js
  └─ services
     ├─ AuthService.js
     ├─ MediaService.js
     ├─ PostService.js
     └─ UserService.js

Lets talk about the structure

We have 2 base classes — One for Controller and another for Service.

  1. Controller.js

This base controller have the basic CRUD operations. To create a new controller just extend this base Controller class.

  1. Service.js

This is the base Service class which includes the database operations. If you want to change the default behaviour of the services you can update this file.

How to Create new CRUD Module?

If you want to create a new Module say Post. Then you’ll have to create 4 basic files. One Controller, one Service, one Model and one route file. And add the new route in routes/index.js with desired url. There is a “Post” CRUD module included in this project for example.

    controllers/PostController.js
    models/Post.js
    services/PostService.js
    routes/post.js

Overriding Base class method

As an example if you see in the media Controller — the default delete method is overriden by its own class method as we have to delete the file from the file system also. So the overriden method is like bellow —

async delete(req, res, next) {
  const { id } = req.params;
  try {
      const response = await this.service.delete(id);
      // File Unlinking..
      if (response.data.path) {
          console.log("unlink item", response.data.path);
          fs.unlink(response.data.path, function (err) {
              if (err) {
                  console.log("error deleting file");
                  throw err;
              }
              console.log("File deleted!");
          });
      }
      return res.status(response.statusCode).json(response);
  }
  catch (e) {
      next(e);
  }
}

Have questions or suggestions?

You can reply to this article REST API Structure using NodeJS MongoDB (Mongoose)

Want to contribute?

If you have any suggestion, feedback or you want to make this project more powerful — feel free to report issues or request a feature or suggest some changes.

Read the Contributing guideline.

License

This project is licensed under the terms of the MIT license.

FOSSA Status

Credit

Special thanks to @thisk8brd for the concept of this API Structure.

node-mongoose-setup's People

Contributors

dependabot[bot] avatar finefilm avatar fossabot avatar sunilksamanta avatar

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.