Skip to content

ajibadeabd/ExclusiveJs

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

22 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Sure, I can help you generate a README file for your package. Here is a template you can use:

ExclusiveJs

ExclusiveJs is a Node.js library that allows you to automatically generate routes for your Express.js application based on the file structure of your project.

Installation

You can install ExclusiveJs using npm:

npm install exclusivejs

Usage

To use ExclusiveJs, simply require the package in your Node.js application and call the init function, Here is an example:

const ExclusiveJs = require('exclusivejs').instance();

ExclusiveJs.setRoutePath("src/routes") // set the path to your routes folder .setApiPrefix("api") // set the prefix for your API routes .setDebugger(true) // enable debugging

.setRoutePath("src/app/routes") // set route path// default route path is src/routes

.connectDocumentation( "/api-docs",swaggerUi.serve,swaggerUi.setup(swaggerDocument) //swagger document ) // serve documentation

.injectPackages() // inject your installed packages

.setValidator({}) // set your validator

ExclusiveJs.init();

This will automatically generate routes for your Express.js app based on the file structure of your src/routes folder.

Options

ExclusiveJs provides several options that you can use to configure how your routes are generated:

setRoutePath(path)

Sets the path to your routes folder. Default value is src/routes.

setApiPrefix(prefix)

Sets the prefix for your API routes. Default value is api.

setDebugger(debug)

Enables or disables debugging. Default value is true.

injectPackages()

Injects your installed packages into your routes. This allows you to use packages in your routes without having to require them in each file. Only compiles packages that are installed, not inbuilt packages.

setValidator(validator)

Sets your validator. This allows you to validate incoming requests in your routes.

connectDocumentation( /api-docs, swaggerUi.serve, swaggerUi.setup(swaggerDocument) )

set your documentation here.

File Structure

ExclusiveJs generates routes based on the file structure of your project. Here is an example file structure:

src/routes/ ├── index.js ├── users.js ├── auth/ │ ├── login.js │ └── register.js └── posts/ ├── [postId].js ├── index.js └── new.js

In this example, ExclusiveJs will generate the following routes:

  • GET /api/
  • GET /api/users
  • GET /api/auth/login
  • POST /api/auth/login
  • GET /api/auth/register
  • POST /api/auth/register
  • GET /api/posts
  • POST /api/posts
  • GET /api/posts/:postId
  • PATCH /api/posts/:postId
  • DELETE /api/posts/:postId
  • GET /api/posts/new

Note that ExclusiveJs automatically generates routes based on the file names and directory structure of your project. Files with the name index.js are treated as the root of a directory.

Here is how your route file will look like


const AuthController = require("../../controller/auth");
const UserSchema = require("../../model/user");

class AuthRoute {
  #validator;
  #packages;
  #services;
  #models;
  constructor({ packages, models, services }) {
    this.#packages = packages;
    this.#services = services;
    this.#models = models;
  }

   
  "post.login" = async (req, res) => {
    const { walletAddress } = req.body;
    let user = await this.#services.AuthController.login(walletAddress);
    if (!user) return res.status(400).json({ message: "user does not exist" });
    user = { email: user.email, userId: String(user._id) };
    const token = this.#packages.jsonwebtoken.sign(
      user,
      process.env.SECRET_KEY
    );
    return res.status(200).json({ token, user });
  };
  "post.register" = async (req, res) => {
    const { walletAddress, githubLink, linkedInLink, lastName, firstName } =
      req.body;
    let user = await this.#services.AuthController.login(walletAddress);
    if (user) return res.status(400).json({ message: "user does  exist" });

    user = await this.#services.AuthController.createUser(
      walletAddress,
      githubLink,
      linkedInLink,
      lastName,
      firstName
    );

    user = {
      email: user.email,
      userId: String(user._id),
      walletAddress: user.walletAddress,
    };
    const token = this.#packages.jsonwebtoken.sign(
      user,
      process.env.SECRET_KEY
    );
    return res.status(200).json({ token, user });
  };
}

class Validator {
  #validator;
  constructor({ validator }) {
    this.#validator = validator;
  }
  all = () => [];

  "post.login" = () => {
    return [
      this.#validator.ValidatorFactory.createUserValidator(),
      this.#validator.validatorRule,
    ];
  };
}
module.exports = {
  route: AuthRoute,
  middleware: Validator,
  injectableClass: [AuthController],
  injectableModel: [UserSchema], 
};



In the above code we created two route called register and a login routes. this file is assume to be inside the auth folder in the routes folder. any model/database schema that will be used must be injected into the injectableModel same for any services or controller. After doing that, you will then get access to the injected in the constructor. check the bellow code snippet.


constructor({ packages, models, services }) {
  }

model ---> the injected models/repository or database schema
services ---> the injectableClass
packages -->  access to all installed packages that inside your package.json file

Also we have one that is called validator


constructor({ validator }) {
    this.#validator = validator;
  }

Validator

This are can be used for middleware on all routes and for you to use this you have to set then in your entry file.

Let say your validation file looks like this

const { body, param, validationResult } = require("express-validator");

exports.validatorRule = function (req, res, next) {
  const error = validationResult(req).formatWith(({ msg }) => msg);
  const hasError = !error.isEmpty();
  if (hasError) {
    res.status(422).json({ error: error.array() });
  } else {
    next();
  }
};

class ValidatorFactory {
  static walletAddress = body("walletAddress")
    .isString()
    .withMessage("Provide a wallet address");
  static createUserValidator() {
    return [this.walletAddress];
  }
}

exports.ValidatorFactory = ValidatorFactory;


All you just need to do is to export the whole file and the use the function(setValidator) to set it in the entry file .

  .setValidator(validator)

Incase you have more that one validator file you can export the in a single file like this


const validator = require("../validator");
module.exports = {
  validator,
};

then import into the entry file

let validator = require("../packages/index");

then set

  .setValidator(validator)

License

This project is licensed under the MIT License - see the LICENSE file for details.

Credits

ExclusiveJs was created by ajibadeabd and is based on [the original project](link to original project). Special thanks to ajibadeabd for their contributions and support.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published