crud-api-express 1.1.2 → 1.1.3

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 +57 -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.3",
4
4
  "type": "module",
5
5
  "description": "",
6
6
  "main": "dist/index.js",
package/readme.md CHANGED
@@ -1,66 +1,71 @@
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
 
16
+ ## Support Me!
17
+
18
+ For Your Support [Visit](https://buymeacoffee.com/mrider007).
19
+
8
20
  ## Table of Contents
9
21
 
10
22
  - [Introduction](#introduction)
11
23
  - [Installation](#installation)
12
24
  - [Usage](#usage)
13
25
  - [API](#api)
26
+ - [Options](#options)
14
27
  - [Examples](#examples)
15
28
  - [Contributing](#contributing)
16
29
  - [License](#license)
17
30
 
18
31
  ## Introduction
19
32
 
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.
21
-
22
- ## Installation
23
-
24
- To use `CrudController` in your Node.js project, follow these steps:
33
+ 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.
25
34
 
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
35
+ ## Usage
30
36
 
37
+ Here's a basic example of how to use `CrudController`:
31
38
 
32
- # Usage
33
- Here's a basic example of how to use CrudController:
34
-
39
+ ```javascript
35
40
  import express from 'express';
36
41
  import mongoose from 'mongoose';
37
42
  import CrudController from 'crud-api-express';
38
43
 
39
44
  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 });
45
+ const ExampleSchema = new Schema(
46
+ {
47
+ type: { type: String, default: 'Percentage', enum: ['Percentage', 'Flat'] },
48
+ status: { type: String, default: 'Active', trim: true },
49
+ expiry_date: { type: Date, index: true, trim: true },
50
+ },
51
+ { timestamps: true, versionKey: false }
52
+ );
45
53
 
46
54
  const ExampleModel = mongoose.model('Example', ExampleSchema);
47
55
 
48
56
  const options = {
49
57
  middleware: [
50
58
  (req, res, next) => {
51
- // Example: Authentication middleware
52
59
  const authToken = req.headers.authorization;
53
60
  if (!authToken) {
54
61
  return res.status(401).json({ message: 'Unauthorized' });
55
62
  }
56
- // Verify token logic here
57
63
  next();
58
64
  },
59
65
  (req, res, next) => {
60
- // Example: Logging middleware
61
66
  console.log(`Request received at ${new Date()}`);
62
67
  next();
63
- }
68
+ },
64
69
  ],
65
70
  onSuccess: (res, method, result) => {
66
71
  console.log(`Successful ${method} operation:`, result);
@@ -71,11 +76,9 @@ const options = {
71
76
  res.status(500).json({ error: error.message });
72
77
  },
73
78
  methods: ['GET', 'POST', 'PUT', 'DELETE'],
74
- relatedModel: RelatedModel,
75
- relatedField: 'relatedId',
76
79
  aggregatePipeline: [
77
80
  { $match: { status: 'Active' } },
78
- { $sort: { createdAt: -1 } }
81
+ { $sort: { createdAt: -1 } },
79
82
  ],
80
83
  customRoutes: [
81
84
  {
@@ -83,30 +86,29 @@ const options = {
83
86
  path: '/custom-route',
84
87
  handler: (req, res) => {
85
88
  res.json({ message: 'Custom route handler executed' });
86
- }
89
+ },
87
90
  },
88
91
  {
89
92
  method: 'post',
90
93
  path: '/custom-action',
91
94
  handler: (req, res) => {
92
- // Custom logic for handling POST request
93
95
  res.json({ message: 'Custom action executed' });
94
- }
95
- }
96
- ]
96
+ },
97
+ },
98
+ ],
97
99
  };
98
100
 
99
101
  const exampleController = new CrudController(ExampleModel, 'examples', options);
100
102
 
101
103
  const mongoURI = 'mongodb://localhost:27017/mydatabase';
102
104
 
103
- mongoose.connect(mongoURI, { useNewUrlParser: true, useUnifiedTopology: true })
105
+ mongoose
106
+ .connect(mongoURI, { useNewUrlParser: true, useUnifiedTopology: true })
104
107
  .then(() => {
105
108
  console.log('Connected to MongoDB');
106
109
 
107
110
  const app = express();
108
111
  app.use(express.json());
109
-
110
112
  app.use('/api', exampleController.getRouter());
111
113
 
112
114
  console.log(exampleController.getRoutes());
@@ -116,31 +118,35 @@ mongoose.connect(mongoURI, { useNewUrlParser: true, useUnifiedTopology: true })
116
118
  console.log(`Server is running on port ${PORT}`);
117
119
  });
118
120
  })
119
- .catch(err => {
121
+ .catch((err) => {
120
122
  console.error('Error connecting to MongoDB:', err.message);
121
123
  process.exit(1);
122
124
  });
125
+ ```
126
+
127
+ ## API
128
+
129
+ ### Methods
123
130
 
131
+ #### `getRouter(): Router`
132
+ Returns the Express Router instance configured with CRUD routes.
124
133
 
134
+ ## Options
125
135
 
126
- # API
136
+ ### `CrudOptions<T>`
127
137
 
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.
138
+ | Option | Type | Description |
139
+ |----------------|--------------------------------------------------------------------------------------------|-------------------------------------------------------|
140
+ | `middleware` | `((req: Request, res: Response, next: NextFunction) => void)[]` | Array of middleware functions |
141
+ | `onSuccess` | `(res: Response, method: string, result: T | T[]) => void` | Success handler function |
142
+ | `onError` | `(res: Response, method: string, error: Error) => void` | Error handler function |
143
+ | `methods` | `('POST' | 'GET' | 'PUT' | 'DELETE')[]` | Array of HTTP methods to support |
144
+ | `relatedModel` | `Model<any>` | Related Mongoose model for relational operations |
145
+ | `relatedField` | `string` | Field name for related models |
146
+ | `relatedMethods` | `('POST' | 'GET' | 'PUT' | 'DELETE')[]` | Methods to apply on related models |
147
+ | `aggregatePipeline` | `object[]` | MongoDB aggregation pipeline stages |
148
+ | `customRoutes` | `{ method: 'post' | 'get' | 'put' | 'delete', path: string, handler: (req, res) => void }[]` | Array of custom route definitions |
133
149
 
134
- CrudOptions<T>
135
- Configuration options for CrudController.
150
+ ## License
136
151
 
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.
152
+ This project is licensed under the ISC License.