@@ -2,12 +2,26 @@ import { ServerResponse } from "node:http";
22import Jrror , { JoorError } from "@/core/error" ;
33import { HeaderSent } from "@/core/error/response" ;
44import logger from '@/helpers/joorLogger' ;
5+ import Response , { RESPONSE_LOCATION_STATUS } from "@/types/response" ;
56
6- const response = ServerResponse . prototype ;
7- response . status = function ( this : ServerResponse , status : number ) {
7+ const response = ServerResponse . prototype as Response ;
8+
9+ /**
10+ * Sets the HTTP status code for the response.
11+ *
12+ * @param {number } status - The HTTP status code to set.
13+ *
14+ * @returns {Response } The response object for chaining.
15+ *
16+ * @example
17+ * ```typescript
18+ * response.status(200);
19+ * ```
20+ */
21+ response . status = function ( this : ServerResponse , status : number ) : Response {
822 try {
923 if ( this . headersSent ) {
10- throw HeaderSent ;
24+ throw HeaderSent ; // Headers have already been sent
1125 }
1226 if ( ! Number . isInteger ( status ) ) {
1327 throw new Jrror ( {
@@ -40,4 +54,35 @@ response.status = function (this: ServerResponse, status: number) {
4054 return this ;
4155 }
4256
57+ }
58+
59+ /**
60+ Sets a location header for the response. Used for redirection.
61+
62+ @param {string } location - The URL to redirect to.
63+ @param {RESPONSE_LOCATION_STATUS } [status=301] - The HTTP status code for the redirection (default is 301).
64+
65+ example
66+ ```typescript
67+ response.location('https://example.com', 302);
68+ ```
69+ For more information, see the [HTTP/1.1 RFC](https://datatracker.ietf.org/doc/html/rfc7231#section-6.4).
70+ */
71+ response . location = function ( this : ServerResponse , location : string , status : RESPONSE_LOCATION_STATUS = 301 ) : void {
72+ try {
73+ if ( this . headersSent ) {
74+ throw HeaderSent ; // Headers have already been sent
75+ }
76+ this . setHeader ( "Location" , location ) ;
77+ this . status ( status ) ;
78+ }
79+ catch ( error : unknown ) {
80+
81+ if ( error instanceof Jrror || error instanceof JoorError ) {
82+ error . handle ( ) ;
83+ }
84+ else {
85+ logger . error ( error ) ;
86+ }
87+ }
4388}
0 commit comments