Skip to content

Commit

Permalink
Merge pull request #3 from JooLuiz/feat/load-page
Browse files Browse the repository at this point in the history
[feat] - Implementing Error handler and loadFile function
  • Loading branch information
JooLuiz authored Jul 6, 2024
2 parents 1ddca23 + 2200aad commit 67e3717
Show file tree
Hide file tree
Showing 19 changed files with 274 additions and 107 deletions.
4 changes: 4 additions & 0 deletions .npmignore
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,7 @@ node_modules/
.editorconfig
.gitignore
.npmrc

src/static/

src/dev.ts
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,16 @@ and this project adheres to [Semantic Versioning](http://semver.org/).

## [Unreleased] - yyyy-mm-dd

## [0.2.0] - 2024-07-06

### Added

- Implementing Error handler and loadFile function

### Fixed

- Adjusting the serveStaticFiles function

## [0.1.2] - 2024-07-05

### Fixed
Expand Down
46 changes: 36 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,33 @@ simpler.router.addRoute("/static", ["GET"], (_req, res) => {
});
```

### Loading Files

You can load files with simpler with the function `loadFile`, it receives a res and the relative path to the file.

Below you'll find an example of how to use it.

```typescript
simpler.router.addRoute("/static-page", ["GET"], (_req, res) => {
simpler.loadFile(res, "./static/teste.html");
});
```

### Handling errors

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.

Below you'll find an example of how to use it.

```typescript
simpler.errorHandler.setCustomErrorHandler(
(res: ServerResponse, error: Error) => {
res.writeHead(400, { "Content-Type": "application/json" });
res.end(JSON.stringify({ message: "Custom Error", error: error.message }));
}
);
```

### Starting the Server

To start the server, use the `listen` method. You can specify the port number, which defaults to 3000 if not provided.
Expand Down Expand Up @@ -166,18 +193,17 @@ simpler.router.addRoute(

simpler.router.addStaticDirectory("static");

simpler.router.addRoute("/static", ["GET"], (_req, res) => {
const testePath = path.join(__dirname, "static", "teste.html");
readFile(testePath, (err, data) => {
if (err) {
simpler.response(res, 500, "text/plain", "500 Internal Server Error");
return;
}

simpler.response(res, 200, "text/html", data);
});
simpler.router.addRoute("/static-page", ["GET"], (_req, res) => {
simpler.loadFile(res, "./static/teste.html");
});

simpler.errorHandler.setCustomErrorHandler(
(res: ServerResponse, error: Error) => {
res.writeHead(400, { "Content-Type": "application/json" });
res.end(JSON.stringify({ message: "Custom Error", error: error.message }));
}
);

simpler.listen(3001);
```

Expand Down
47 changes: 37 additions & 10 deletions README.pt-br.md
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,34 @@ simpler.router.addRoute("/static", ["GET"], (_req, res) => {
});
```

### Carregando arquivos

Você pode carregar arquivos com simpler utilizando a função `loadFile`, a função recebe um res a o caminho relativo para o arquivo.

Abaixo você encontrará um exemplo de como utilizar-la.

```typescript
simpler.router.addRoute("/static-page", ["GET"], (_req, res) => {
simpler.loadFile(res, "./static/teste.html");
});
```

### Lidando com Erros

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.

Abaixo você encontrará um exemplo de como utilizar-la.

```typescript
simpler.errorHandler.setCustomErrorHandler(
(res: ServerResponse, error: Error) => {
res.writeHead(400, { "Content-Type": "application/json" });
res.end(JSON.stringify({ message: "Custom Error", error: error.message }));
}
);
```


### Iniciando o Servidor

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.
Expand Down Expand Up @@ -166,18 +194,17 @@ simpler.router.addRoute(

simpler.router.addStaticDirectory("static");

simpler.router.addRoute("/static", ["GET"], (_req, res) => {
const testePath = path.join(__dirname, "static", "teste.html");
readFile(testePath, (err, data) => {
if (err) {
simpler.response(res, 500, "text/plain", "500 Internal Server Error");
return;
}

simpler.response(res, 200, "text/html", data);
});
simpler.router.addRoute("/static-page", ["GET"], (_req, res) => {
simpler.loadFile(res, "./static/teste.html");
});

simpler.errorHandler.setCustomErrorHandler(
(res: ServerResponse, error: Error) => {
res.writeHead(400, { "Content-Type": "application/json" });
res.end(JSON.stringify({ message: "Custom Error", error: error.message }));
}
);

simpler.listen(3001);
```

Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "simpler-server",
"version": "0.1.2",
"version": "0.2.0",
"description": "Simpler is a simple Node.js server, designed to rapidly provide a base to start your server projects.",
"main": "dist/index.js",
"types": "dist/index.d.ts",
Expand All @@ -16,7 +16,7 @@
"type": "git",
"url": "[email protected]:JooLuiz/simpler.git"
},
"keywords": [],
"keywords": ["Node Server"],
"author": "João Luiz de Castro (https://github.com/JooLuiz)",
"license": "ISC",
"devDependencies": {
Expand Down
6 changes: 6 additions & 0 deletions src/main/ErrorHandler/errorHandler.interface.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
interface IErrorHandler {
handleError: HandleErrorFunction;
setCustomErrorHandler: SetCustomErrorHandlerFunction;
}

export default IErrorHandler;
42 changes: 42 additions & 0 deletions src/main/ErrorHandler/errorHandler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { ServerResponse } from "http";
import type ILogger from "../Logger/logger.interface";
import type IErrorHandler from "./errorHandler.interface";

import Logger from "../Logger";

class ErrorHandler implements IErrorHandler {
private logger: ILogger;

constructor(isVerbose: boolean) {
this.logger = new Logger(isVerbose);
}

private defaultErrorHandler: HandleErrorFunction = (
res: ServerResponse,
error: Error
) => {
this.logger.error(
`An error happening when processing the callback: ${error.message}`
);
res.writeHead(500, { "Content-Type": "application/json" });
res.end(
JSON.stringify({ message: "Internal Server Error", error: error.message })
);
};

private customErrorHandler?: HandleErrorFunction;

public handleError(res: ServerResponse, error: Error): void {
if (this.customErrorHandler) {
this.customErrorHandler(res, error);
} else {
this.defaultErrorHandler(res, error);
}
}

public setCustomErrorHandler(handler: HandleErrorFunction): void {
this.customErrorHandler = handler;
}
}

export default ErrorHandler;
3 changes: 3 additions & 0 deletions src/main/ErrorHandler/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import ErrorHandler from "./errorHandler";

export default ErrorHandler
6 changes: 3 additions & 3 deletions src/main/Logger/logger.interface.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
interface ILogger {
log: (message: string) => void;
logIfVerbose: (message: string, isVerbose: boolean) => void;
error: (message: string) => void;
log: LoggerFunction;
logIfVerbose: LoggerFunction;
error: LoggerFunction;
}

export default ILogger;
14 changes: 9 additions & 5 deletions src/main/Logger/logger.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,23 @@
import ILogger from "./logger.interface";

class Logger implements ILogger {
constructor() {}
private isVerbose: boolean;

log(message: string) {
constructor(isVerbose: boolean) {
this.isVerbose = isVerbose;
}

public log(message: string) {
console.log(message);
}

logIfVerbose(message: string, isVerbose: boolean) {
if (isVerbose) {
public logIfVerbose(message: string) {
if (this.isVerbose) {
this.log(message);
}
}

error(message: string) {
public error(message: string) {
console.error(message);
}
}
Expand Down
23 changes: 15 additions & 8 deletions src/main/Router/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,21 +6,28 @@ class Router implements IRouter {

constructor() {}

addRoute(url: string, method: METHODS[], callback: RouteCallback): void {
public addRoute(
url: string,
method: METHODS[],
callback: RouteCallback
): void {
this.routes.push({
url,
method,
callback,
});
}

addRoutes(routes: [Route]) {
public addRoutes(routes: [Route]) {
routes.forEach((route) => {
this.addRoute(route.url, route.method, route.callback);
});
}

getRoute(url: string | undefined, method: string | undefined): Route | null {
public getRoute(
url: string | undefined,
method: string | undefined
): Route | null {
if (!url || !method) {
return null;
}
Expand All @@ -45,7 +52,7 @@ class Router implements IRouter {
return route;
}

getPathVariables(
public getPathVariables(
reqUrl: string | undefined,
routeUrl: string
): Record<string, string> {
Expand All @@ -66,7 +73,7 @@ class Router implements IRouter {
return pathVariables;
}

getQueryParams(url: string | undefined): Record<string, string> {
public getQueryParams(url: string | undefined): Record<string, string> {
if (!url) return {};

const queryParams: Record<string, string> = {};
Expand All @@ -83,17 +90,17 @@ class Router implements IRouter {
return queryParams;
}

addStaticDirectory(directory: string) {
public addStaticDirectory(directory: string) {
this.staticDirs.push(directory);
}

addStaticDirectories(directories: string[]) {
public addStaticDirectories(directories: string[]) {
directories.forEach((dir) => {
this.addStaticDirectory(dir);
});
}

getStaticDirs() {
public getStaticDirs() {
return this.staticDirs;
}
}
Expand Down
1 change: 1 addition & 0 deletions src/main/Server/server.interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ interface IServer {
handleRequest: HandleRequestFunction;
listen: ListenFunction;
response: ResponseFunction;
loadFile: LoadFileFunction;
}

export default IServer;
Loading

0 comments on commit 67e3717

Please sign in to comment.