node-responder 1.0.0

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.
package/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+ Copyright (c) 2026 hammadsadi
3
+
4
+ Permission is hereby granted, free of
5
+ charge, to any person obtaining a copy of this software and associated
6
+ documentation files (the "Software"), to deal in the Software without
7
+ restriction, including without limitation the rights to use, copy, modify, merge,
8
+ publish, distribute, sublicense, and/or sell copies of the Software, and to
9
+ permit persons to whom the Software is furnished to do so, subject to the
10
+ following conditions:
11
+
12
+ The above copyright notice and this permission notice
13
+ (including the next paragraph) shall be included in all copies or substantial
14
+ portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
17
+ ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
19
+ EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
20
+ OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22
+ THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,253 @@
1
+ # node-responder
2
+
3
+ > Modern, standardized API response middleware for Express.js
4
+
5
+ [![npm version](https://img.shields.io/npm/v/node-responder.svg)](https://www.npmjs.com/package/node-responder)
6
+ [![license](https://img.shields.io/npm/l/node-responder.svg)](LICENSE)
7
+ [![TypeScript](https://img.shields.io/badge/TypeScript-supported-blue.svg)](types/index.d.ts)
8
+ [![zero dependencies](https://img.shields.io/badge/dependencies-0-green.svg)]()
9
+
10
+ Stop writing repetitive `res.status(200).json({ success: true, data: ... })` in every route. `node-responder` adds clean, consistent response helpers directly to Express's `res` object.
11
+
12
+ ---
13
+
14
+ ## ✨ Features
15
+
16
+ - ✅ **Zero dependencies** — only Express as a peer dependency
17
+ - ✅ **TypeScript support** — full type definitions included
18
+ - ✅ **ESM + CommonJS** — works with both `require` and `import`
19
+ - ✅ **Pagination built-in** — `res.paginate()` with full meta
20
+ - ✅ **Consistent format** — every response follows the same structure
21
+ - ✅ **Shorthand methods** — `res.ok()`, `res.notFound()`, `res.unauthorized()` and more
22
+ - ✅ **Node.js 14+** supported
23
+
24
+ ---
25
+
26
+ ## 📦 Installation
27
+
28
+ ```bash
29
+ npm install node-responder
30
+ ```
31
+
32
+ ---
33
+
34
+ ## 🚀 Quick Start
35
+
36
+ ```js
37
+ const express = require("express");
38
+ const responder = require("node-responder");
39
+
40
+ const app = express();
41
+
42
+ // Apply middleware globally
43
+ app.use(responder());
44
+
45
+ app.get("/user/:id", async (req, res) => {
46
+ const user = await User.findById(req.params.id);
47
+
48
+ if (!user) return res.notFound("User not found");
49
+
50
+ return res.ok(user);
51
+ });
52
+
53
+ app.listen(3000);
54
+ ```
55
+
56
+ ---
57
+
58
+ ## 📋 Response Format
59
+
60
+ All responses follow this consistent structure:
61
+
62
+ **Success:**
63
+
64
+ ```json
65
+ {
66
+ "success": true,
67
+ "message": "Success",
68
+ "data": { ... },
69
+ "meta": {
70
+ "timestamp": "2024-01-15T10:30:00.000Z",
71
+ "statusCode": 200
72
+ }
73
+ }
74
+ ```
75
+
76
+ **Error:**
77
+
78
+ ```json
79
+ {
80
+ "success": false,
81
+ "message": "User not found",
82
+ "data": null,
83
+ "errors": null,
84
+ "meta": {
85
+ "timestamp": "2024-01-15T10:30:00.000Z",
86
+ "statusCode": 404
87
+ }
88
+ }
89
+ ```
90
+
91
+ **Paginated:**
92
+
93
+ ```json
94
+ {
95
+ "success": true,
96
+ "message": "Users fetched",
97
+ "data": [ ... ],
98
+ "meta": {
99
+ "timestamp": "2024-01-15T10:30:00.000Z",
100
+ "statusCode": 200,
101
+ "pagination": {
102
+ "page": 1,
103
+ "limit": 10,
104
+ "total": 100,
105
+ "totalPages": 10,
106
+ "hasNextPage": true,
107
+ "hasPrevPage": false
108
+ }
109
+ }
110
+ }
111
+ ```
112
+
113
+ ---
114
+
115
+ ## 📖 API Reference
116
+
117
+ ### Middleware Setup
118
+
119
+ ```js
120
+ const responder = require("node-responder");
121
+
122
+ app.use(responder()); // attach to all routes
123
+ // or
124
+ router.use(responder()); // attach to specific router
125
+ ```
126
+
127
+ ---
128
+
129
+ ### ✅ Success Methods
130
+
131
+ | Method | Status | Description |
132
+ | ---------------------------------------- | ------ | ---------------- |
133
+ | `res.success(data, message, statusCode)` | custom | Generic success |
134
+ | `res.ok(data, message)` | 200 | Standard OK |
135
+ | `res.created(data, message)` | 201 | Resource created |
136
+ | `res.noContent()` | 204 | No content |
137
+
138
+ ```js
139
+ res.ok({ id: 1, name: "Rahim" });
140
+ res.created({ id: 5 }, "User created successfully");
141
+ res.success(data, "Custom message", 200);
142
+ ```
143
+
144
+ ---
145
+
146
+ ### ❌ Error Methods
147
+
148
+ | Method | Status | Description |
149
+ | ---------------------------------------- | ------ | -------------------- |
150
+ | `res.error(message, statusCode, errors)` | custom | Generic error |
151
+ | `res.badRequest(message, errors)` | 400 | Validation failed |
152
+ | `res.unauthorized(message)` | 401 | Not authenticated |
153
+ | `res.forbidden(message)` | 403 | Not authorized |
154
+ | `res.notFound(message)` | 404 | Resource not found |
155
+ | `res.conflict(message)` | 409 | Conflict |
156
+ | `res.unprocessable(message, errors)` | 422 | Unprocessable entity |
157
+ | `res.serverError(message)` | 500 | Server error |
158
+
159
+ ```js
160
+ res.notFound("Product not found");
161
+ res.unauthorized("Please login first");
162
+ res.badRequest("Validation failed", { email: "Email is required" });
163
+ ```
164
+
165
+ ---
166
+
167
+ ### 📄 Pagination
168
+
169
+ ```js
170
+ const users = await User.find().skip(skip).limit(limit);
171
+ const total = await User.countDocuments();
172
+
173
+ res.paginate(users, "Users fetched", {
174
+ page: 1,
175
+ limit: 10,
176
+ total: total,
177
+ });
178
+ ```
179
+
180
+ ---
181
+
182
+ ## 🔧 Real-World Example (MERN)
183
+
184
+ ```js
185
+ const express = require("express");
186
+ const responder = require("node-responder");
187
+ const router = express.Router();
188
+
189
+ router.use(responder());
190
+
191
+ // GET all users with pagination
192
+ router.get("/", async (req, res) => {
193
+ try {
194
+ const page = parseInt(req.query.page) || 1;
195
+ const limit = parseInt(req.query.limit) || 10;
196
+ const skip = (page - 1) * limit;
197
+
198
+ const [users, total] = await Promise.all([
199
+ User.find().skip(skip).limit(limit),
200
+ User.countDocuments(),
201
+ ]);
202
+
203
+ return res.paginate(users, "Users fetched", { page, limit, total });
204
+ } catch (err) {
205
+ return res.serverError("Failed to fetch users");
206
+ }
207
+ });
208
+
209
+ // POST create user
210
+ router.post("/", async (req, res) => {
211
+ try {
212
+ const { name, email } = req.body;
213
+
214
+ if (!name || !email) {
215
+ return res.badRequest("Validation failed", {
216
+ name: !name ? "Name is required" : null,
217
+ email: !email ? "Email is required" : null,
218
+ });
219
+ }
220
+
221
+ const exists = await User.findOne({ email });
222
+ if (exists) return res.conflict("Email already registered");
223
+
224
+ const user = await User.create({ name, email });
225
+ return res.created(user, "User registered successfully");
226
+ } catch (err) {
227
+ return res.serverError();
228
+ }
229
+ });
230
+ ```
231
+
232
+ ---
233
+
234
+ ## TypeScript Usage
235
+
236
+ ```ts
237
+ import express from "express";
238
+ import responder from "node-responder";
239
+
240
+ const app = express();
241
+ app.use(responder());
242
+
243
+ app.get("/users", async (req, res) => {
244
+ const users = await User.find();
245
+ res.ok(users, "Users fetched");
246
+ });
247
+ ```
248
+
249
+ ---
250
+
251
+ ## 📄 License
252
+
253
+ MIT © [Hammad Sadi](https://github.com/hammadsadi)
package/package.json ADDED
@@ -0,0 +1,59 @@
1
+ {
2
+ "name": "node-responder",
3
+ "version": "1.0.0",
4
+ "description": "Modern, standardized API response middleware for Express.js — with TypeScript support, pagination, and shorthand methods.",
5
+ "main": "src/index.js",
6
+ "types": "types/index.d.ts",
7
+ "exports": {
8
+ ".": {
9
+ "require": "./src/index.js",
10
+ "import": "./src/index.js",
11
+ "types": "./types/index.d.ts"
12
+ }
13
+ },
14
+ "scripts": {
15
+ "test": "node test/index.test.js"
16
+ },
17
+ "keywords": [
18
+ "express",
19
+ "api",
20
+ "response",
21
+ "middleware",
22
+ "rest",
23
+ "json",
24
+ "typescript",
25
+ "mern",
26
+ "nodejs",
27
+ "http",
28
+ "pagination",
29
+ "standardized",
30
+ "node-responder",
31
+ "responder"
32
+ ],
33
+ "author": "Hammad Sadi <hammad.sadi@yahoo.com>",
34
+ "license": "MIT",
35
+ "peerDependencies": {
36
+ "express": ">=4.0.0"
37
+ },
38
+ "devDependencies": {
39
+ "@types/express": "^4.17.21",
40
+ "express": "^4.18.2"
41
+ },
42
+ "repository": {
43
+ "type": "git",
44
+ "url": "https://github.com/hammadsadi/node-responder"
45
+ },
46
+ "homepage": "https://github.com/hammadsadi/node-responder#readme",
47
+ "bugs": {
48
+ "url": "https://github.com/hammadsadi/node-responder/issues"
49
+ },
50
+ "files": [
51
+ "src/",
52
+ "types/",
53
+ "README.md",
54
+ "LICENSE"
55
+ ],
56
+ "engines": {
57
+ "node": ">=14.0.0"
58
+ }
59
+ }
package/src/index.js ADDED
@@ -0,0 +1,142 @@
1
+ "use strict";
2
+
3
+ /**
4
+ * node-responder
5
+ * Standardized, modern API response middleware for Express.js
6
+ * @author Hammad Sadi
7
+ * @license MIT
8
+ */
9
+
10
+ /**
11
+ * Creates a success response
12
+ */
13
+ function successResponse(
14
+ res,
15
+ data = null,
16
+ message = "Success",
17
+ statusCode = 200,
18
+ ) {
19
+ return res.status(statusCode).json({
20
+ success: true,
21
+ message,
22
+ data,
23
+ meta: {
24
+ timestamp: new Date().toISOString(),
25
+ statusCode,
26
+ },
27
+ });
28
+ }
29
+
30
+ /**
31
+ * Creates an error response
32
+ */
33
+ function errorResponse(
34
+ res,
35
+ message = "Something went wrong",
36
+ statusCode = 500,
37
+ errors = null,
38
+ ) {
39
+ return res.status(statusCode).json({
40
+ success: false,
41
+ message,
42
+ data: null,
43
+ errors,
44
+ meta: {
45
+ timestamp: new Date().toISOString(),
46
+ statusCode,
47
+ },
48
+ });
49
+ }
50
+
51
+ /**
52
+ * Creates a paginated response
53
+ */
54
+ function paginatedResponse(
55
+ res,
56
+ data = [],
57
+ message = "Success",
58
+ pagination = {},
59
+ ) {
60
+ const { page = 1, limit = 10, total = 0 } = pagination;
61
+
62
+ const totalPages = Math.ceil(total / limit);
63
+
64
+ return res.status(200).json({
65
+ success: true,
66
+ message,
67
+ data,
68
+ meta: {
69
+ timestamp: new Date().toISOString(),
70
+ statusCode: 200,
71
+ pagination: {
72
+ page: Number(page),
73
+ limit: Number(limit),
74
+ total: Number(total),
75
+ totalPages,
76
+ hasNextPage: page < totalPages,
77
+ hasPrevPage: page > 1,
78
+ },
79
+ },
80
+ });
81
+ }
82
+
83
+ /**
84
+ * Express middleware — attaches helper methods to res object
85
+ */
86
+ function apiResponse() {
87
+ return function (req, res, next) {
88
+ // res.success(data, message, statusCode)
89
+ res.success = function (
90
+ data = null,
91
+ message = "Success",
92
+ statusCode = 200,
93
+ ) {
94
+ return successResponse(res, data, message, statusCode);
95
+ };
96
+
97
+ // res.error(message, statusCode, errors)
98
+ res.error = function (
99
+ message = "Something went wrong",
100
+ statusCode = 500,
101
+ errors = null,
102
+ ) {
103
+ return errorResponse(res, message, statusCode, errors);
104
+ };
105
+
106
+ // res.paginate(data, message, pagination)
107
+ res.paginate = function (data = [], message = "Success", pagination = {}) {
108
+ return paginatedResponse(res, data, message, pagination);
109
+ };
110
+
111
+ // Shorthand methods
112
+ res.ok = (data, message = "Success") =>
113
+ successResponse(res, data, message, 200);
114
+ res.created = (data, message = "Created successfully") =>
115
+ successResponse(res, data, message, 201);
116
+ res.noContent = () => res.status(204).send();
117
+
118
+ res.badRequest = (message = "Bad request", errors = null) =>
119
+ errorResponse(res, message, 400, errors);
120
+ res.unauthorized = (message = "Unauthorized") =>
121
+ errorResponse(res, message, 401);
122
+ res.forbidden = (message = "Forbidden") => errorResponse(res, message, 403);
123
+ res.notFound = (message = "Not found") => errorResponse(res, message, 404);
124
+ res.conflict = (message = "Conflict") => errorResponse(res, message, 409);
125
+ res.unprocessable = (message = "Unprocessable entity", errors = null) =>
126
+ errorResponse(res, message, 422, errors);
127
+ res.serverError = (message = "Internal server error") =>
128
+ errorResponse(res, message, 500);
129
+
130
+ next();
131
+ };
132
+ }
133
+
134
+ // Named exports
135
+ module.exports = apiResponse;
136
+ module.exports.apiResponse = apiResponse;
137
+ module.exports.successResponse = successResponse;
138
+ module.exports.errorResponse = errorResponse;
139
+ module.exports.paginatedResponse = paginatedResponse;
140
+
141
+ // ESM default export support
142
+ module.exports.default = apiResponse;
@@ -0,0 +1,108 @@
1
+ import { Request, Response, NextFunction, RequestHandler } from "express";
2
+
3
+ export interface Pagination {
4
+ page?: number;
5
+ limit?: number;
6
+ total?: number;
7
+ }
8
+
9
+ export interface PaginationMeta {
10
+ page: number;
11
+ limit: number;
12
+ total: number;
13
+ totalPages: number;
14
+ hasNextPage: boolean;
15
+ hasPrevPage: boolean;
16
+ }
17
+
18
+ export interface ApiMeta {
19
+ timestamp: string;
20
+ statusCode: number;
21
+ pagination?: PaginationMeta;
22
+ }
23
+
24
+ export interface ApiSuccessResponse<T = any> {
25
+ success: true;
26
+ message: string;
27
+ data: T;
28
+ meta: ApiMeta;
29
+ }
30
+
31
+ export interface ApiErrorResponse {
32
+ success: false;
33
+ message: string;
34
+ data: null;
35
+ errors: any | null;
36
+ meta: ApiMeta;
37
+ }
38
+
39
+ declare global {
40
+ namespace Express {
41
+ interface Response {
42
+ /** Send a success response */
43
+ success<T = any>(
44
+ data?: T,
45
+ message?: string,
46
+ statusCode?: number,
47
+ ): Response;
48
+
49
+ /** Send an error response */
50
+ error(message?: string, statusCode?: number, errors?: any): Response;
51
+
52
+ /** Send a paginated response */
53
+ paginate<T = any>(
54
+ data?: T[],
55
+ message?: string,
56
+ pagination?: Pagination,
57
+ ): Response;
58
+
59
+ // Shorthand methods
60
+ /** 200 OK */
61
+ ok<T = any>(data?: T, message?: string): Response;
62
+ /** 201 Created */
63
+ created<T = any>(data?: T, message?: string): Response;
64
+ /** 204 No Content */
65
+ noContent(): Response;
66
+
67
+ /** 400 Bad Request */
68
+ badRequest(message?: string, errors?: any): Response;
69
+ /** 401 Unauthorized */
70
+ unauthorized(message?: string): Response;
71
+ /** 403 Forbidden */
72
+ forbidden(message?: string): Response;
73
+ /** 404 Not Found */
74
+ notFound(message?: string): Response;
75
+ /** 409 Conflict */
76
+ conflict(message?: string): Response;
77
+ /** 422 Unprocessable Entity */
78
+ unprocessable(message?: string, errors?: any): Response;
79
+ /** 500 Internal Server Error */
80
+ serverError(message?: string): Response;
81
+ }
82
+ }
83
+ }
84
+
85
+ export declare function apiResponse(): RequestHandler;
86
+
87
+ export declare function successResponse(
88
+ res: Response,
89
+ data?: any,
90
+ message?: string,
91
+ statusCode?: number,
92
+ ): Response;
93
+
94
+ export declare function errorResponse(
95
+ res: Response,
96
+ message?: string,
97
+ statusCode?: number,
98
+ errors?: any,
99
+ ): Response;
100
+
101
+ export declare function paginatedResponse(
102
+ res: Response,
103
+ data?: any[],
104
+ message?: string,
105
+ pagination?: Pagination,
106
+ ): Response;
107
+
108
+ export default apiResponse;