UNPKG

resuponsu

Version:

A minimal, type-safe HTTP Response wrapper for Node.js and browser environments, with support for standardized success/error handling.

105 lines (77 loc) 2.98 kB
# Resuponsu > _“Standardize your API responses. Works like the native Response.”_ **Resuponsu** is a TypeScript-friendly wrapper around the native `Response` class for Node.js and browser environments. It provides a consistent way to send JSON responses, with optional `success`, `error`, and `message` fields, while remaining fully compatible with `fetch` and any code expecting a standard `Response`. ## Features - 📦 **Standardized JSON responses** with `success`, `error`, and `message` fields - 🛡 **Type-safe body validation**: ensures proper structure before sending - ⚡ **Fully compatible with native `Response`**: works anywhere a Response is expected - 📝 **Handles empty arrays or objects gracefully** - 💡 Minimal and flexible wrapper for consistent API responses ## Installation ```bash npm install resuponsu # or yarn add resuponsu # or pnpm add resuponsu ``` ## Basic Usage ```ts import { Resuponsu } from 'resuponsu'; // Using the static JSON helper return Resuponsu.json([{ id: 1, name: 'Quote' }]); return Resuponsu.json({ success: true, data: { foo: 'bar' } }); return Resuponsu.json([]); // empty array return Resuponsu.json({}); // empty object // Using Resuponsu directly like a native Response return new Resuponsu(JSON.stringify([{ id: 1, name: 'Quote' }]), { headers: { 'Content-Type': 'application/json' }, status: 200, }); ``` ## Advanced Usage ### Success and Error Responses ```ts // Success response return Resuponsu.json({ success: true, data: { id: 1, name: 'Quote' } }); // Error response with proper HTTP status return Resuponsu.json( { success: false, error: 'NOT_FOUND', message: 'Quote not found' }, { status: 404 }, ); ``` ### Empty Arrays or Objects ```ts // Empty array returns valid response return Resuponsu.json([]); // Empty object returns valid response return Resuponsu.json({}); ``` ## API Reference ### `Resuponsu.json(body?: BodyInit, init?: ResponseInit): Response` - **body**: Object or array to serialize as JSON - **init**: Optional `ResponseInit` containing `status` and `headers` - Validates: - `body` must be a non-null object or array - `success: true` must have status 200 - `success: false` must have non-200 status - Fully compatible with native `Response` methods (`json()`, `text()`, `clone()`, etc.) ### `Supported Status Codes` | Code | Meaning | | ---- | --------------------- | | 200 | OK | | 201 | Created | | 204 | No Content | | 400 | Bad Request | | 401 | Unauthorized | | 403 | Forbidden | | 404 | Not Found | | 409 | Conflict | | 422 | Unprocessable Entity | | 429 | Too Many Requests | | 500 | Internal Server Error | | 502 | Bad Gateway | | 503 | Service Unavailable | ## License MIT License – see [LICENSE](LICENSE) for details. **Author:** Estarlin R ([estarlincito.com](https://estarlincito.com))