UNPKG

@pulzar/core

Version:

Next-generation Node.js framework for ultra-fast web applications with zero-reflection DI, GraphQL, WebSockets, events, and edge runtime support

103 lines 3.02 kB
export class ResponseWrapper { reply; request; startTime; constructor(reply, request) { this.reply = reply; this.request = request; this.startTime = Date.now(); } success(data, message, meta) { const response = { success: true, data, message, meta: { timestamp: new Date().toISOString(), path: this.request.url, duration: Date.now() - this.startTime, ...meta, }, }; this.reply.send(response); } error(error, statusCode = 500, meta) { const response = { success: false, error: typeof error === "string" ? error : error.message, meta: { timestamp: new Date().toISOString(), path: this.request.url, duration: Date.now() - this.startTime, ...meta, }, }; this.reply.code(statusCode).send(response); } paginated(data, page, limit, total, message, meta) { const pages = Math.ceil(total / limit); const response = { success: true, data, message, pagination: { page, limit, total, pages, hasNext: page < pages, hasPrev: page > 1, }, meta: { timestamp: new Date().toISOString(), path: this.request.url, duration: Date.now() - this.startTime, ...meta, }, }; this.reply.send(response); } created(data, message) { this.reply.code(201); this.success(data, message); } noContent() { this.reply.code(204).send(); } notFound(message = "Resource not found") { this.error(message, 404); } badRequest(message = "Bad request") { this.error(message, 400); } unauthorized(message = "Unauthorized") { this.error(message, 401); } forbidden(message = "Forbidden") { this.error(message, 403); } conflict(message = "Conflict") { this.error(message, 409); } unprocessableEntity(message = "Unprocessable entity") { this.error(message, 422); } tooManyRequests(message = "Too many requests") { this.error(message, 429); } internalServerError(message = "Internal server error") { this.error(message, 500); } } export function wrapResponse(reply, request) { return new ResponseWrapper(reply, request); } // Hook to add response wrapper to Fastify export function responseWrapperHook(request, reply) { reply.wrap = () => wrapResponse(reply, request); } // Plugin to register response wrapper export function registerResponseWrapperPlugin(fastify) { fastify.addHook("preHandler", responseWrapperHook); } //# sourceMappingURL=responseWrapper.js.map