1.1.0 • Published 8 months ago

killbot3 v1.1.0

Weekly downloads
-
License
ISC
Repository
-
Last release
8 months ago

Custom Utility Functions for Express and MongoDB

This package provides a set of custom utility functions for simplifying common tasks when working with Express.js and MongoDB. These functions are designed to enhance your development workflow by providing streamlined methods for handling CRUD operations, request validation, response handling, dynamic database schema creation, and more.

Installation

To use these utility functions in your project, you can install the package via npm:

npm i killbot3

Usage

const express = require('express');
const mongoose = require('mongoose');
const {postRecursiveRoutes} = require('killbot3');

// Initialize Express app and MongoDB connection
const app = express();
mongoose.connect('mongodb://localhost/mydatabase', { useNewUrlParser: true, useUnifiedTopology: true });

// Define your MongoDB database schema configurations
const databaseConfig = {
    db: {
        // Define your MongoDB collections and schema here
        // Example: 'collectionName': { field1: String, field2: Number, ... }
    },
    pre: {
        // Define pre-save middleware functions if needed
        // Example: 'collectionName': [['save', function(next) { ... }], ['save', function(next) { ... }]]
    },
    statics: {
        // Define static methods if needed
        // Example: 'collectionName': [['methodName', function() { ... }], ['methodName', function() { ... }]]
    }
};

const validation = {
    // Define your MongoDB collections and schema here
    // Example: 'collectionName':  { post: [field1, field2], patch: [field1, field2] } 
};

// Set up dynamic routes using postRecursiveRoutes
postRecursiveRoutes(app, databaseConfig, validation={}); 

// Start the Express server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});

Functions

Crud(modal, method, id, body, condition, pages, populate, orderby, select)

This function simplifies CRUD operations for MongoDB using Mongoose.

  • modal: The Mongoose model for the collection you want to interact with.
  • method: The CRUD operation to perform ('get', 'post', 'patch', or 'delete').
  • id: Document ID for 'get', 'patch', or 'delete' operations.
  • body: Data for 'post' and 'patch' operations.
  • condition: Query conditions for 'get' operation.
  • pages: Pagination configuration for 'get' operation.
  • populate: Fields to populate using Mongoose's populate method.
  • orderby: Sorting configuration for 'get' operation.
  • select: Fields to select for 'get' operation.
const { Crud } = require('killbot3');

// Usage example:
const modal = // your Mongoose model
const method = 'get'; // 'get', 'post', 'patch', or 'delete'
const id = ''; // document ID
const body = {null}; // data for 'post' and 'patch' methods
const condition = {null}; // query conditions for 'get' method
const pages = { page: 1, limit: 10 } || 'all' || 'single'; // pagination settings 
const populate = ''; // field to populate using Mongoose's `populate`
const orderby = {null}; // sorting configuration
const select = ''; // fields to select

const [success, result] = await Crud(modal, method, id, body, condition, pages, populate, orderby, select);

getData(modal, id, condition, pages, populate, orderby, select)

This function simplifies CRUD operations for MongoDB using Mongoose.

  • modal: The Mongoose model for the collection you want to interact with.
  • id: Document ID for 'get', 'patch', or 'delete' operations.
  • condition: Query conditions for 'get' operation.
  • pages: Pagination configuration for 'get' operation.
  • populate: Fields to populate using Mongoose's populate method.
  • orderby: Sorting configuration for 'get' operation.
  • select: Fields to select for 'get' operation.
const { getData } = require('killbot3');


// Usage example:
const modal = // your Mongoose model
const id = ''; // document ID
const condition = null; // query conditions
const pages = { page: 1, limit: 10 }; // pagination settings
const populate = ''; // field to populate using Mongoose's `populate`
const orderby = null; // sorting configuration
const select = ''; // fields to select

const [success, result] = await getData(modal, id, condition, pages, populate, orderby, select);

validater(res, search, data)

A function for validating request data based on specified search criteria.

  • res: Your Express response object
  • search: An array of field names to validate.
  • data: The data object to validate against.
const { validater } = require('killbot3');

// Usage example:
const res = // your Express response object
const search = ['field1', 'field2']; // fields to validate
const data = // your data object

validater(res, search, data);

HandleRes(res, status, message, data)

A function for handling and formatting HTTP responses.

  • res: The Express response object.
  • status: HTTP status code.
  • message: Response message.
  • data: Data to include in the response.
const { HandleRes } = require('killbot3');

// Usage example:
const res = // your Express response object
const status = 200; // HTTP status code
const message = 'Request successful'; // response message
const data = // your response data

HandleRes(res, status, message, data);

DynamicDB(name, db)

A function for dynamically creating Mongoose models based on database configurations.

  • name: The name of the collection/model.
  • db: Database configuration object.
const { DynamicDB } = require('killbot3');

// Usage example:
const name = 'MyCollection'; // collection name
const db = // your database configuration object

const Modal = DynamicDB(name, db);

postRecursiveRoutes(app, db,validaters)

A function for setting up dynamic routes in an Express app based on database configurations.

  • app: The Express app.
  • db: Database configuration object.
  • validaters: your validation rules object
const { postRecursiveRoutes } = require('killbot3');

// Usage example:
const app = // your Express app
const db = // your database configuration object
const validaters = // your validation rules object

postRecursiveRoutes(app, db, validaters);

recursiveRoutes(app, db,validaters)

A function for setting up dynamic routes in an Express app based on database configurations.

  • app: The Express app.
  • db: Database configuration object.
  • validaters: your validation rules object
  • middlewares: your middleware object
const { recursiveRoutes } = require('killbot3');

// Usage example:
const app = // your Express app
const db = // your database configuration object
const validaters = // your validation rules object
const middlewares = // your middleware object

recursiveRoutes(app, db, validaters, middlewares);

Example databaseConfig

const databaseConfig = {
    db: {
        "User": {
            name: {
                type: String,
                required: [true, "Can't be blank"]
            },
            email: {
                type: String,
                lowercase: true,
                unique: true,
                required: [true, "Can't be blank"],
                index: true,
            },
            admin: {
                type: Boolean,
                default: false
            },
            password: {
                type: String,
                required: [true, "Can't be blank"]
            },
            picture: {
                type: String,
            },
            status: {
                type: String,
                default: 'online'
            }
        },
    },
    pre: {
        "User": [
        ['save', function (next) {
            const user = this;
            if (!user.isModified('password')) return next();
            bcrypt.genSalt(10, function (err, salt) {
                if (err) return next(err);
                bcrypt.hash(user.password, salt, function (err, hash) {
                    if (err) return next(err);
                    user.password = hash
                    next();
                })
            })
        }]],
    },
    statics: {
         "User": [
        ['findByCredentials', async function (email, password) {
            const user = await this.findOne({ email });
            if (!user) throw new Error('invalid email or password');

            const isMatch = await bcrypt.compare(password, user.password);
            if (!isMatch) throw new Error('invalid email or password')
            return user
        }]],

    }
};
1.1.0

8 months ago

1.0.5

9 months ago

1.0.4

9 months ago

1.0.3

9 months ago

1.0.2

9 months ago

1.0.1

9 months ago

1.0.0

9 months ago