crud-api-express 1.1.2 → 1.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/LICENSE +9 -0
  2. package/package.json +1 -1
  3. package/readme.md +69 -51
package/LICENSE ADDED
@@ -0,0 +1,9 @@
1
+ ISC License
2
+
3
+ Copyright (c) 2025 Mukesh Kumar Singh
4
+
5
+ Permission to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is provided to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT, OR OTHERWISE, ARISING FROM, OUT OF, OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "crud-api-express",
3
- "version": "1.1.2",
3
+ "version": "1.1.4",
4
4
  "type": "module",
5
5
  "description": "",
6
6
  "main": "dist/index.js",
package/readme.md CHANGED
@@ -1,66 +1,78 @@
1
1
  # CRUD API Controller using Express and Mongoose
2
2
 
3
- npm install crud-api-express
3
+ ![npm](https://img.shields.io/npm/v/crud-api-express)
4
+ ![downloads](https://img.shields.io/npm/dm/crud-api-express)
5
+
6
+ ## Installation
4
7
 
8
+ Install the package using npm:
9
+
10
+ ```bash
11
+ npm install crud-api-express
12
+ ```
5
13
 
6
14
  This project provides a flexible and reusable CRUD (Create, Read, Update, Delete) API controller for MongoDB using Express.js and Mongoose.
7
15
 
8
- ## Table of Contents
16
+ ## Support Me! ❤️
17
+
18
+ If you find this package useful, consider supporting me:
19
+ [Buy Me a Coffee ☕](https://buymeacoffee.com/mrider007)
20
+
21
+ ---
22
+
23
+ ## 📌 Table of Contents
9
24
 
10
25
  - [Introduction](#introduction)
11
26
  - [Installation](#installation)
12
27
  - [Usage](#usage)
13
28
  - [API](#api)
29
+ - [Options](#options)
14
30
  - [Examples](#examples)
15
31
  - [Contributing](#contributing)
16
32
  - [License](#license)
17
33
 
18
- ## Introduction
34
+ ---
19
35
 
20
- 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.
36
+ ## 🚀 Introduction
21
37
 
22
- ## Installation
38
+ The `CrudController` class simplifies the creation of RESTful APIs in Node.js applications using MongoDB. It abstracts away common CRUD operations, error handling, middleware integration, and supports custom routes and aggregation pipelines.
23
39
 
24
- To use `CrudController` in your Node.js project, follow these steps:
40
+ ---
25
41
 
26
- 1. **Install Node.js**: Make sure you have Node.js installed on your system.
27
- 2. **Install Dependencies**: Navigate to your project directory and run:
28
- ```bash
29
- npm install express mongoose
42
+ ## 🔧 Usage
30
43
 
44
+ Here's a basic example of how to use `CrudController`:
31
45
 
32
- # Usage
33
- Here's a basic example of how to use CrudController:
34
-
46
+ ```javascript
35
47
  import express from 'express';
36
48
  import mongoose from 'mongoose';
37
49
  import CrudController from 'crud-api-express';
38
50
 
39
51
  const Schema = mongoose.Schema;
40
- const ExampleSchema = new Schema({
41
- type: { type: String, default: 'Percentage', enum: ['Percentage', 'Flat'] },
42
- status: { type: String, default: 'Active', trim: true },
43
- expiry_date: { type: Date, index: true, trim: true },
44
- }, { timestamps: true, versionKey: false });
52
+ const ExampleSchema = new Schema(
53
+ {
54
+ type: { type: String, default: 'Percentage', enum: ['Percentage', 'Flat'] },
55
+ status: { type: String, default: 'Active', trim: true },
56
+ expiry_date: { type: Date, index: true, trim: true },
57
+ },
58
+ { timestamps: true, versionKey: false }
59
+ );
45
60
 
46
61
  const ExampleModel = mongoose.model('Example', ExampleSchema);
47
62
 
48
63
  const options = {
49
64
  middleware: [
50
65
  (req, res, next) => {
51
- // Example: Authentication middleware
52
66
  const authToken = req.headers.authorization;
53
67
  if (!authToken) {
54
68
  return res.status(401).json({ message: 'Unauthorized' });
55
69
  }
56
- // Verify token logic here
57
70
  next();
58
71
  },
59
72
  (req, res, next) => {
60
- // Example: Logging middleware
61
73
  console.log(`Request received at ${new Date()}`);
62
74
  next();
63
- }
75
+ },
64
76
  ],
65
77
  onSuccess: (res, method, result) => {
66
78
  console.log(`Successful ${method} operation:`, result);
@@ -71,11 +83,9 @@ const options = {
71
83
  res.status(500).json({ error: error.message });
72
84
  },
73
85
  methods: ['GET', 'POST', 'PUT', 'DELETE'],
74
- relatedModel: RelatedModel,
75
- relatedField: 'relatedId',
76
86
  aggregatePipeline: [
77
87
  { $match: { status: 'Active' } },
78
- { $sort: { createdAt: -1 } }
88
+ { $sort: { createdAt: -1 } },
79
89
  ],
80
90
  customRoutes: [
81
91
  {
@@ -83,30 +93,29 @@ const options = {
83
93
  path: '/custom-route',
84
94
  handler: (req, res) => {
85
95
  res.json({ message: 'Custom route handler executed' });
86
- }
96
+ },
87
97
  },
88
98
  {
89
99
  method: 'post',
90
100
  path: '/custom-action',
91
101
  handler: (req, res) => {
92
- // Custom logic for handling POST request
93
102
  res.json({ message: 'Custom action executed' });
94
- }
95
- }
96
- ]
103
+ },
104
+ },
105
+ ],
97
106
  };
98
107
 
99
108
  const exampleController = new CrudController(ExampleModel, 'examples', options);
100
109
 
101
110
  const mongoURI = 'mongodb://localhost:27017/mydatabase';
102
111
 
103
- mongoose.connect(mongoURI, { useNewUrlParser: true, useUnifiedTopology: true })
112
+ mongoose
113
+ .connect(mongoURI, { useNewUrlParser: true, useUnifiedTopology: true })
104
114
  .then(() => {
105
115
  console.log('Connected to MongoDB');
106
116
 
107
117
  const app = express();
108
118
  app.use(express.json());
109
-
110
119
  app.use('/api', exampleController.getRouter());
111
120
 
112
121
  console.log(exampleController.getRoutes());
@@ -116,31 +125,40 @@ mongoose.connect(mongoURI, { useNewUrlParser: true, useUnifiedTopology: true })
116
125
  console.log(`Server is running on port ${PORT}`);
117
126
  });
118
127
  })
119
- .catch(err => {
128
+ .catch((err) => {
120
129
  console.error('Error connecting to MongoDB:', err.message);
121
130
  process.exit(1);
122
131
  });
132
+ ```
133
+
134
+ ---
135
+
136
+ ## 📖 API
137
+
138
+ ### `getRouter(): Router`
139
+ Returns the Express Router instance configured with CRUD routes.
140
+
141
+ ---
142
+
143
+ ## ⚙️ Options
123
144
 
124
145
 
146
+ ### `CrudOptions<T>`
125
147
 
126
- # API
148
+ | Option | Type | Description |
149
+ |--------------------|---------------------------------------------------------------------------------------------------------|------------------------------------------------------|
150
+ | `middleware` | `((req: Request, res: Response, next: NextFunction) => void)[]` | Array of middleware functions |
151
+ | `onSuccess` | `(res: Response, method: string, result: T \| T[]) => void` | Success handler function |
152
+ | `onError` | `(res: Response, method: string, error: Error) => void` | Error handler function |
153
+ | `methods` | `('POST' \| 'GET' \| 'PUT' \| 'DELETE')[]` | Array of HTTP methods to support |
154
+ | `relatedModel` | `Model<any>` | Related Mongoose model for relational operations |
155
+ | `relatedField` | `string` | Field name for related models |
156
+ | `relatedMethods` | `('POST' \| 'GET' \| 'PUT' \| 'DELETE')[]` | Methods to apply on related models |
157
+ | `aggregatePipeline` | `object[]` | MongoDB aggregation pipeline stages |
158
+ | `customRoutes` | `{ method: 'post' \| 'get' \| 'put' \| 'delete', path: string, handler: (req: Request, res: Response) => void }[]` | Array of custom route definitions |
127
159
 
128
- model: Mongoose model for CRUD operations.
129
- endpoint: API endpoint path.
130
- options: Optional configuration for CRUD operations.
131
- Methods
132
- getRouter(): Router - Returns the Express Router instance configured with CRUD routes.
160
+ ---
133
161
 
134
- CrudOptions<T>
135
- Configuration options for CrudController.
162
+ ## 📜 License
136
163
 
137
- # options
138
- middleware?: ((req: Request, res: Response, next: NextFunction) => void)[] - Array of middleware functions.
139
- onSuccess?: (res: Response, method: string, result: T | T[]) => void - Success handler function.
140
- onError?: (res: Response, method: string, error: Error) => void - Error handler function.
141
- methods?: ('POST' | 'GET' | 'PUT' | 'DELETE')[] - Array of HTTP methods to support.
142
- relatedModel?: Model<any> - Related Mongoose model for relational operations.
143
- relatedField?: string - Field name for related models.
144
- relatedMethods?: ('POST' | 'GET' | 'PUT' | 'DELETE')[] - Methods to apply on related models.
145
- aggregatePipeline?: object[] - MongoDB aggregation pipeline stages.
146
- customRoutes?: { method: 'post' | 'get' | 'put' | 'delete', path: string, handler: (req: Request, res: Response) => void }[] - Array of custom routes definitions.
164
+ This project is licensed under the **ISC License**.