Skip to content

Commit 56b42df

Browse files
authored
Merge pull request #5 from JooLuiz/feat/implement-redirect
[feat] - Implementing Redirect function and adjusting response function
2 parents cd233b6 + cc1abe0 commit 56b42df

7 files changed

Lines changed: 150 additions & 35 deletions

File tree

CHANGELOG.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,12 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
77

88
## [Unreleased] - yyyy-mm-dd
99

10+
## [0.3.0] - 2024-07-06
11+
12+
### Added
13+
14+
- Implementing Redirect function and adjusting response function
15+
1016
## [0.2.1] - 2024-07-06
1117

1218
### Fixed

README.md

Lines changed: 62 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -35,14 +35,19 @@ Simpler has a response method that will run the default response methods, you ca
3535

3636
```typescript
3737
//Returning with simpler
38-
simpler.response(res, 200, "application/json", JSON.stringify(parsedBody));
38+
simpler.response(
39+
res,
40+
200,
41+
{ "Content-Type": "application/json" },
42+
JSON.stringify(parsedBody)
43+
);
3944

4045
//Equivalent returning directly with res
4146
res.writeHead(200, { "Content-Type": "application/json" });
4247
res.end(JSON.stringify(parsedBody));
4348

4449
//Returning with simpler
45-
simpler.response(res, 200, "text/html", data);
50+
simpler.response(res, 200, { "Content-Type": "text/html" }, data);
4651

4752
//Equivalent returning directly with res
4853
res.writeHead(200, { "Content-Type": "text/html" });
@@ -57,7 +62,12 @@ simpler.router.addRoute(
5762
["POST", "GET"],
5863
(_req, res, body, _pathVariables, _queryParams) => {
5964
const parsedBody = JSON.parse(body);
60-
simpler.response(res, 200, "application/json", JSON.stringify(parsedBody));
65+
simpler.response(
66+
res,
67+
200,
68+
{ "Content-Type": "application/json" },
69+
JSON.stringify(parsedBody)
70+
);
6171
return;
6272
}
6373
);
@@ -73,7 +83,12 @@ simpler.router.addRoute(
7383
"id": "{value}"
7484
}
7585
*/
76-
simpler.response(res, 200, "application/json", JSON.stringify(parsedBody));
86+
simpler.response(
87+
res,
88+
200,
89+
{ "Content-Type": "application/json" },
90+
JSON.stringify(parsedBody)
91+
);
7792
return;
7893
}
7994
);
@@ -90,7 +105,12 @@ simpler.router.addRoute(
90105
"xpto": "{value2}",
91106
}
92107
*/
93-
simpler.response(res, 200, "application/json", JSON.stringify(parsedBody));
108+
simpler.response(
109+
res,
110+
200,
111+
{ "Content-Type": "application/json" },
112+
JSON.stringify(parsedBody)
113+
);
94114
return;
95115
}
96116
);
@@ -110,11 +130,16 @@ simpler.router.addRoute("/static", ["GET"], (_req, res) => {
110130
const testePath = path.join(__dirname, "static", "test.html");
111131
readFile(testePath, (err, data) => {
112132
if (err) {
113-
simpler.response(res, 500, "text/plain", "500 Internal Server Error");
133+
simpler.response(
134+
res,
135+
500,
136+
{ "Content-Type": "text/plain" },
137+
"500 Internal Server Error"
138+
);
114139
return;
115140
}
116141

117-
simpler.response(res, 200, "text/html", data);
142+
simpler.response(res, 200, { "Content-Type": "text/plain" }, data);
118143
});
119144
});
120145
```
@@ -131,6 +156,18 @@ simpler.router.addRoute("/static-page", ["GET"], (_req, res) => {
131156
});
132157
```
133158

159+
### Redirecting
160+
161+
You can redirect routes with the function `redirect`, it receives a res and the relative url to be redirected to.
162+
163+
Below you'll find an example of how yo use it
164+
165+
```typescript
166+
simpler.router.addRoute("/redir", ["GET"], (_req, res) => {
167+
simpler.redirect(res, "/static-page");
168+
});
169+
```
170+
134171
### Handling errors
135172

136173
You can have custom error handlers using the function `errorHandler.setCustomErrorHandler`. It receives a function that will have a res and an error as parameters.
@@ -167,7 +204,12 @@ const simpler = new Simpler(true);
167204

168205
simpler.router.addRoute("/test", ["POST", "GET"], (_req, res, body) => {
169206
const parsedBody = JSON.parse(body);
170-
simpler.response(res, 200, "application/json", JSON.stringify(parsedBody));
207+
simpler.response(
208+
res,
209+
200,
210+
{ "Content-Type": "application/json" },
211+
JSON.stringify(parsedBody)
212+
);
171213
return;
172214
});
173215

@@ -176,7 +218,12 @@ simpler.router.addRoute(
176218
["POST", "GET"],
177219
(_req, res, body: string, _pathVariables, _queryParams) => {
178220
const parsedBody = JSON.parse(body);
179-
simpler.response(res, 200, "application/json", JSON.stringify(parsedBody));
221+
simpler.response(
222+
res,
223+
200,
224+
{ "Content-Type": "application/json" },
225+
JSON.stringify(parsedBody)
226+
);
180227
return;
181228
}
182229
);
@@ -186,7 +233,12 @@ simpler.router.addRoute(
186233
["POST", "GET"],
187234
(_req, res, body, _pathVariables, _queryParams) => {
188235
const parsedBody = JSON.parse(body);
189-
simpler.response(res, 200, "application/json", JSON.stringify(parsedBody));
236+
simpler.response(
237+
res,
238+
200,
239+
{ "Content-Type": "application/json" },
240+
JSON.stringify(parsedBody)
241+
);
190242
return;
191243
}
192244
);

README.pt-br.md

Lines changed: 66 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -35,14 +35,19 @@ Simpler possui um método de resposta que executará os métodos de resposta pad
3535

3636
```typescript
3737
// Retornando com Simpler
38-
simpler.response(res, 200, "application/json", JSON.stringify(parsedBody));
38+
simpler.response(
39+
res,
40+
200,
41+
{ "Content-Type": "application/json" },
42+
JSON.stringify(parsedBody)
43+
);
3944

4045
// Equivalente retornando diretamente com res
4146
res.writeHead(200, { "Content-Type": "application/json" });
4247
res.end(JSON.stringify(parsedBody));
4348

4449
// Retornando com Simpler
45-
simpler.response(res, 200, "text/html", data);
50+
simpler.response(res, 200, { "Content-Type": "text/html" }, data);
4651

4752
// Equivalente retornando diretamente com res
4853
res.writeHead(200, { "Content-Type": "text/html" });
@@ -57,7 +62,12 @@ simpler.router.addRoute(
5762
["POST", "GET"],
5863
(_req, res, body, _pathVariables, _queryParams) => {
5964
const parsedBody = JSON.parse(body);
60-
simpler.response(res, 200, "application/json", JSON.stringify(parsedBody));
65+
simpler.response(
66+
res,
67+
200,
68+
{ "Content-Type": "application/json" },
69+
JSON.stringify(parsedBody)
70+
);
6171
return;
6272
}
6373
);
@@ -73,7 +83,12 @@ simpler.router.addRoute(
7383
"id": "{valor}"
7484
}
7585
*/
76-
simpler.response(res, 200, "application/json", JSON.stringify(parsedBody));
86+
simpler.response(
87+
res,
88+
200,
89+
{ "Content-Type": "application/json" },
90+
JSON.stringify(parsedBody)
91+
);
7792
return;
7893
}
7994
);
@@ -90,7 +105,12 @@ simpler.router.addRoute(
90105
"xpto": "{valor2}",
91106
}
92107
*/
93-
simpler.response(res, 200, "application/json", JSON.stringify(parsedBody));
108+
simpler.response(
109+
res,
110+
200,
111+
{ "Content-Type": "application/json" },
112+
JSON.stringify(parsedBody)
113+
);
94114
return;
95115
}
96116
);
@@ -110,11 +130,16 @@ simpler.router.addRoute("/static", ["GET"], (_req, res) => {
110130
const testePath = path.join(__dirname, "static", "test.html");
111131
readFile(testePath, (err, data) => {
112132
if (err) {
113-
simpler.response(res, 500, "text/plain", "500 Internal Server Error");
133+
simpler.response(
134+
res,
135+
500,
136+
{ "Content-Type": "text/plain" },
137+
"500 Internal Server Error"
138+
);
114139
return;
115140
}
116141

117-
simpler.response(res, 200, "text/html", data);
142+
simpler.response(res, 200, { "Content-Type": "text/html" }, data);
118143
});
119144
});
120145
```
@@ -131,6 +156,18 @@ simpler.router.addRoute("/static-page", ["GET"], (_req, res) => {
131156
});
132157
```
133158

159+
### Redirecionando
160+
161+
Você pode redirectionar rotas com a função `redirect`, ela recebe um parametro res e a url relativa para onde deve-se redirecionar o usuário.
162+
163+
Abaixo você encontrará um exemplo de como utilizar-la.
164+
165+
```typescript
166+
simpler.router.addRoute("/redir", ["GET"], (_req, res) => {
167+
simpler.redirect(res, "/static-page");
168+
});
169+
```
170+
134171
### Lidando com Erros
135172

136173
Você pode lidar com erros de maneira customizada utilizando a função `errorHandler.setCustomErrorHandler`. A função recebe uma função como parâmetro que receberá res e error como parâmetros.
@@ -140,13 +177,14 @@ Abaixo você encontrará um exemplo de como utilizar-la.
140177
```typescript
141178
simpler.errorHandler.setCustomErrorHandler(
142179
(res: ServerResponse, error: Error) => {
143-
res.writeHead(400, { "Content-Type": "application/json" });
180+
res.writeHead(400, {
181+
"Content-Type": { "Content-Type": "application/json" },
182+
});
144183
res.end(JSON.stringify({ message: "Custom Error", error: error.message }));
145184
}
146185
);
147186
```
148187

149-
150188
### Iniciando o Servidor
151189

152190
Para iniciar o servidor, use o método `listen`. Você pode especificar o número da porta, que por padrão é 3000 se não for fornecido.
@@ -168,7 +206,12 @@ const simpler = new Simpler(true);
168206

169207
simpler.router.addRoute("/test", ["POST", "GET"], (_req, res, body) => {
170208
const parsedBody = JSON.parse(body);
171-
simpler.response(res, 200, "application/json", JSON.stringify(parsedBody));
209+
simpler.response(
210+
res,
211+
200,
212+
{ "Content-Type": "application/json" },
213+
JSON.stringify(parsedBody)
214+
);
172215
return;
173216
});
174217

@@ -177,7 +220,12 @@ simpler.router.addRoute(
177220
["POST", "GET"],
178221
(_req, res, body: string, _pathVariables, _queryParams) => {
179222
const parsedBody = JSON.parse(body);
180-
simpler.response(res, 200, "application/json", JSON.stringify(parsedBody));
223+
simpler.response(
224+
res,
225+
200,
226+
{ "Content-Type": "application/json" },
227+
JSON.stringify(parsedBody)
228+
);
181229
return;
182230
}
183231
);
@@ -187,7 +235,12 @@ simpler.router.addRoute(
187235
["POST", "GET"],
188236
(_req, res, body, _pathVariables, _queryParams) => {
189237
const parsedBody = JSON.parse(body);
190-
simpler.response(res, 200, "application/json", JSON.stringify(parsedBody));
238+
simpler.response(
239+
res,
240+
200,
241+
{ "Content-Type": "application/json" },
242+
JSON.stringify(parsedBody)
243+
);
191244
return;
192245
}
193246
);
@@ -216,4 +269,4 @@ Este projeto é licenciado sob a licença MIT. Consulte o arquivo [LICENSE](LICE
216269

217270
# Outras versões
218271

219-
[Readme em Inglês (EN)](README.md)
272+
[Readme em Inglês (EN)](README.md)

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "simpler-server",
3-
"version": "0.2.1",
3+
"version": "0.3.0",
44
"description": "Simpler is a simple Node.js server, designed to rapidly provide a base to start your server projects.",
55
"main": "dist/index.js",
66
"types": "dist/index.d.ts",

src/main/Server/server.interface.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ interface IServer {
33
listen: ListenFunction;
44
response: ResponseFunction;
55
loadFile: LoadFileFunction;
6+
redirect: RedirectFunction;
67
}
78

89
export default IServer;

src/main/Server/server.ts

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,6 @@ class Server implements IServer {
5454
const srvr = http.createServer(
5555
async (req: IncomingMessage, res: ServerResponse) => {
5656
try {
57-
console.log(req.url);
5857
const isStaticPage = await this.serveStaticFiles(req, res);
5958
if (isStaticPage) {
6059
return;
@@ -65,7 +64,7 @@ class Server implements IServer {
6564
this.response(
6665
res,
6766
404,
68-
"application/json",
67+
{ "Content-Type": "application/json" },
6968
JSON.stringify({ message: "Route Not Found" })
7069
);
7170
return;
@@ -135,7 +134,7 @@ class Server implements IServer {
135134
fileTypes[extname as FILE_EXTENSIONS] || "application/octet-stream";
136135
try {
137136
const content = await readFile(filePath);
138-
this.response(res, 200, contentType, content);
137+
this.response(res, 200, { "Content-Type": contentType }, content);
139138
this.logger.logIfVerbose(`Loaded Static File:${filePath}`);
140139
return true;
141140
} catch (error) {
@@ -149,10 +148,9 @@ class Server implements IServer {
149148

150149
public async loadFile(res: ServerResponse, urlFile: string) {
151150
const filePath = path.join(process.cwd(), urlFile);
152-
console.log("load file file path", filePath);
153151
try {
154152
const content = await readFile(filePath);
155-
this.response(res, 200, "text/html", content);
153+
this.response(res, 200, { "Content-Type": "text/html" }, content);
156154
return;
157155
} catch (error) {
158156
this.errorHandler.handleError(res, error as Error);
@@ -162,11 +160,15 @@ class Server implements IServer {
162160
public response<T>(
163161
res: ServerResponse,
164162
status: number,
165-
contentType: string,
166-
message: T
163+
headers: Record<string, string>,
164+
content: T
167165
) {
168-
res.writeHead(status, { "Content-Type": contentType });
169-
res.end(message);
166+
res.writeHead(status, headers);
167+
res.end(content);
168+
}
169+
170+
public redirect(res: ServerResponse, location: string) {
171+
this.response(res, 302, { Location: location }, null);
170172
}
171173
}
172174

0 commit comments

Comments
 (0)