@ooneex/http-status 0.0.1 → 0.0.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.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @ooneex/http-status
2
2
 
3
- A comprehensive TypeScript/JavaScript library for working with HTTP status codes. This package provides all standard HTTP status codes with their corresponding text messages and utility methods to categorize and work with different status code types.
3
+ A comprehensive HTTP status codes library providing TypeScript enums, constants, and helper utilities for status classification. This package offers type-safe access to all standard HTTP status codes (1xx-5xx) with methods to categorize responses by type.
4
4
 
5
5
  ![Browser](https://img.shields.io/badge/Browser-Compatible-green?style=flat-square&logo=googlechrome)
6
6
  ![Bun](https://img.shields.io/badge/Bun-Compatible-orange?style=flat-square&logo=bun)
@@ -11,21 +11,17 @@ A comprehensive TypeScript/JavaScript library for working with HTTP status codes
11
11
 
12
12
  ## Features
13
13
 
14
- ✅ **Complete Status Code Collection** - All standard HTTP status codes from 1xx to 5xx
14
+ ✅ **Complete Status Codes** - All standard HTTP status codes from 1xx to 5xx
15
15
 
16
- ✅ **Status Text Mapping** - Corresponding text messages for all status codes
16
+ ✅ **Status Text** - Human-readable status text for all codes
17
17
 
18
- ✅ **Type-Safe** - Full TypeScript support with proper type definitions
19
-
20
- ✅ **Category Detection** - Methods to identify status code categories (informational, success, redirect, error)
21
-
22
- ✅ **Lightweight** - No external dependencies required
18
+ ✅ **Classification Methods** - Easily check if a status is informational, success, redirect, or error
23
19
 
24
- ✅ **Cross-Platform** - Works in Browser, Node.js, Bun, and Deno
20
+ ✅ **Type-Safe** - Full TypeScript support with proper type definitions
25
21
 
26
- ✅ **Standards Compliant** - Based on official HTTP status code specifications
22
+ ✅ **Zero Dependencies** - Lightweight with no external dependencies
27
23
 
28
- ✅ **Easy Integration** - Simple API for common HTTP status operations
24
+ ✅ **Static Access** - Access codes and text via static properties
29
25
 
30
26
  ## Installation
31
27
 
@@ -51,443 +47,327 @@ npm install @ooneex/http-status
51
47
 
52
48
  ## Usage
53
49
 
54
- ### Basic Usage
50
+ ### Accessing Status Codes
55
51
 
56
52
  ```typescript
57
- import { Status } from '@ooneex/http-status';
58
-
59
- const status = new Status();
53
+ import { HttpStatus } from '@ooneex/http-status';
60
54
 
61
55
  // Access status codes
62
- console.log(Status.Code.OK); // 200
63
- console.log(Status.Code.NotFound); // 404
64
- console.log(Status.Code.InternalServerError); // 500
65
-
66
- // Access status text
67
- console.log(Status.Text[200]); // "OK"
68
- console.log(Status.Text[404]); // "Not Found"
69
- console.log(Status.Text[500]); // "Internal Server Error"
70
-
71
- // Or use the exported constants directly
72
- console.log(Status.Code.OK); // 200
73
- console.log(Status.Text[Status.Code.NotFound]); // "Not Found"
56
+ console.log(HttpStatus.Code.OK); // 200
57
+ console.log(HttpStatus.Code.Created); // 201
58
+ console.log(HttpStatus.Code.BadRequest); // 400
59
+ console.log(HttpStatus.Code.NotFound); // 404
60
+ console.log(HttpStatus.Code.InternalServerError); // 500
74
61
  ```
75
62
 
76
- ### Status Code Category Detection
63
+ ### Accessing Status Text
77
64
 
78
65
  ```typescript
79
- import { Status } from '@ooneex/http-status';
80
-
81
- const status = new Status();
66
+ import { HttpStatus } from '@ooneex/http-status';
82
67
 
83
- // Check if status code is successful (2xx)
84
- console.log(status.isSuccessful(Status.Code.OK)); // true
85
- console.log(status.isSuccessful(Status.Code.Created)); // true
86
- console.log(status.isSuccessful(Status.Code.NotFound)); // false
87
-
88
- // Check if status code is an error (4xx or 5xx)
89
- console.log(status.isError(Status.Code.BadRequest)); // true
90
- console.log(status.isError(Status.Code.InternalServerError)); // true
91
- console.log(status.isError(Status.Code.OK)); // false
92
-
93
- // Check specific error types
94
- console.log(status.isClientError(Status.Code.BadRequest)); // true
95
- console.log(status.isClientError(Status.Code.NotFound)); // true
96
- console.log(status.isServerError(Status.Code.InternalServerError)); // true
97
- console.log(status.isServerError(Status.Code.BadGateway)); // true
98
-
99
- // Check for redirects (3xx)
100
- console.log(status.isRedirect(Status.Code.MovedPermanently)); // true
101
- console.log(status.isRedirect(Status.Code.Found)); // true
102
-
103
- // Check for informational responses (1xx)
104
- console.log(status.isInformational(Status.Code.Continue)); // true
105
- console.log(status.isInformational(Status.Code.SwitchingProtocols)); // true
68
+ // Access status text by code
69
+ console.log(HttpStatus.Text[200]); // "OK"
70
+ console.log(HttpStatus.Text[201]); // "Created"
71
+ console.log(HttpStatus.Text[404]); // "Not Found"
72
+ console.log(HttpStatus.Text[500]); // "Internal Server Error"
106
73
  ```
107
74
 
108
- ### Express.js Integration Example
75
+ ### Checking Status Categories
109
76
 
110
77
  ```typescript
111
- import express from 'express';
112
- import { Status } from '@ooneex/http-status';
113
-
114
- const app = express();
115
- const status = new Status();
116
-
117
- app.get('/api/users/:id', (req, res) => {
118
- const user = getUserById(req.params.id);
119
-
120
- if (!user) {
121
- return res.status(Status.Code.NotFound).json({
122
- error: Status.Text[Status.Code.NotFound],
123
- message: 'User not found'
124
- });
125
- }
126
-
127
- res.status(Status.Code.OK).json(user);
128
- });
129
-
130
- app.use((error, req, res, next) => {
131
- const statusCode = Status.Code.InternalServerError;
132
-
133
- console.log(`Error ${statusCode}: ${Status.Text[statusCode]}`);
134
- console.log(`Is Server Error: ${status.isServerError(statusCode)}`);
135
-
136
- res.status(statusCode).json({
137
- error: Status.Text[statusCode]
138
- });
139
- });
78
+ import { HttpStatus } from '@ooneex/http-status';
79
+
80
+ const status = new HttpStatus();
81
+
82
+ // Check if status is informational (1xx)
83
+ console.log(status.isInformational(100)); // true
84
+ console.log(status.isInformational(200)); // false
85
+
86
+ // Check if status is successful (2xx)
87
+ console.log(status.isSuccessful(200)); // true
88
+ console.log(status.isSuccessful(201)); // true
89
+ console.log(status.isSuccessful(404)); // false
90
+
91
+ // Check if status is redirect (3xx)
92
+ console.log(status.isRedirect(301)); // true
93
+ console.log(status.isRedirect(302)); // true
94
+ console.log(status.isRedirect(200)); // false
95
+
96
+ // Check if status is client error (4xx)
97
+ console.log(status.isClientError(400)); // true
98
+ console.log(status.isClientError(404)); // true
99
+ console.log(status.isClientError(500)); // false
100
+
101
+ // Check if status is server error (5xx)
102
+ console.log(status.isServerError(500)); // true
103
+ console.log(status.isServerError(503)); // true
104
+ console.log(status.isServerError(404)); // false
105
+
106
+ // Check if status is any error (4xx or 5xx)
107
+ console.log(status.isError(400)); // true
108
+ console.log(status.isError(500)); // true
109
+ console.log(status.isError(200)); // false
140
110
  ```
141
111
 
142
- ### Fetch API Integration Example
112
+ ### Using in Response Handlers
143
113
 
144
114
  ```typescript
145
- import { Status } from '@ooneex/http-status';
146
-
147
- const status = new Status();
148
-
149
- async function apiCall(url: string) {
150
- try {
151
- const response = await fetch(url);
115
+ import { HttpStatus, type StatusCodeType } from '@ooneex/http-status';
152
116
 
153
- console.log(`Response status: ${response.status} - ${Status.Text[response.status]}`);
154
-
155
- if (status.isSuccessful(response.status)) {
156
- return await response.json();
157
- }
158
-
159
- if (status.isClientError(response.status)) {
160
- throw new Error(`Client error: ${Status.Text[response.status]}`);
161
- }
162
-
163
- if (status.isServerError(response.status)) {
164
- throw new Error(`Server error: ${Status.Text[response.status]}`);
165
- }
166
-
167
- if (status.isRedirect(response.status)) {
168
- console.log('Redirect response received');
169
- // Handle redirect logic
170
- }
171
-
172
- } catch (error) {
173
- console.error('API call failed:', error);
117
+ function handleResponse(statusCode: StatusCodeType): string {
118
+ const status = new HttpStatus();
119
+
120
+ if (status.isSuccessful(statusCode)) {
121
+ return 'Request completed successfully';
174
122
  }
123
+
124
+ if (status.isClientError(statusCode)) {
125
+ return `Client error: ${HttpStatus.Text[statusCode]}`;
126
+ }
127
+
128
+ if (status.isServerError(statusCode)) {
129
+ return `Server error: ${HttpStatus.Text[statusCode]}`;
130
+ }
131
+
132
+ return 'Unknown status';
175
133
  }
134
+
135
+ console.log(handleResponse(HttpStatus.Code.OK)); // "Request completed successfully"
136
+ console.log(handleResponse(HttpStatus.Code.NotFound)); // "Client error: Not Found"
176
137
  ```
177
138
 
178
139
  ## API Reference
179
140
 
180
- ### `Status` Class
181
-
182
- The main class providing HTTP status code utility methods.
141
+ ### Classes
183
142
 
184
- #### Static Properties
143
+ #### `HttpStatus`
185
144
 
186
- ##### `Status.Code`
187
- Object containing all HTTP status codes as constants.
145
+ Main class providing HTTP status code utilities.
188
146
 
189
- **Example:**
190
- ```typescript
191
- Status.Code.OK; // 200
192
- Status.Code.NotFound; // 404
193
- Status.Code.InternalServerError; // 500
194
- ```
147
+ **Static Properties:**
195
148
 
196
- ##### `Status.Text`
197
- Object mapping status codes to their text descriptions.
149
+ ##### `HttpStatus.Code`
198
150
 
199
- **Example:**
200
- ```typescript
201
- Status.Text[200]; // "OK"
202
- Status.Text[404]; // "Not Found"
203
- Status.Text[500]; // "Internal Server Error"
204
- ```
151
+ Object containing all HTTP status codes as named constants.
205
152
 
206
- #### Methods
153
+ | Property | Value | Description |
154
+ |----------|-------|-------------|
155
+ | `Continue` | 100 | Continue |
156
+ | `SwitchingProtocols` | 101 | Switching Protocols |
157
+ | `Processing` | 102 | Processing |
158
+ | `EarlyHints` | 103 | Early Hints |
159
+ | `OK` | 200 | OK |
160
+ | `Created` | 201 | Created |
161
+ | `Accepted` | 202 | Accepted |
162
+ | `NonAuthoritativeInfo` | 203 | Non-Authoritative Information |
163
+ | `NoContent` | 204 | No Content |
164
+ | `ResetContent` | 205 | Reset Content |
165
+ | `PartialContent` | 206 | Partial Content |
166
+ | `MultiStatus` | 207 | Multi-Status |
167
+ | `AlreadyReported` | 208 | Already Reported |
168
+ | `IMUsed` | 226 | IM Used |
169
+ | `MultipleChoices` | 300 | Multiple Choices |
170
+ | `MovedPermanently` | 301 | Moved Permanently |
171
+ | `Found` | 302 | Found |
172
+ | `SeeOther` | 303 | See Other |
173
+ | `NotModified` | 304 | Not Modified |
174
+ | `UseProxy` | 305 | Use Proxy |
175
+ | `TemporaryRedirect` | 307 | Temporary Redirect |
176
+ | `PermanentRedirect` | 308 | Permanent Redirect |
177
+ | `BadRequest` | 400 | Bad Request |
178
+ | `Unauthorized` | 401 | Unauthorized |
179
+ | `PaymentRequired` | 402 | Payment Required |
180
+ | `Forbidden` | 403 | Forbidden |
181
+ | `NotFound` | 404 | Not Found |
182
+ | `MethodNotAllowed` | 405 | Method Not Allowed |
183
+ | `NotAcceptable` | 406 | Not Acceptable |
184
+ | `ProxyAuthRequired` | 407 | Proxy Authentication Required |
185
+ | `RequestTimeout` | 408 | Request Timeout |
186
+ | `Conflict` | 409 | Conflict |
187
+ | `Gone` | 410 | Gone |
188
+ | `LengthRequired` | 411 | Length Required |
189
+ | `PreconditionFailed` | 412 | Precondition Failed |
190
+ | `ContentTooLarge` | 413 | Content Too Large |
191
+ | `URITooLong` | 414 | URI Too Long |
192
+ | `UnsupportedMediaType` | 415 | Unsupported Media Type |
193
+ | `RangeNotSatisfiable` | 416 | Range Not Satisfiable |
194
+ | `ExpectationFailed` | 417 | Expectation Failed |
195
+ | `Teapot` | 418 | I'm a teapot |
196
+ | `MisdirectedRequest` | 421 | Misdirected Request |
197
+ | `UnprocessableEntity` | 422 | Unprocessable Entity |
198
+ | `Locked` | 423 | Locked |
199
+ | `FailedDependency` | 424 | Failed Dependency |
200
+ | `TooEarly` | 425 | Too Early |
201
+ | `UpgradeRequired` | 426 | Upgrade Required |
202
+ | `PreconditionRequired` | 428 | Precondition Required |
203
+ | `TooManyRequests` | 429 | Too Many Requests |
204
+ | `RequestHeaderFieldsTooLarge` | 431 | Request Header Fields Too Large |
205
+ | `UnavailableForLegalReasons` | 451 | Unavailable For Legal Reasons |
206
+ | `InternalServerError` | 500 | Internal Server Error |
207
+ | `NotImplemented` | 501 | Not Implemented |
208
+ | `BadGateway` | 502 | Bad Gateway |
209
+ | `ServiceUnavailable` | 503 | Service Unavailable |
210
+ | `GatewayTimeout` | 504 | Gateway Timeout |
211
+ | `HTTPVersionNotSupported` | 505 | HTTP Version Not Supported |
212
+ | `VariantAlsoNegotiates` | 506 | Variant Also Negotiates |
213
+ | `InsufficientStorage` | 507 | Insufficient Storage |
214
+ | `LoopDetected` | 508 | Loop Detected |
215
+ | `NotExtended` | 510 | Not Extended |
216
+ | `NetworkAuthenticationRequired` | 511 | Network Authentication Required |
217
+
218
+ ##### `HttpStatus.Text`
219
+
220
+ Object mapping status codes to their human-readable text descriptions.
221
+
222
+ **Instance Methods:**
207
223
 
208
224
  ##### `isInformational(code: StatusCodeType): boolean`
209
- Checks if a status code is informational (1xx).
210
225
 
211
- **Parameters:**
212
- - `code` - The HTTP status code to check
213
-
214
- **Returns:** `true` if the status code is in the 1xx range
215
-
216
- **Example:**
217
- ```typescript
218
- status.isInformational(100); // true (Continue)
219
- status.isInformational(101); // true (Switching Protocols)
220
- status.isInformational(200); // false (OK)
221
- ```
226
+ Checks if the status code is informational (100-199).
222
227
 
223
228
  ##### `isSuccessful(code: StatusCodeType): boolean`
224
- Checks if a status code indicates success (2xx).
225
229
 
226
- **Example:**
227
- ```typescript
228
- status.isSuccessful(200); // true (OK)
229
- status.isSuccessful(201); // true (Created)
230
- status.isSuccessful(204); // true (No Content)
231
- status.isSuccessful(404); // false (Not Found)
232
- ```
230
+ Checks if the status code is successful (200-299).
233
231
 
234
232
  ##### `isRedirect(code: StatusCodeType): boolean`
235
- Checks if a status code indicates a redirect (3xx).
236
233
 
237
- **Example:**
238
- ```typescript
239
- status.isRedirect(301); // true (Moved Permanently)
240
- status.isRedirect(302); // true (Found)
241
- status.isRedirect(304); // true (Not Modified)
242
- status.isRedirect(200); // false (OK)
243
- ```
234
+ Checks if the status code is a redirect (300-399).
244
235
 
245
236
  ##### `isClientError(code: StatusCodeType): boolean`
246
- Checks if a status code indicates a client error (4xx).
247
237
 
248
- **Example:**
249
- ```typescript
250
- status.isClientError(400); // true (Bad Request)
251
- status.isClientError(404); // true (Not Found)
252
- status.isClientError(403); // true (Forbidden)
253
- status.isClientError(500); // false (Internal Server Error)
254
- ```
238
+ Checks if the status code is a client error (400-499).
255
239
 
256
240
  ##### `isServerError(code: StatusCodeType): boolean`
257
- Checks if a status code indicates a server error (5xx).
258
241
 
259
- **Example:**
260
- ```typescript
261
- status.isServerError(500); // true (Internal Server Error)
262
- status.isServerError(502); // true (Bad Gateway)
263
- status.isServerError(503); // true (Service Unavailable)
264
- status.isServerError(404); // false (Not Found)
265
- ```
242
+ Checks if the status code is a server error (500-599).
266
243
 
267
244
  ##### `isError(code: StatusCodeType): boolean`
268
- Checks if a status code indicates any error (4xx or 5xx).
269
245
 
270
- **Example:**
271
- ```typescript
272
- status.isError(400); // true (Bad Request - client error)
273
- status.isError(500); // true (Internal Server Error - server error)
274
- status.isError(200); // false (OK - success)
275
- status.isError(301); // false (Moved Permanently - redirect)
276
- ```
277
-
278
- ### Constants
279
-
280
- #### `Status.Code`
281
- Object containing all HTTP status codes as named constants.
282
-
283
- **Available Status Codes:**
284
-
285
- **1xx Informational:**
286
- - `Continue` (100)
287
- - `SwitchingProtocols` (101)
288
- - `Processing` (102)
289
- - `EarlyHints` (103)
290
-
291
- **2xx Success:**
292
- - `OK` (200)
293
- - `Created` (201)
294
- - `Accepted` (202)
295
- - `NonAuthoritativeInfo` (203)
296
- - `NoContent` (204)
297
- - `ResetContent` (205)
298
- - `PartialContent` (206)
299
- - `MultiStatus` (207)
300
- - `AlreadyReported` (208)
301
- - `IMUsed` (226)
302
-
303
- **3xx Redirection:**
304
- - `MultipleChoices` (300)
305
- - `MovedPermanently` (301)
306
- - `Found` (302)
307
- - `SeeOther` (303)
308
- - `NotModified` (304)
309
- - `UseProxy` (305)
310
- - `TemporaryRedirect` (307)
311
- - `PermanentRedirect` (308)
312
-
313
- **4xx Client Error:**
314
- - `BadRequest` (400)
315
- - `Unauthorized` (401)
316
- - `PaymentRequired` (402)
317
- - `Forbidden` (403)
318
- - `NotFound` (404)
319
- - `MethodNotAllowed` (405)
320
- - `NotAcceptable` (406)
321
- - `ProxyAuthRequired` (407)
322
- - `RequestTimeout` (408)
323
- - `Conflict` (409)
324
- - `Gone` (410)
325
- - `LengthRequired` (411)
326
- - `PreconditionFailed` (412)
327
- - `ContentTooLarge` (413)
328
- - `URITooLong` (414)
329
- - `UnsupportedMediaType` (415)
330
- - `RangeNotSatisfiable` (416)
331
- - `ExpectationFailed` (417)
332
- - `Teapot` (418)
333
- - `MisdirectedRequest` (421)
334
- - `UnprocessableEntity` (422)
335
- - `Locked` (423)
336
- - `FailedDependency` (424)
337
- - `TooEarly` (425)
338
- - `UpgradeRequired` (426)
339
- - `PreconditionRequired` (428)
340
- - `TooManyRequests` (429)
341
- - `RequestHeaderFieldsTooLarge` (431)
342
- - `UnavailableForLegalReasons` (451)
343
-
344
- **5xx Server Error:**
345
- - `InternalServerError` (500)
346
- - `NotImplemented` (501)
347
- - `BadGateway` (502)
348
- - `ServiceUnavailable` (503)
349
- - `GatewayTimeout` (504)
350
- - `HTTPVersionNotSupported` (505)
351
- - `VariantAlsoNegotiates` (506)
352
- - `InsufficientStorage` (507)
353
- - `LoopDetected` (508)
354
- - `NotExtended` (510)
355
- - `NetworkAuthenticationRequired` (511)
356
-
357
- #### `Status.Text`
358
- Object mapping status codes to their corresponding text descriptions.
359
-
360
- **Example:**
361
- ```typescript
362
- import { Status } from '@ooneex/http-status';
363
-
364
- Status.Text[Status.Code.OK]; // "OK"
365
- Status.Text[Status.Code.NotFound]; // "Not Found"
366
- Status.Text[Status.Code.InternalServerError]; // "Internal Server Error"
367
- Status.Text[Status.Code.Teapot]; // "I'm a teapot"
368
- ```
246
+ Checks if the status code is any error (400-599).
369
247
 
370
248
  ### Types
371
249
 
372
250
  #### `StatusCodeType`
373
- TypeScript type representing all valid HTTP status codes.
374
251
 
375
- **Example:**
376
- ```typescript
377
- import { StatusCodeType } from '@ooneex/http-status';
252
+ Union type of all valid HTTP status code numbers.
378
253
 
379
- const code: StatusCodeType = 200; // Type-safe
380
- const handler = (statusCode: StatusCodeType) => {
381
- // Handle status code
382
- };
254
+ ```typescript
255
+ type StatusCodeType = 100 | 101 | 102 | 103 | 200 | 201 | ... | 511;
383
256
  ```
384
257
 
385
258
  #### `StatusTextType`
386
- TypeScript type representing all valid HTTP status text messages.
387
259
 
388
- **Example:**
389
- ```typescript
390
- import { StatusTextType } from '@ooneex/http-status';
260
+ Union type of all valid HTTP status text strings.
391
261
 
392
- const message: StatusTextType = "OK"; // Type-safe
262
+ ```typescript
263
+ type StatusTextType = "OK" | "Created" | "Not Found" | "Internal Server Error" | ...;
393
264
  ```
394
265
 
395
- ### Interface
266
+ ### Interfaces
396
267
 
397
- #### `IStatus`
398
- Interface defining all available status code detection methods.
268
+ #### `IHttpStatus`
399
269
 
400
- **Example:**
401
270
  ```typescript
402
- import { IStatus } from '@ooneex/http-status';
403
-
404
- class CustomStatusHandler implements IStatus {
405
- isInformational(code: StatusCodeType): boolean {
406
- // Custom implementation
407
- return code >= 100 && code < 200;
408
- }
409
-
410
- isSuccessful(code: StatusCodeType): boolean {
411
- // Custom implementation
412
- return code >= 200 && code < 300;
413
- }
414
-
415
- // ... implement other required methods
271
+ interface IHttpStatus {
272
+ isInformational: (code: StatusCodeType) => boolean;
273
+ isSuccessful: (code: StatusCodeType) => boolean;
274
+ isRedirect: (code: StatusCodeType) => boolean;
275
+ isClientError: (code: StatusCodeType) => boolean;
276
+ isServerError: (code: StatusCodeType) => boolean;
277
+ isError: (code: StatusCodeType) => boolean;
416
278
  }
417
279
  ```
418
280
 
419
- ## Common Use Cases
281
+ ## Advanced Usage
420
282
 
421
- ### API Response Handling
283
+ ### Building API Responses
422
284
 
423
285
  ```typescript
424
- import { Status } from '@ooneex/http-status';
286
+ import { HttpStatus, type StatusCodeType } from '@ooneex/http-status';
287
+
288
+ interface ApiResponse<T> {
289
+ success: boolean;
290
+ status: StatusCodeType;
291
+ statusText: string;
292
+ data?: T;
293
+ error?: string;
294
+ }
425
295
 
426
- const status = new Status();
296
+ function createResponse<T>(
297
+ code: StatusCodeType,
298
+ data?: T,
299
+ error?: string
300
+ ): ApiResponse<T> {
301
+ const status = new HttpStatus();
302
+
303
+ return {
304
+ success: status.isSuccessful(code),
305
+ status: code,
306
+ statusText: HttpStatus.Text[code],
307
+ ...(data && { data }),
308
+ ...(error && { error })
309
+ };
310
+ }
427
311
 
428
- function handleApiResponse(statusCode: number, data: any) {
429
- if (status.isSuccessful(statusCode)) {
430
- console.log('Success:', data);
431
- return { success: true, data };
432
- }
312
+ // Success response
313
+ const successResponse = createResponse(HttpStatus.Code.OK, { user: { id: 1 } });
314
+ // { success: true, status: 200, statusText: "OK", data: { user: { id: 1 } } }
433
315
 
434
- if (status.isClientError(statusCode)) {
435
- console.error('Client Error:', Status.Text[statusCode]);
436
- return { success: false, error: 'Client error occurred' };
437
- }
316
+ // Error response
317
+ const errorResponse = createResponse(HttpStatus.Code.NotFound, undefined, 'User not found');
318
+ // { success: false, status: 404, statusText: "Not Found", error: "User not found" }
319
+ ```
438
320
 
439
- if (status.isServerError(statusCode)) {
440
- console.error('Server Error:', Status.Text[statusCode]);
441
- return { success: false, error: 'Server error occurred' };
442
- }
321
+ ### Integration with Ooneex Framework
443
322
 
444
- if (status.isRedirect(statusCode)) {
445
- console.log('Redirect:', Status.Text[statusCode]);
446
- return { success: true, redirect: true };
323
+ ```typescript
324
+ import { HttpStatus } from '@ooneex/http-status';
325
+ import { HttpResponse } from '@ooneex/http-response';
326
+ import type { IController, ContextType } from '@ooneex/controller';
327
+
328
+ class UserController implements IController {
329
+ public async index(context: ContextType) {
330
+ const user = await this.findUser(context.params.id);
331
+
332
+ if (!user) {
333
+ return context.response.json(
334
+ { error: 'User not found' },
335
+ HttpStatus.Code.NotFound
336
+ );
337
+ }
338
+
339
+ return context.response.json(
340
+ { user },
341
+ HttpStatus.Code.OK
342
+ );
447
343
  }
448
344
  }
449
345
  ```
450
346
 
451
- ### HTTP Client Wrapper
347
+ ### Middleware Status Checking
452
348
 
453
349
  ```typescript
454
- import { Status } from '@ooneex/http-status';
455
-
456
- class HttpClient {
457
- private status = new Status();
458
-
459
- async request(url: string, options?: RequestInit) {
460
- try {
461
- const response = await fetch(url, options);
462
-
463
- return {
464
- status: response.status,
465
- statusText: Status.Text[response.status],
466
- isSuccess: this.status.isSuccessful(response.status),
467
- isError: this.status.isError(response.status),
468
- isClientError: this.status.isClientError(response.status),
469
- isServerError: this.status.isServerError(response.status),
470
- data: response.ok ? await response.json() : null
471
- };
472
- } catch (error) {
473
- return {
474
- status: Status.Code.InternalServerError,
475
- statusText: Status.Text[Status.Code.InternalServerError],
476
- isSuccess: false,
477
- isError: true,
478
- isClientError: false,
479
- isServerError: true,
480
- data: null,
481
- error
482
- };
483
- }
350
+ import { HttpStatus } from '@ooneex/http-status';
351
+
352
+ function logResponseStatus(statusCode: number): void {
353
+ const status = new HttpStatus();
354
+ const text = HttpStatus.Text[statusCode as keyof typeof HttpStatus.Text];
355
+
356
+ if (status.isSuccessful(statusCode)) {
357
+ console.log(`✅ Success: ${statusCode} ${text}`);
358
+ } else if (status.isClientError(statusCode)) {
359
+ console.warn(`⚠️ Client Error: ${statusCode} ${text}`);
360
+ } else if (status.isServerError(statusCode)) {
361
+ console.error(`❌ Server Error: ${statusCode} ${text}`);
362
+ } else if (status.isRedirect(statusCode)) {
363
+ console.info(`↪️ Redirect: ${statusCode} ${text}`);
484
364
  }
485
365
  }
486
366
  ```
487
367
 
488
368
  ## License
489
369
 
490
- This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
370
+ This project is licensed under the MIT License - see the [LICENSE](./LICENSE) file for details.
491
371
 
492
372
  ## Contributing
493
373
 
@@ -497,7 +377,7 @@ Contributions are welcome! Please feel free to submit a Pull Request. For major
497
377
 
498
378
  1. Clone the repository
499
379
  2. Install dependencies: `bun install`
500
- 3. Run tests: `bun test`
380
+ 3. Run tests: `bun run test`
501
381
  4. Build the project: `bun run build`
502
382
 
503
383
  ### Guidelines
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@ooneex/http-status",
3
- "description": "",
4
- "version": "0.0.1",
3
+ "description": "Comprehensive HTTP status codes (1xx-5xx) with TypeScript enums and helper utilities for status classification",
4
+ "version": "0.0.3",
5
5
  "type": "module",
6
6
  "files": [
7
7
  "dist",
@@ -25,10 +25,7 @@
25
25
  "test": "bun test tests",
26
26
  "build": "bunup",
27
27
  "lint": "tsgo --noEmit && bunx biome lint",
28
- "publish:prod": "bun publish --tolerate-republish --access public",
29
- "publish:pack": "bun pm pack --destination ./dist",
30
- "publish:dry": "bun publish --dry-run"
28
+ "publish": "bun publish --tolerate-republish --access public"
31
29
  },
32
- "devDependencies": {},
33
- "peerDependencies": {}
30
+ "devDependencies": {}
34
31
  }
Binary file