@ooneex/http-response 0.0.1
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 +21 -0
- package/README.md +558 -0
- package/dist/index.d.ts +58 -0
- package/dist/index.js +3 -0
- package/dist/index.js.map +10 -0
- package/dist/ooneex-http-response-0.0.1.tgz +0 -0
- package/package.json +39 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Ooneex
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,558 @@
|
|
|
1
|
+
# @ooneex/http-response
|
|
2
|
+
|
|
3
|
+
A comprehensive TypeScript/JavaScript library for building HTTP responses in web applications. This package provides a fluent API for creating JSON responses, handling exceptions, managing redirects, and working with HTTP headers in a type-safe manner.
|
|
4
|
+
|
|
5
|
+

|
|
6
|
+

|
|
7
|
+

|
|
8
|
+

|
|
9
|
+

|
|
10
|
+

|
|
11
|
+
|
|
12
|
+
## Features
|
|
13
|
+
|
|
14
|
+
✅ **Fluent API** - Chain methods for easy response building
|
|
15
|
+
|
|
16
|
+
✅ **Type-Safe** - Full TypeScript support with generic types
|
|
17
|
+
|
|
18
|
+
✅ **JSON Responses** - Easy creation of JSON API responses
|
|
19
|
+
|
|
20
|
+
✅ **Exception Handling** - Built-in error response formatting
|
|
21
|
+
|
|
22
|
+
✅ **HTTP Redirects** - Support for all redirect status codes
|
|
23
|
+
|
|
24
|
+
✅ **Header Management** - Integrated HTTP header handling
|
|
25
|
+
|
|
26
|
+
✅ **Web Standards** - Returns native Web API Response objects
|
|
27
|
+
|
|
28
|
+
✅ **Method Chaining** - All methods return the instance for chaining
|
|
29
|
+
|
|
30
|
+
✅ **State Management** - Proper state transitions between response types
|
|
31
|
+
|
|
32
|
+
✅ **Cross-Platform** - Works in Browser, Node.js, Bun, and Deno
|
|
33
|
+
|
|
34
|
+
## Installation
|
|
35
|
+
|
|
36
|
+
### Bun
|
|
37
|
+
```bash
|
|
38
|
+
bun add @ooneex/http-response
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
### pnpm
|
|
42
|
+
```bash
|
|
43
|
+
pnpm add @ooneex/http-response
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
### Yarn
|
|
47
|
+
```bash
|
|
48
|
+
yarn add @ooneex/http-response
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
### npm
|
|
52
|
+
```bash
|
|
53
|
+
npm install @ooneex/http-response
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
## Usage
|
|
57
|
+
|
|
58
|
+
### Basic JSON Responses
|
|
59
|
+
|
|
60
|
+
```typescript
|
|
61
|
+
import { HttpResponse } from '@ooneex/http-response';
|
|
62
|
+
import { HttpStatus } from '@ooneex/http-status';
|
|
63
|
+
|
|
64
|
+
const response = new HttpResponse();
|
|
65
|
+
|
|
66
|
+
// Simple JSON response
|
|
67
|
+
const webResponse = response
|
|
68
|
+
.json({ message: 'Hello, World!' })
|
|
69
|
+
.get();
|
|
70
|
+
|
|
71
|
+
console.log(webResponse.status); // 200
|
|
72
|
+
console.log(await webResponse.json()); // { message: 'Hello, World!' }
|
|
73
|
+
|
|
74
|
+
// JSON response with custom status
|
|
75
|
+
response
|
|
76
|
+
.json({ user: { id: 1, name: 'John' } }, Status.Code.Created)
|
|
77
|
+
.get();
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
### Exception Handling
|
|
81
|
+
|
|
82
|
+
```typescript
|
|
83
|
+
import { HttpResponse } from '@ooneex/http-response';
|
|
84
|
+
import { HttpStatus } from '@ooneex/http-status';
|
|
85
|
+
|
|
86
|
+
const response = new HttpResponse();
|
|
87
|
+
|
|
88
|
+
// Basic exception
|
|
89
|
+
const errorResponse = response
|
|
90
|
+
.exception('Something went wrong')
|
|
91
|
+
.get();
|
|
92
|
+
|
|
93
|
+
console.log(errorResponse.status); // 500
|
|
94
|
+
console.log(await errorResponse.json());
|
|
95
|
+
// {
|
|
96
|
+
// error: true,
|
|
97
|
+
// message: 'Something went wrong',
|
|
98
|
+
// status: 500,
|
|
99
|
+
// data: null
|
|
100
|
+
// }
|
|
101
|
+
|
|
102
|
+
// Exception with custom status and data
|
|
103
|
+
response
|
|
104
|
+
.exception('Validation failed', {
|
|
105
|
+
status: Status.Code.BadRequest,
|
|
106
|
+
data: { field: 'email', reason: 'invalid format' }
|
|
107
|
+
})
|
|
108
|
+
.get();
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
### Not Found Responses
|
|
112
|
+
|
|
113
|
+
```typescript
|
|
114
|
+
import { HttpResponse } from '@ooneex/http-response';
|
|
115
|
+
|
|
116
|
+
const response = new HttpResponse();
|
|
117
|
+
|
|
118
|
+
// Basic not found
|
|
119
|
+
response
|
|
120
|
+
.notFound('User not found')
|
|
121
|
+
.get();
|
|
122
|
+
|
|
123
|
+
// Not found with custom data
|
|
124
|
+
response
|
|
125
|
+
.notFound('Resource not found', {
|
|
126
|
+
data: { resourceId: 123, type: 'user' }
|
|
127
|
+
})
|
|
128
|
+
.get();
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
### HTTP Redirects
|
|
132
|
+
|
|
133
|
+
```typescript
|
|
134
|
+
import { HttpResponse } from '@ooneex/http-response';
|
|
135
|
+
import { HttpStatus } from '@ooneex/http-status';
|
|
136
|
+
|
|
137
|
+
const response = new HttpResponse();
|
|
138
|
+
|
|
139
|
+
// Basic redirect (302 Found)
|
|
140
|
+
response
|
|
141
|
+
.redirect('https://example.com')
|
|
142
|
+
.get();
|
|
143
|
+
|
|
144
|
+
// Permanent redirect
|
|
145
|
+
response
|
|
146
|
+
.redirect('https://example.com/new-path', Status.Code.MovedPermanently)
|
|
147
|
+
.get();
|
|
148
|
+
|
|
149
|
+
// Redirect with URL object
|
|
150
|
+
const url = new URL('https://api.example.com/v2/users');
|
|
151
|
+
response
|
|
152
|
+
.redirect(url, Status.Code.SeeOther)
|
|
153
|
+
.get();
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
### Working with Headers
|
|
157
|
+
|
|
158
|
+
```typescript
|
|
159
|
+
import { HttpResponse } from '@ooneex/http-response';
|
|
160
|
+
import { Header } from '@ooneex/http-header';
|
|
161
|
+
|
|
162
|
+
// With custom headers
|
|
163
|
+
const customHeader = new Header();
|
|
164
|
+
customHeader.set('X-API-Version', '2.0');
|
|
165
|
+
customHeader.set('X-Request-ID', '12345');
|
|
166
|
+
|
|
167
|
+
const response = new HttpResponse(customHeader);
|
|
168
|
+
|
|
169
|
+
response
|
|
170
|
+
.json({ data: 'response with custom headers' })
|
|
171
|
+
.get();
|
|
172
|
+
|
|
173
|
+
// Headers are preserved across response types
|
|
174
|
+
response.header.set('X-Custom', 'value');
|
|
175
|
+
response.json({ message: 'test' });
|
|
176
|
+
// X-Custom header is still present
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
### TypeScript Generics
|
|
180
|
+
|
|
181
|
+
```typescript
|
|
182
|
+
import { HttpResponse } from '@ooneex/http-response';
|
|
183
|
+
|
|
184
|
+
// Define your data type
|
|
185
|
+
interface User extends Record<string, unknown> {
|
|
186
|
+
id: number;
|
|
187
|
+
name: string;
|
|
188
|
+
email: string;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
interface ApiError extends Record<string, unknown> {
|
|
192
|
+
code: string;
|
|
193
|
+
field?: string;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// Type-safe responses
|
|
197
|
+
const userResponse = new HttpResponse<User>();
|
|
198
|
+
const userData: User = {
|
|
199
|
+
id: 1,
|
|
200
|
+
name: 'John Doe',
|
|
201
|
+
email: 'john@example.com'
|
|
202
|
+
};
|
|
203
|
+
|
|
204
|
+
userResponse.json(userData); // Type-safe!
|
|
205
|
+
|
|
206
|
+
// Type-safe error responses
|
|
207
|
+
const errorResponse = new HttpResponse<ApiError>();
|
|
208
|
+
errorResponse.exception('Validation error', {
|
|
209
|
+
data: { code: 'INVALID_EMAIL', field: 'email' }
|
|
210
|
+
});
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
### Advanced Usage
|
|
214
|
+
|
|
215
|
+
```typescript
|
|
216
|
+
import { HttpResponse } from '@ooneex/http-response';
|
|
217
|
+
import { HttpStatus } from '@ooneex/http-status';
|
|
218
|
+
|
|
219
|
+
const response = new HttpResponse();
|
|
220
|
+
|
|
221
|
+
// Complex API response
|
|
222
|
+
const apiResponse = {
|
|
223
|
+
data: {
|
|
224
|
+
users: [
|
|
225
|
+
{ id: 1, name: 'John' },
|
|
226
|
+
{ id: 2, name: 'Jane' }
|
|
227
|
+
]
|
|
228
|
+
},
|
|
229
|
+
meta: {
|
|
230
|
+
page: 1,
|
|
231
|
+
limit: 10,
|
|
232
|
+
total: 25
|
|
233
|
+
}
|
|
234
|
+
};
|
|
235
|
+
|
|
236
|
+
response
|
|
237
|
+
.json(apiResponse, Status.Code.OK)
|
|
238
|
+
.get();
|
|
239
|
+
|
|
240
|
+
// Error handling with detailed information
|
|
241
|
+
response
|
|
242
|
+
.exception('Database connection failed', {
|
|
243
|
+
status: Status.Code.ServiceUnavailable,
|
|
244
|
+
data: {
|
|
245
|
+
service: 'database',
|
|
246
|
+
retryAfter: 30,
|
|
247
|
+
errorCode: 'DB_CONN_TIMEOUT'
|
|
248
|
+
}
|
|
249
|
+
})
|
|
250
|
+
.get();
|
|
251
|
+
|
|
252
|
+
// State transitions
|
|
253
|
+
response.json({ initial: 'data' });
|
|
254
|
+
// Later change to redirect
|
|
255
|
+
response.redirect('/login');
|
|
256
|
+
// Headers and state are properly managed
|
|
257
|
+
```
|
|
258
|
+
|
|
259
|
+
## API Reference
|
|
260
|
+
|
|
261
|
+
### `HttpResponse<DataType>` Class
|
|
262
|
+
|
|
263
|
+
The main class for building HTTP responses with optional generic type parameter.
|
|
264
|
+
|
|
265
|
+
#### Constructor
|
|
266
|
+
|
|
267
|
+
##### `new HttpResponse<DataType>(header?: IHeader)`
|
|
268
|
+
|
|
269
|
+
Creates a new HTTP response instance.
|
|
270
|
+
|
|
271
|
+
**Parameters:**
|
|
272
|
+
- `header` (optional) - Custom header instance. If not provided, creates a default header.
|
|
273
|
+
|
|
274
|
+
**Example:**
|
|
275
|
+
```typescript
|
|
276
|
+
// With default header
|
|
277
|
+
const response = new HttpResponse();
|
|
278
|
+
|
|
279
|
+
// With custom header
|
|
280
|
+
const customHeader = new Header();
|
|
281
|
+
const response = new HttpResponse(customHeader);
|
|
282
|
+
```
|
|
283
|
+
|
|
284
|
+
#### Properties
|
|
285
|
+
|
|
286
|
+
##### `readonly header: IHeader`
|
|
287
|
+
|
|
288
|
+
Access to the HTTP header instance for setting custom headers.
|
|
289
|
+
|
|
290
|
+
**Example:**
|
|
291
|
+
```typescript
|
|
292
|
+
response.header.set('X-Custom-Header', 'value');
|
|
293
|
+
response.header.setCache('public', 3600);
|
|
294
|
+
```
|
|
295
|
+
|
|
296
|
+
#### Methods
|
|
297
|
+
|
|
298
|
+
##### `json(data: DataType, status?: StatusCodeType): IResponse<DataType>`
|
|
299
|
+
|
|
300
|
+
Creates a JSON response with the provided data.
|
|
301
|
+
|
|
302
|
+
**Parameters:**
|
|
303
|
+
- `data` - The data to serialize as JSON
|
|
304
|
+
- `status` (optional) - HTTP status code (
|
|
305
|
+
defaults to 200)
|
|
306
|
+
|
|
307
|
+
**Returns:** The response instance for method chaining
|
|
308
|
+
|
|
309
|
+
**Example:**
|
|
310
|
+
```typescript
|
|
311
|
+
response.json({ message: 'Success' });
|
|
312
|
+
response.json({ user: userData }, Status.Code.Created);
|
|
313
|
+
```
|
|
314
|
+
|
|
315
|
+
##### `exception(message: string, config?: object): IResponse<DataType>`
|
|
316
|
+
|
|
317
|
+
Creates an error response with structured error information.
|
|
318
|
+
|
|
319
|
+
**Parameters:**
|
|
320
|
+
- `message` - Error message
|
|
321
|
+
- `config` (optional) - Configuration object
|
|
322
|
+
- `data` - Additional error data
|
|
323
|
+
- `status` - HTTP status code (defaults to 500)
|
|
324
|
+
|
|
325
|
+
**Returns:** The response instance for method chaining
|
|
326
|
+
|
|
327
|
+
**Example:**
|
|
328
|
+
```typescript
|
|
329
|
+
response.exception('Internal server error');
|
|
330
|
+
response.exception('Validation failed', {
|
|
331
|
+
status: Status.Code.BadRequest,
|
|
332
|
+
data: { field: 'email' }
|
|
333
|
+
});
|
|
334
|
+
```
|
|
335
|
+
|
|
336
|
+
##### `notFound(message: string, config?: object): IResponse<DataType>`
|
|
337
|
+
|
|
338
|
+
Creates a not found error response.
|
|
339
|
+
|
|
340
|
+
**Parameters:**
|
|
341
|
+
- `message` - Not found message
|
|
342
|
+
- `config` (optional) - Configuration object
|
|
343
|
+
- `data` - Additional error data
|
|
344
|
+
- `status` - HTTP status code (defaults to 404)
|
|
345
|
+
|
|
346
|
+
**Returns:** The response instance for method chaining
|
|
347
|
+
|
|
348
|
+
**Example:**
|
|
349
|
+
```typescript
|
|
350
|
+
response.notFound('User not found');
|
|
351
|
+
response.notFound('Resource not found', {
|
|
352
|
+
data: { resourceId: 123 }
|
|
353
|
+
});
|
|
354
|
+
```
|
|
355
|
+
|
|
356
|
+
##### `redirect(url: string | URL, status?: StatusCodeType): IResponse<DataType>`
|
|
357
|
+
|
|
358
|
+
Creates a redirect response.
|
|
359
|
+
|
|
360
|
+
**Parameters:**
|
|
361
|
+
- `url` - Destination URL (string or URL object)
|
|
362
|
+
- `status` (optional) - HTTP redirect status code (defaults to 302)
|
|
363
|
+
|
|
364
|
+
**Returns:** The response instance for method chaining
|
|
365
|
+
|
|
366
|
+
**Example:**
|
|
367
|
+
```typescript
|
|
368
|
+
response.redirect('https://example.com');
|
|
369
|
+
response.redirect('/dashboard', Status.Code.MovedPermanently);
|
|
370
|
+
response.redirect(new URL('https://api.example.com/v2'));
|
|
371
|
+
```
|
|
372
|
+
|
|
373
|
+
##### `get(): Response`
|
|
374
|
+
|
|
375
|
+
Builds and returns the final Web API Response object.
|
|
376
|
+
|
|
377
|
+
**Returns:** Standard Web API Response object
|
|
378
|
+
|
|
379
|
+
**Example:**
|
|
380
|
+
```typescript
|
|
381
|
+
const webResponse = response.json({ data: 'test' }).get();
|
|
382
|
+
// webResponse is a standard Response object
|
|
383
|
+
const data = await webResponse.json();
|
|
384
|
+
const status = webResponse.status;
|
|
385
|
+
const headers = webResponse.headers;
|
|
386
|
+
```
|
|
387
|
+
|
|
388
|
+
### Interfaces
|
|
389
|
+
|
|
390
|
+
#### `IResponse<DataType>`
|
|
391
|
+
|
|
392
|
+
Interface defining the response builder contract.
|
|
393
|
+
|
|
394
|
+
**Methods:**
|
|
395
|
+
- `json(data: DataType, status?: StatusCodeType): IResponse<DataType>`
|
|
396
|
+
- `exception(message: string, config?: object): IResponse<DataType>`
|
|
397
|
+
- `notFound(message: string, config?: object): IResponse<DataType>`
|
|
398
|
+
- `redirect(url: string | URL, status?: StatusCodeType): IResponse<DataType>`
|
|
399
|
+
- `get(): Response`
|
|
400
|
+
|
|
401
|
+
**Properties:**
|
|
402
|
+
- `readonly header: IHeader`
|
|
403
|
+
|
|
404
|
+
### Response Structure
|
|
405
|
+
|
|
406
|
+
#### JSON Response
|
|
407
|
+
```typescript
|
|
408
|
+
// Standard JSON response body is your provided data
|
|
409
|
+
{ message: 'Hello, World!' }
|
|
410
|
+
```
|
|
411
|
+
|
|
412
|
+
#### Exception Response
|
|
413
|
+
```typescript
|
|
414
|
+
{
|
|
415
|
+
error: true,
|
|
416
|
+
message: 'Error message',
|
|
417
|
+
status: 500,
|
|
418
|
+
data: null | YourDataType
|
|
419
|
+
}
|
|
420
|
+
```
|
|
421
|
+
|
|
422
|
+
#### Not Found Response
|
|
423
|
+
```typescript
|
|
424
|
+
{
|
|
425
|
+
error: true,
|
|
426
|
+
message: 'Resource not found',
|
|
427
|
+
status: 404,
|
|
428
|
+
data: null | YourDataType
|
|
429
|
+
}
|
|
430
|
+
```
|
|
431
|
+
|
|
432
|
+
#### Redirect Response
|
|
433
|
+
```typescript
|
|
434
|
+
// Empty body with Location header set
|
|
435
|
+
// Status: 302, 301, 303, etc.
|
|
436
|
+
// Headers: { Location: 'redirect-url' }
|
|
437
|
+
```
|
|
438
|
+
|
|
439
|
+
## Integration Examples
|
|
440
|
+
|
|
441
|
+
### Express.js Integration
|
|
442
|
+
|
|
443
|
+
```typescript
|
|
444
|
+
import express from 'express';
|
|
445
|
+
import { HttpResponse } from '@ooneex/http-response';
|
|
446
|
+
import { HttpStatus } from '@ooneex/http-status';
|
|
447
|
+
|
|
448
|
+
const app = express();
|
|
449
|
+
|
|
450
|
+
app.get('/api/users/:id', async (req, res) => {
|
|
451
|
+
const response = new HttpResponse();
|
|
452
|
+
|
|
453
|
+
try {
|
|
454
|
+
const user = await getUserById(req.params.id);
|
|
455
|
+
if (!user) {
|
|
456
|
+
const webResponse = response
|
|
457
|
+
.notFound('User not found')
|
|
458
|
+
.get();
|
|
459
|
+
|
|
460
|
+
return res.status(webResponse.status).json(await webResponse.json());
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
const webResponse = response
|
|
464
|
+
.json({ user })
|
|
465
|
+
.get();
|
|
466
|
+
|
|
467
|
+
res.status(webResponse.status).json(await webResponse.json());
|
|
468
|
+
} catch (error) {
|
|
469
|
+
const webResponse = response
|
|
470
|
+
.exception('Failed to fetch user')
|
|
471
|
+
.get();
|
|
472
|
+
|
|
473
|
+
res.status(webResponse.status).json(await webResponse.json());
|
|
474
|
+
}
|
|
475
|
+
});
|
|
476
|
+
```
|
|
477
|
+
|
|
478
|
+
### Hono Framework Integration
|
|
479
|
+
|
|
480
|
+
```typescript
|
|
481
|
+
import { Hono } from 'hono';
|
|
482
|
+
import { HttpResponse } from '@ooneex/http-response';
|
|
483
|
+
|
|
484
|
+
const app = new Hono();
|
|
485
|
+
|
|
486
|
+
app.get('/api/users', async (c) => {
|
|
487
|
+
const response = new HttpResponse();
|
|
488
|
+
|
|
489
|
+
try {
|
|
490
|
+
const users = await getUsers();
|
|
491
|
+
return response.json({ users }).get();
|
|
492
|
+
} catch (error) {
|
|
493
|
+
return response.exception('Failed to fetch users').get();
|
|
494
|
+
}
|
|
495
|
+
});
|
|
496
|
+
|
|
497
|
+
app.post('/api/users', async (c) => {
|
|
498
|
+
const response = new HttpResponse();
|
|
499
|
+
|
|
500
|
+
try {
|
|
501
|
+
const userData = await c.req.json();
|
|
502
|
+
const user = await createUser(userData);
|
|
503
|
+
return response.json({ user }, Status.Code.Created).get();
|
|
504
|
+
} catch (error) {
|
|
505
|
+
return response.exception('Failed to create user').get();
|
|
506
|
+
}
|
|
507
|
+
});
|
|
508
|
+
```
|
|
509
|
+
|
|
510
|
+
### Bun Server Integration
|
|
511
|
+
|
|
512
|
+
```typescript
|
|
513
|
+
import { HttpResponse } from '@ooneex/http-response';
|
|
514
|
+
|
|
515
|
+
const server = Bun.serve({
|
|
516
|
+
port: 3000,
|
|
517
|
+
async fetch(req) {
|
|
518
|
+
const response = new HttpResponse();
|
|
519
|
+
const url = new URL(req.url);
|
|
520
|
+
|
|
521
|
+
if (url.pathname === '/api/health') {
|
|
522
|
+
return response.json({ status: 'ok', timestamp: Date.now() }).get();
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
if (url.pathname === '/redirect') {
|
|
526
|
+
return response.redirect('https://example.com').get();
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
return response.notFound('Endpoint not found').get();
|
|
530
|
+
}
|
|
531
|
+
});
|
|
532
|
+
```
|
|
533
|
+
|
|
534
|
+
## License
|
|
535
|
+
|
|
536
|
+
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
|
|
537
|
+
|
|
538
|
+
## Contributing
|
|
539
|
+
|
|
540
|
+
Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.
|
|
541
|
+
|
|
542
|
+
### Development Setup
|
|
543
|
+
|
|
544
|
+
1. Clone the repository
|
|
545
|
+
2. Install dependencies: `bun install`
|
|
546
|
+
3. Run tests: `bun run test`
|
|
547
|
+
4. Build the project: `bun run build`
|
|
548
|
+
|
|
549
|
+
### Guidelines
|
|
550
|
+
|
|
551
|
+
- Write tests for new features
|
|
552
|
+
- Follow the existing code style
|
|
553
|
+
- Update documentation for API changes
|
|
554
|
+
- Ensure all tests pass before submitting PR
|
|
555
|
+
|
|
556
|
+
---
|
|
557
|
+
|
|
558
|
+
Made with ❤️ by the Ooneex team
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { IHeader as IHeader2 } from "@ooneex/http-header";
|
|
2
|
+
import { StatusCodeType as StatusCodeType2 } from "@ooneex/http-status";
|
|
3
|
+
import { Environment } from "@ooneex/app-env";
|
|
4
|
+
import { IHeader } from "@ooneex/http-header";
|
|
5
|
+
import { StatusCodeType } from "@ooneex/http-status";
|
|
6
|
+
interface IResponse<DataType extends Record<string, unknown> = Record<string, unknown>> {
|
|
7
|
+
readonly header: IHeader;
|
|
8
|
+
done: boolean;
|
|
9
|
+
json: (data: DataType, status?: StatusCodeType) => IResponse<DataType>;
|
|
10
|
+
exception: (message: string, config?: {
|
|
11
|
+
data?: DataType;
|
|
12
|
+
status?: StatusCodeType;
|
|
13
|
+
}) => IResponse<DataType>;
|
|
14
|
+
notFound: (message: string, config?: {
|
|
15
|
+
data?: DataType;
|
|
16
|
+
status?: StatusCodeType;
|
|
17
|
+
}) => IResponse<DataType>;
|
|
18
|
+
redirect: (url: string | URL, status?: StatusCodeType) => IResponse<DataType>;
|
|
19
|
+
get: () => Response;
|
|
20
|
+
}
|
|
21
|
+
type ResponseDataType<Data extends Record<string, unknown>> = {
|
|
22
|
+
data: Data;
|
|
23
|
+
message: string | null;
|
|
24
|
+
success: boolean;
|
|
25
|
+
done: boolean;
|
|
26
|
+
status: number;
|
|
27
|
+
isClientError: boolean;
|
|
28
|
+
isServerError: boolean;
|
|
29
|
+
isNotFound: boolean;
|
|
30
|
+
isUnauthorized: boolean;
|
|
31
|
+
isForbidden: boolean;
|
|
32
|
+
debug: boolean;
|
|
33
|
+
app: {
|
|
34
|
+
url: string;
|
|
35
|
+
env: Environment;
|
|
36
|
+
};
|
|
37
|
+
};
|
|
38
|
+
declare class HttpResponse<Data extends Record<string, unknown> = Record<string, unknown>> implements IResponse<Data> {
|
|
39
|
+
readonly header: IHeader2;
|
|
40
|
+
private data;
|
|
41
|
+
private status;
|
|
42
|
+
private redirectUrl;
|
|
43
|
+
private message;
|
|
44
|
+
done: boolean;
|
|
45
|
+
constructor(header?: IHeader2);
|
|
46
|
+
json(data: Data, status?: StatusCodeType2): IResponse<Data>;
|
|
47
|
+
exception(message: string, config?: {
|
|
48
|
+
data?: Data;
|
|
49
|
+
status?: StatusCodeType2;
|
|
50
|
+
}): IResponse<Data>;
|
|
51
|
+
notFound(message: string, config?: {
|
|
52
|
+
data?: Data;
|
|
53
|
+
status?: StatusCodeType2;
|
|
54
|
+
}): IResponse<Data>;
|
|
55
|
+
redirect(url: string | URL, status?: StatusCodeType2): IResponse<Data>;
|
|
56
|
+
get(): Response;
|
|
57
|
+
}
|
|
58
|
+
export { ResponseDataType, IResponse, HttpResponse };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{Environment as a}from"@ooneex/app-env";import{Header as r}from"@ooneex/http-header";import{HttpStatus as s}from"@ooneex/http-status";class n{header;data=null;status=s.Code.OK;redirectUrl=null;message=null;done=!1;constructor(e){this.header=e||new r}json(e,t=s.Code.OK){return this.data=e,this.status=t,this.header.setJson(),this.header.remove("Location"),this.redirectUrl=null,this.message=null,this}exception(e,t){return this.message=e,this.status=t?.status??s.Code.InternalServerError,this.data=t?.data||null,this.redirectUrl=null,this.header.setJson(),this.header.remove("Location"),this}notFound(e,t){return this.message=e,this.status=t?.status||s.Code.NotFound,this.data=t?.data||null,this.redirectUrl=null,this.header.setJson(),this.header.remove("Location"),this}redirect(e,t=s.Code.Found){return this.redirectUrl=e,this.status=t,this.header.setLocation(e.toString()),this.data=null,this.message=null,this}get(){if(this.redirectUrl)return new Response(null,{status:this.status,headers:this.header.native});let e=new s,t={data:this.data||{},message:this.message,success:e.isSuccessful(this.status),done:this.done,status:this.status,isClientError:e.isClientError(this.status),isServerError:e.isServerError(this.status),isNotFound:!1,isUnauthorized:!1,isForbidden:!1,debug:!1,app:{url:"",env:a.PRODUCTION}};return new Response(JSON.stringify(t),{status:t.status,headers:this.header.native})}}export{n as HttpResponse};
|
|
2
|
+
|
|
3
|
+
//# debugId=0F4483EB048F7FC264756E2164756E21
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["src/HttpResponse.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"import { Environment } from \"@ooneex/app-env\";\nimport { Header, type IHeader } from \"@ooneex/http-header\";\nimport { HttpStatus, type StatusCodeType } from \"@ooneex/http-status\";\nimport type { IResponse, ResponseDataType } from \"./types\";\n\nexport class HttpResponse<Data extends Record<string, unknown> = Record<string, unknown>> implements IResponse<Data> {\n public readonly header: IHeader;\n private data: Data | null = null;\n private status: StatusCodeType = HttpStatus.Code.OK;\n private redirectUrl: string | URL | null = null;\n private message: string | null = null;\n public done = false; // For socket\n\n constructor(header?: IHeader) {\n this.header = header || new Header();\n }\n\n public json(data: Data, status: StatusCodeType = HttpStatus.Code.OK): IResponse<Data> {\n this.data = data;\n this.status = status;\n this.header.setJson();\n this.header.remove(\"Location\");\n this.redirectUrl = null;\n this.message = null;\n\n return this;\n }\n\n public exception(\n message: string,\n config?: {\n data?: Data;\n status?: StatusCodeType;\n },\n ): IResponse<Data> {\n this.message = message;\n this.status = config?.status ?? HttpStatus.Code.InternalServerError;\n this.data = config?.data || null;\n this.redirectUrl = null;\n this.header.setJson();\n this.header.remove(\"Location\");\n\n return this;\n }\n\n public notFound(\n message: string,\n config?: {\n data?: Data;\n status?: StatusCodeType;\n },\n ): IResponse<Data> {\n this.message = message;\n this.status = config?.status || HttpStatus.Code.NotFound;\n this.data = config?.data || null;\n this.redirectUrl = null;\n this.header.setJson();\n this.header.remove(\"Location\");\n\n return this;\n }\n\n public redirect(url: string | URL, status: StatusCodeType = HttpStatus.Code.Found): IResponse<Data> {\n this.redirectUrl = url;\n this.status = status;\n this.header.setLocation(url.toString());\n this.data = null;\n this.message = null;\n\n return this;\n }\n\n public get(): Response {\n if (this.redirectUrl) {\n return new Response(null, {\n status: this.status,\n headers: this.header.native,\n });\n }\n\n const status = new HttpStatus();\n\n const responseData: ResponseDataType<Data> = {\n data: this.data || ({} as Data),\n message: this.message,\n success: status.isSuccessful(this.status),\n done: this.done,\n status: this.status,\n isClientError: status.isClientError(this.status),\n isServerError: status.isServerError(this.status),\n isNotFound: false,\n isUnauthorized: false,\n isForbidden: false,\n debug: false,\n app: {\n url: \"\",\n env: Environment.PRODUCTION,\n },\n };\n\n return new Response(JSON.stringify(responseData), {\n status: responseData.status,\n headers: this.header.native,\n });\n }\n}\n"
|
|
6
|
+
],
|
|
7
|
+
"mappings": "AAAA,sBAAS,wBACT,iBAAS,4BACT,qBAAS,4BAGF,MAAM,CAAwG,CACnG,OACR,KAAoB,KACpB,OAAyB,EAAW,KAAK,GACzC,YAAmC,KACnC,QAAyB,KAC1B,KAAO,GAEd,WAAW,CAAC,EAAkB,CAC5B,KAAK,OAAS,GAAU,IAAI,EAGvB,IAAI,CAAC,EAAY,EAAyB,EAAW,KAAK,GAAqB,CAQpF,OAPA,KAAK,KAAO,EACZ,KAAK,OAAS,EACd,KAAK,OAAO,QAAQ,EACpB,KAAK,OAAO,OAAO,UAAU,EAC7B,KAAK,YAAc,KACnB,KAAK,QAAU,KAER,KAGF,SAAS,CACd,EACA,EAIiB,CAQjB,OAPA,KAAK,QAAU,EACf,KAAK,OAAS,GAAQ,QAAU,EAAW,KAAK,oBAChD,KAAK,KAAO,GAAQ,MAAQ,KAC5B,KAAK,YAAc,KACnB,KAAK,OAAO,QAAQ,EACpB,KAAK,OAAO,OAAO,UAAU,EAEtB,KAGF,QAAQ,CACb,EACA,EAIiB,CAQjB,OAPA,KAAK,QAAU,EACf,KAAK,OAAS,GAAQ,QAAU,EAAW,KAAK,SAChD,KAAK,KAAO,GAAQ,MAAQ,KAC5B,KAAK,YAAc,KACnB,KAAK,OAAO,QAAQ,EACpB,KAAK,OAAO,OAAO,UAAU,EAEtB,KAGF,QAAQ,CAAC,EAAmB,EAAyB,EAAW,KAAK,MAAwB,CAOlG,OANA,KAAK,YAAc,EACnB,KAAK,OAAS,EACd,KAAK,OAAO,YAAY,EAAI,SAAS,CAAC,EACtC,KAAK,KAAO,KACZ,KAAK,QAAU,KAER,KAGF,GAAG,EAAa,CACrB,GAAI,KAAK,YACP,OAAO,IAAI,SAAS,KAAM,CACxB,OAAQ,KAAK,OACb,QAAS,KAAK,OAAO,MACvB,CAAC,EAGH,IAAM,EAAS,IAAI,EAEb,EAAuC,CAC3C,KAAM,KAAK,MAAS,CAAC,EACrB,QAAS,KAAK,QACd,QAAS,EAAO,aAAa,KAAK,MAAM,EACxC,KAAM,KAAK,KACX,OAAQ,KAAK,OACb,cAAe,EAAO,cAAc,KAAK,MAAM,EAC/C,cAAe,EAAO,cAAc,KAAK,MAAM,EAC/C,WAAY,GACZ,eAAgB,GAChB,YAAa,GACb,MAAO,GACP,IAAK,CACH,IAAK,GACL,IAAK,EAAY,UACnB,CACF,EAEA,OAAO,IAAI,SAAS,KAAK,UAAU,CAAY,EAAG,CAChD,OAAQ,EAAa,OACrB,QAAS,KAAK,OAAO,MACvB,CAAC,EAEL",
|
|
8
|
+
"debugId": "0F4483EB048F7FC264756E2164756E21",
|
|
9
|
+
"names": []
|
|
10
|
+
}
|
|
Binary file
|
package/package.json
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@ooneex/http-response",
|
|
3
|
+
"description": "",
|
|
4
|
+
"version": "0.0.1",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"files": [
|
|
7
|
+
"dist",
|
|
8
|
+
"LICENSE",
|
|
9
|
+
"README.md",
|
|
10
|
+
"package.json"
|
|
11
|
+
],
|
|
12
|
+
"module": "./dist/index.js",
|
|
13
|
+
"types": "./dist/index.d.ts",
|
|
14
|
+
"exports": {
|
|
15
|
+
".": {
|
|
16
|
+
"import": {
|
|
17
|
+
"types": "./dist/index.d.ts",
|
|
18
|
+
"default": "./dist/index.js"
|
|
19
|
+
}
|
|
20
|
+
},
|
|
21
|
+
"./package.json": "./package.json"
|
|
22
|
+
},
|
|
23
|
+
"license": "MIT",
|
|
24
|
+
"scripts": {
|
|
25
|
+
"compile": "tsc ./src/index.ts --declaration --emitDeclarationOnly --target ES2022 --moduleResolution bundler --outfile dist/index.d.ts",
|
|
26
|
+
"build": "bunup",
|
|
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"
|
|
31
|
+
},
|
|
32
|
+
"dependencies": {
|
|
33
|
+
"@ooneex/app-env": "0.0.1",
|
|
34
|
+
"@ooneex/http-header": "0.0.1",
|
|
35
|
+
"@ooneex/http-status": "0.0.1"
|
|
36
|
+
},
|
|
37
|
+
"devDependencies": {},
|
|
38
|
+
"peerDependencies": {}
|
|
39
|
+
}
|