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

crud-api-express

v1.1.1

Published

npm install crud-api-express

Downloads

36

Readme

CRUD API Controller using Express and Mongoose

npm install crud-api-express

This project provides a flexible and reusable CRUD (Create, Read, Update, Delete) API controller for MongoDB using Express.js and Mongoose.

Table of Contents

Introduction

The CrudController class is designed to simplify the creation of RESTful APIs in Node.js applications that use MongoDB as the database backend. It abstracts away common CRUD operations, error handling, middleware integration, and supports custom routes and aggregation pipelines.

Installation

To use CrudController in your Node.js project, follow these steps:

  1. Install Node.js: Make sure you have Node.js installed on your system.
  2. Install Dependencies: Navigate to your project directory and run:
    npm install express mongoose
    
    

Usage

Here's a basic example of how to use CrudController:

import express from 'express'; import mongoose from 'mongoose'; import CrudController from 'crud-api-express';

const Schema = mongoose.Schema; const ExampleSchema = new Schema({ type: { type: String, default: 'Percentage', enum: ['Percentage', 'Flat'] }, status: { type: String, default: 'Active', trim: true }, expiry_date: { type: Date, index: true, trim: true }, }, { timestamps: true, versionKey: false });

const ExampleModel = mongoose.model('Example', ExampleSchema);

const options = { middleware: [ (req, res, next) => { // Example: Authentication middleware const authToken = req.headers.authorization; if (!authToken) { return res.status(401).json({ message: 'Unauthorized' }); } // Verify token logic here next(); }, (req, res, next) => { // Example: Logging middleware console.log(Request received at ${new Date()}); next(); } ], onSuccess: (res, method, result) => { console.log(Successful ${method} operation:, result); res.status(200).json({ success: true, data: result }); }, onError: (res, method, error) => { console.error(Error in ${method} operation:, error); res.status(500).json({ error: error.message }); }, methods: ['GET', 'POST', 'PUT', 'DELETE'], relatedModel: RelatedModel, relatedField: 'relatedId', aggregatePipeline: [ { $match: { status: 'Active' } }, { $sort: { createdAt: -1 } } ], customRoutes: [ { method: 'get', path: '/custom-route', handler: (req, res) => { res.json({ message: 'Custom route handler executed' }); } }, { method: 'post', path: '/custom-action', handler: (req, res) => { // Custom logic for handling POST request res.json({ message: 'Custom action executed' }); } } ] };

const exampleController = new CrudController(ExampleModel, 'examples', options);

const mongoURI = 'mongodb://localhost:27017/mydatabase';

mongoose.connect(mongoURI, { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => { console.log('Connected to MongoDB');

const app = express();
app.use(express.json());

app.use('/api', exampleController.getRouter());

console.log(exampleController.getRoutes());

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

}) .catch(err => { console.error('Error connecting to MongoDB:', err.message); process.exit(1); });

API

model: Mongoose model for CRUD operations. endpoint: API endpoint path. options: Optional configuration for CRUD operations. Methods getRouter(): Router - Returns the Express Router instance configured with CRUD routes.

CrudOptions Configuration options for CrudController.

options

middleware?: ((req: Request, res: Response, next: NextFunction) => void)[] - Array of middleware functions. onSuccess?: (res: Response, method: string, result: T | T[]) => void - Success handler function. onError?: (res: Response, method: string, error: Error) => void - Error handler function. methods?: ('POST' | 'GET' | 'PUT' | 'DELETE')[] - Array of HTTP methods to support. relatedModel?: Model - Related Mongoose model for relational operations. relatedField?: string - Field name for related models. relatedMethods?: ('POST' | 'GET' | 'PUT' | 'DELETE')[] - Methods to apply on related models. aggregatePipeline?: object[] - MongoDB aggregation pipeline stages. customRoutes?: { method: 'post' | 'get' | 'put' | 'delete', path: string, handler: (req: Request, res: Response) => void }[] - Array of custom routes definitions.