response-kit 1.0.0 → 2.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.
@@ -1,105 +1,181 @@
1
1
  # Success Responses
2
2
 
3
+ This document covers all success response helpers in Response Kit v2.
4
+
3
5
  Success responses are used when an operation completes successfully.
4
6
 
5
7
  ---
6
8
 
7
- # success()
9
+ ## Overview
10
+
11
+ Response Kit provides two success response helpers:
12
+
13
+ 1. **`success()`** - General success responses (200)
14
+ 2. **`created()`** - Resource creation responses (201)
8
15
 
9
- Use this method when data is fetched successfully.
16
+ Both methods are available in two ways:
17
+ - **Middleware API** (v2): `res.success(data, message)`
18
+ - **Direct API** (v1): `response.success(res, data, message)`
19
+
20
+ ---
10
21
 
11
- ## Syntax
22
+ ## success()
23
+
24
+ Use this method when data is fetched or an operation completes successfully.
25
+
26
+ ### Using Middleware (Recommended)
12
27
 
13
28
  ```js
14
- response.success(
15
- res,
16
- data,
17
- message
18
- );
29
+ app.use(response.middleware());
30
+
31
+ app.get('/users', (req, res) => {
32
+ const users = [
33
+ { id: 1, name: 'John Doe' },
34
+ { id: 2, name: 'Jane Smith' }
35
+ ];
36
+
37
+ res.success(users, 'Users fetched successfully');
38
+ });
19
39
  ```
20
40
 
21
- ## Example
41
+ ### Using Direct API
22
42
 
23
43
  ```js
24
- app.get("/users", (req, res) => {
44
+ app.get('/users', (req, res) => {
25
45
  const users = [
26
- {
27
- id: 1,
28
- name: "John"
29
- }
46
+ { id: 1, name: 'John Doe' },
47
+ { id: 2, name: 'Jane Smith' }
30
48
  ];
31
49
 
32
- response.success(
33
- res,
34
- users,
35
- "Users fetched successfully"
36
- );
50
+ response.success(res, users, 'Users fetched successfully');
37
51
  });
38
52
  ```
39
53
 
40
- ---
54
+ ### Syntax
55
+
56
+ **Middleware API:**
57
+ ```js
58
+ res.success(data, message, statusCode)
59
+ ```
41
60
 
42
- ## Output
61
+ **Direct API:**
62
+ ```js
63
+ response.success(res, data, message, statusCode)
64
+ ```
65
+
66
+ ### Parameters
67
+
68
+ | Parameter | Type | Required | Default | Description |
69
+ |-----------|------|----------|---------|-------------|
70
+ | `data` | any | No | `null` | Response data |
71
+ | `message` | string | No | `'Success'` | Success message |
72
+ | `statusCode` | number | No | `200` | HTTP status code |
73
+
74
+ ### Response Structure
43
75
 
44
76
  ```json
45
77
  {
46
78
  "success": true,
47
79
  "message": "Users fetched successfully",
48
80
  "data": [
49
- {
50
- "id": 1,
51
- "name": "John"
52
- }
81
+ { "id": 1, "name": "John Doe" },
82
+ { "id": 2, "name": "Jane Smith" }
53
83
  ]
54
84
  }
55
85
  ```
56
86
 
57
- ---
87
+ **Status Code:** `200 OK`
58
88
 
59
- # created()
89
+ ### With Configuration
60
90
 
61
- Use this helper after creating a new resource.
91
+ ```js
92
+ response.configure({
93
+ includeTimestamp: true,
94
+ includeRequestId: true,
95
+ });
62
96
 
63
- Examples:
97
+ res.success(users, 'Users fetched successfully');
98
+ ```
64
99
 
65
- * User Registration
66
- * Product Creation
67
- * Order Creation
100
+ **Response:**
101
+ ```json
102
+ {
103
+ "success": true,
104
+ "message": "Users fetched successfully",
105
+ "data": [...],
106
+ "timestamp": "2024-01-15T10:30:00.000Z",
107
+ "requestId": "1705315800000-a1b2c3d4e"
108
+ }
109
+ ```
68
110
 
69
- ---
111
+ ### Custom Status Code
70
112
 
71
- ## Syntax
113
+ You can override the default 200 status code:
72
114
 
73
115
  ```js
74
- response.created(
75
- res,
76
- data,
77
- message
78
- );
116
+ res.success(data, 'Operation completed', 202);
79
117
  ```
80
118
 
119
+ **Status Code:** `202 Accepted`
120
+
81
121
  ---
82
122
 
83
- ## Example
123
+ ## created()
124
+
125
+ Use this method after successfully creating a new resource.
126
+
127
+ ### Common Use Cases
128
+
129
+ - User registration
130
+ - Creating a new post/article
131
+ - Adding a new product
132
+ - Creating a new order
133
+
134
+ ### Using Middleware (Recommended)
84
135
 
85
136
  ```js
86
- app.post("/users", (req, res) => {
87
- const user = {
88
- id: 1,
89
- name: "John"
90
- };
137
+ app.use(response.middleware());
91
138
 
92
- response.created(
93
- res,
94
- user,
95
- "User created successfully"
96
- );
139
+ app.post('/users', response.asyncHandler(async (req, res) => {
140
+ const user = await User.create({
141
+ name: req.body.name,
142
+ email: req.body.email,
143
+ });
144
+
145
+ res.created(user, 'User created successfully');
146
+ }));
147
+ ```
148
+
149
+ ### Using Direct API
150
+
151
+ ```js
152
+ app.post('/users', async (req, res) => {
153
+ const user = await User.create(req.body);
154
+
155
+ response.created(res, user, 'User created successfully');
97
156
  });
98
157
  ```
99
158
 
100
- ---
159
+ ### Syntax
160
+
161
+ **Middleware API:**
162
+ ```js
163
+ res.created(data, message)
164
+ ```
101
165
 
102
- ## Output
166
+ **Direct API:**
167
+ ```js
168
+ response.created(res, data, message)
169
+ ```
170
+
171
+ ### Parameters
172
+
173
+ | Parameter | Type | Required | Default | Description |
174
+ |-----------|------|----------|---------|-------------|
175
+ | `data` | any | No | `null` | Created resource data |
176
+ | `message` | string | No | `'Created Successfully'` | Success message |
177
+
178
+ ### Response Structure
103
179
 
104
180
  ```json
105
181
  {
@@ -107,27 +183,216 @@ app.post("/users", (req, res) => {
107
183
  "message": "User created successfully",
108
184
  "data": {
109
185
  "id": 1,
110
- "name": "John"
186
+ "name": "John Doe",
187
+ "email": "john@example.com"
111
188
  }
112
189
  }
113
190
  ```
114
191
 
192
+ **Status Code:** `201 Created`
193
+
194
+ ---
195
+
196
+ ## Examples
197
+
198
+ ### Example 1: Fetching User Profile
199
+
200
+ ```js
201
+ app.get('/profile', response.asyncHandler(async (req, res) => {
202
+ const user = await User.findById(req.user.id);
203
+
204
+ res.success(user, 'Profile fetched successfully');
205
+ }));
206
+ ```
207
+
208
+ ### Example 2: Creating a Blog Post
209
+
210
+ ```js
211
+ app.post('/posts', response.asyncHandler(async (req, res) => {
212
+ const { title, content } = req.body;
213
+
214
+ const post = await Post.create({
215
+ title,
216
+ content,
217
+ author: req.user.id,
218
+ });
219
+
220
+ res.created(post, 'Post created successfully');
221
+ }));
222
+ ```
223
+
224
+ ### Example 3: Updating a Resource
225
+
226
+ ```js
227
+ app.put('/users/:id', response.asyncHandler(async (req, res) => {
228
+ const user = await User.findByIdAndUpdate(
229
+ req.params.id,
230
+ req.body,
231
+ { new: true }
232
+ );
233
+
234
+ res.success(user, 'User updated successfully');
235
+ }));
236
+ ```
237
+
238
+ ### Example 4: Success Without Data
239
+
240
+ ```js
241
+ app.post('/logout', (req, res) => {
242
+ req.session.destroy();
243
+
244
+ res.success(null, 'Logged out successfully');
245
+ });
246
+ ```
247
+
248
+ **Response:**
249
+ ```json
250
+ {
251
+ "success": true,
252
+ "message": "Logged out successfully",
253
+ "data": null
254
+ }
255
+ ```
256
+
257
+ ### Example 5: Custom Response Keys
258
+
259
+ ```js
260
+ response.configure({
261
+ successKey: 'status',
262
+ dataKey: 'result',
263
+ messageKey: 'msg',
264
+ });
265
+
266
+ res.success({ count: 10 }, 'Data retrieved');
267
+ ```
268
+
269
+ **Response:**
270
+ ```json
271
+ {
272
+ "status": true,
273
+ "msg": "Data retrieved",
274
+ "result": { "count": 10 }
275
+ }
276
+ ```
277
+
115
278
  ---
116
279
 
117
- ## Status Code
280
+ ## Best Practices
118
281
 
119
- ```http
120
- 201 Created
282
+ ### ✅ Do's
283
+
284
+ - Use `success()` for GET requests and general operations
285
+ - Use `created()` for POST requests that create resources
286
+ - Provide meaningful success messages
287
+ - Use consistent message patterns across your API
288
+ - Include relevant data in the response
289
+
290
+ ```js
291
+ // ✅ Good
292
+ res.success(user, 'User fetched successfully');
293
+ res.created(post, 'Post created successfully');
294
+ ```
295
+
296
+ ### ❌ Don'ts
297
+
298
+ - Don't use `success()` after creating resources (use `created()`)
299
+ - Don't send empty or generic messages
300
+ - Don't include sensitive data in responses
301
+ - Don't manually write JSON if using Response Kit
302
+
303
+ ```js
304
+ // ❌ Bad
305
+ response.success(res, user, ''); // Empty message
306
+ res.success({ password: 'secret123' }); // Sensitive data
307
+ res.json({ success: true, data: user }); // Manual JSON
121
308
  ```
122
309
 
123
310
  ---
124
311
 
125
- # Best Practices
312
+ ## TypeScript
126
313
 
127
- Use success() for fetching data
314
+ Response Kit includes full TypeScript support:
128
315
 
129
- ✅ Use created() for creating resources
316
+ ```typescript
317
+ import response, { ExtendedResponse } from 'response-kit';
318
+ import { Request } from 'express';
319
+
320
+ interface User {
321
+ id: number;
322
+ name: string;
323
+ email: string;
324
+ }
325
+
326
+ app.get('/users/:id', async (req: Request, res: ExtendedResponse) => {
327
+ const user: User = await User.findById(req.params.id);
328
+
329
+ res.success(user, 'User fetched successfully');
330
+ });
331
+ ```
332
+
333
+ ---
334
+
335
+ ## Advanced Usage
336
+
337
+ ### Conditional Success Responses
338
+
339
+ ```js
340
+ app.get('/search', response.asyncHandler(async (req, res) => {
341
+ const results = await searchDatabase(req.query.q);
342
+
343
+ if (results.length === 0) {
344
+ return res.success([], 'No results found');
345
+ }
346
+
347
+ res.success(results, `Found ${results.length} results`);
348
+ }));
349
+ ```
350
+
351
+ ### Success with Additional Metadata
352
+
353
+ ```js
354
+ response.configure({
355
+ includeMeta: true,
356
+ });
357
+
358
+ res.success(users, 'Users fetched');
359
+ ```
360
+
361
+ **Response:**
362
+ ```json
363
+ {
364
+ "success": true,
365
+ "message": "Users fetched",
366
+ "data": [...],
367
+ "meta": {
368
+ "method": "GET",
369
+ "path": "/users"
370
+ }
371
+ }
372
+ ```
373
+
374
+ ### Nested Data Structures
375
+
376
+ ```js
377
+ app.get('/dashboard', response.asyncHandler(async (req, res) => {
378
+ const data = {
379
+ stats: {
380
+ users: 150,
381
+ posts: 320,
382
+ comments: 1240
383
+ },
384
+ recentActivity: [...],
385
+ notifications: [...]
386
+ };
387
+
388
+ res.success(data, 'Dashboard data fetched');
389
+ }));
390
+ ```
391
+
392
+ ---
130
393
 
131
- Don't use success() after creating resources
394
+ ## Related
132
395
 
133
- Don't manually write JSON responses if using API Response Kit
396
+ - [Error Responses](./error-response.md)
397
+ - [Pagination](./pagination.md)
398
+ - [Getting Started](./getting-started.md)
package/index.d.ts CHANGED
@@ -1,56 +1,158 @@
1
+ import { Request, Response, NextFunction, RequestHandler } from 'express';
2
+
3
+ /**
4
+ * Configuration Options
5
+ */
6
+ export interface ResponseConfig {
7
+ successKey?: string;
8
+ dataKey?: string;
9
+ messageKey?: string;
10
+ errorKey?: string;
11
+ includeTimestamp?: boolean;
12
+ includeRequestId?: boolean;
13
+ includeMeta?: boolean;
14
+ timestampKey?: string;
15
+ requestIdKey?: string;
16
+ metaKey?: string;
17
+ }
18
+
19
+ /**
20
+ * Extended Express Response with response helpers
21
+ */
22
+ export interface ExtendedResponse extends Response {
23
+ success(data?: any, message?: string, statusCode?: number): Response;
24
+ created(data?: any, message?: string): Response;
25
+ badRequest(message?: string): Response;
26
+ unauthorized(message?: string): Response;
27
+ forbidden(message?: string): Response;
28
+ notFound(message?: string): Response;
29
+ conflict(message?: string): Response;
30
+ internalError(message?: string): Response;
31
+ validationError(errors?: object, message?: string): Response;
32
+ paginate(data: any[], page: number, limit: number, total: number): Response;
33
+ }
34
+
35
+ /**
36
+ * V1 API - Backward Compatible Functions
37
+ */
1
38
  export function success(
2
- res: any,
39
+ res: Response,
3
40
  data?: any,
4
41
  message?: string,
5
42
  statusCode?: number
6
- ): any;
43
+ ): Response;
7
44
 
8
45
  export function created(
9
- res: any,
46
+ res: Response,
10
47
  data?: any,
11
48
  message?: string
12
- ): any;
49
+ ): Response;
13
50
 
14
51
  export function badRequest(
15
- res: any,
52
+ res: Response,
16
53
  message?: string
17
- ): any;
54
+ ): Response;
18
55
 
19
56
  export function unauthorized(
20
- res: any,
57
+ res: Response,
21
58
  message?: string
22
- ): any;
59
+ ): Response;
23
60
 
24
61
  export function forbidden(
25
- res: any,
62
+ res: Response,
26
63
  message?: string
27
- ): any;
64
+ ): Response;
28
65
 
29
66
  export function notFound(
30
- res: any,
67
+ res: Response,
31
68
  message?: string
32
- ): any;
69
+ ): Response;
33
70
 
34
71
  export function conflict(
35
- res: any,
72
+ res: Response,
36
73
  message?: string
37
- ): any;
74
+ ): Response;
38
75
 
39
76
  export function internalError(
40
- res: any,
77
+ res: Response,
41
78
  message?: string
42
- ): any;
79
+ ): Response;
43
80
 
44
81
  export function validationError(
45
- res: any,
82
+ res: Response,
46
83
  errors?: object,
47
84
  message?: string
48
- ): any;
85
+ ): Response;
49
86
 
50
87
  export function paginate(
51
- res: any,
88
+ res: Response,
52
89
  data: any[],
53
90
  page: number,
54
91
  limit: number,
55
92
  total: number
56
- ): any;
93
+ ): Response;
94
+
95
+ /**
96
+ * V2 API - New Features
97
+ */
98
+
99
+ /**
100
+ * Configure global response settings
101
+ */
102
+ export function configure(options: ResponseConfig): void;
103
+
104
+ /**
105
+ * Get current configuration
106
+ */
107
+ export function getConfig(): ResponseConfig;
108
+
109
+ /**
110
+ * Reset configuration to defaults
111
+ */
112
+ export function resetConfig(): void;
113
+
114
+ /**
115
+ * Express middleware that attaches response helpers to res object
116
+ */
117
+ export function middleware(): (
118
+ req: Request,
119
+ res: Response,
120
+ next: NextFunction
121
+ ) => void;
122
+
123
+ /**
124
+ * Async handler wrapper for Express routes
125
+ */
126
+ export function asyncHandler<T = any>(
127
+ fn: (
128
+ req: Request,
129
+ res: ExtendedResponse,
130
+ next: NextFunction
131
+ ) => Promise<T>
132
+ ): RequestHandler;
133
+
134
+ /**
135
+ * Default export with all functions
136
+ */
137
+ declare const response: {
138
+ // V1 API
139
+ success: typeof success;
140
+ created: typeof created;
141
+ badRequest: typeof badRequest;
142
+ unauthorized: typeof unauthorized;
143
+ forbidden: typeof forbidden;
144
+ notFound: typeof notFound;
145
+ conflict: typeof conflict;
146
+ internalError: typeof internalError;
147
+ validationError: typeof validationError;
148
+ paginate: typeof paginate;
149
+
150
+ // V2 API
151
+ configure: typeof configure;
152
+ getConfig: typeof getConfig;
153
+ resetConfig: typeof resetConfig;
154
+ middleware: typeof middleware;
155
+ asyncHandler: typeof asyncHandler;
156
+ };
157
+
158
+ export default response;