mohamed adel
mohamed adel

Reputation: 715

NodeJS APIs folder structure

I am going to have multiple APIs in routes folder should I put them in in the same file API or separate them?

├── app.js
├── src/
│   ├── contants/
│   ├── helpers/
│   ├── models/
│   ├── routes/
|   |         |___index.js
              |___api.js
│   └── libs/
│       ├── backbone/
│       ├── underscore/
│       └── ...
api.js file contains all the APIs
    const jwt = require("jsonwebtoken")
    const axios = require("axios")
    require("express-async-errors")
    const bodyParser = require("body-parser")
    const fs = require("fs")

    const LOLTrackingSystem = require("../methods/onlineGamesTracking/LOLTracking")
    const getUserData = require("../methods/leagueOfLegends/getUserData")
    const isAuthenticated = require("../helpers/authenticated")

    const apiRoute = (api) => {
      api.use(bodyParser.json())
      api.use(bodyParser.urlencoded({
        extended: false
      }));

      api.post("/api/auth", (req, res) => {
        //API Functions
      })

      api.post("/api/gizmo/memberProfile", isAuthenticated, (req, res) => {
        //API Functions
      })

      api.post("/api/gizmo/memberState/:userId/:host/:state", async (req, res) => {
        //API Functions
      })
    }

    module.exports = apiRoute

Is what I am doing is right?

If it's wrong what is the right way to do it?

Upvotes: 1

Views: 1076

Answers (1)

programmerRaj
programmerRaj

Reputation: 2058

It really depends on your personal preferences.

If you prefer having all of the functions in one file, that's okay. One good thing about doing this is that you don t have to keep track of requiring other files.

What I think you should think about is how related the API'S are to each other, how many different functions you have, and the length of the functions. If you don't have many functions then you should keep them all in one file. However if you have many big, independent api's then it can be more organized keeping them in separate files.

In the end, there is not right or wrong answer. You decide based on your style, and if you wanted advice and opinions there are plenty in the comments. Good luck.

Upvotes: 1

Related Questions