npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

killbot

v1.1.0

Published

Introducing Killbot, a formidable CRUD system designed for seamless integration with Node.js and MongoDB. Simplify your data management tasks with our intuitive and efficient solution. Killbot offers a robust set of features, including easy-to-use APIs fo

Downloads

5

Readme

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
        }]],

    }
};