Skip to content

Commit

Permalink
Merge pull request #1 from JooLuiz/feat/creating-server
Browse files Browse the repository at this point in the history
[feat] - Creating server
  • Loading branch information
JooLuiz authored Jul 5, 2024
2 parents 8c81491 + b7686fd commit 868b219
Show file tree
Hide file tree
Showing 27 changed files with 6,682 additions and 11 deletions.
14 changes: 14 additions & 0 deletions .eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 2020,
"sourceType": "module"
},
"plugins": ["@typescript-eslint"],
"extends": ["eslint:recommended", "plugin:@typescript-eslint/recommended"],
"rules": {
"no-unused-vars": "off",
"@typescript-eslint/no-unused-vars": ["error"]
}
}

4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
node_modules
dist
src/dev.ts
src/static
27 changes: 27 additions & 0 deletions .npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Arquivos de configuração
.eslintrc
.prettierrc
.stylelintrc

# Arquivos de teste
__tests__
test/
tests/
*.test.ts
*.spec.ts

# Pastas e arquivos de build
build/
lib/
*.log

# Arquivos temporários
*.tmp

# Dependências locais instaladas
node_modules/

# Outros arquivos que não são necessários para o pacote publicado
.editorconfig
.gitignore
.npmrc
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,14 @@ and this project adheres to [Semantic Versioning](http://semver.org/).

### Added

- Implementing tests for Logger, Router and Server

- Creating Simpler server README.md file.

- Creating Simpler server response method.

- Creating Simpler server methods to serve static files.

- Creating Simpler server base structure (Server, Router and Logger) to deal with API routes.

- Adding github actions, changelog and readme files.
190 changes: 184 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,14 +1,192 @@
# Simpler
# Simpler Server

![Node.js](https://img.shields.io/badge/Node.js-v14.17.3-green)
![License](https://img.shields.io/badge/license-MIT-blue)

Simpler é um servidor Node.js simples, projetado para fornecer uma base para iniciar rapidamente seus projetos de servidor.
Simpler is a lightweight, customizable Node.js server framework. It allows you to define routes, handle dynamic path variables, query parameters, and serve static files with ease.

## Licença
## Installation

Este projeto está licenciado sob a Licença MIT. Veja o arquivo [LICENSE](LICENSE) para mais detalhes.
To install Simpler, you can use npm:

# Outras versões
```bash
npm install simpler-server
```

[Readme in Portuguese (PT-BR)](README.pt-br.md)
## Usage

### Creating an Instance

You can create an instance of Simpler by importing it and optionally enabling verbose logging:

```typescript
import Simpler from "simpler-server";

const simpler = new Simpler(true); // Enable verbose logging
```

### Defining Routes

You can define routes using the `addRoute` or the `addRoutes` methods. The same route can handle multiple methods, and you can define dynamic path variables using `:`. The callback function for a route will always receive `req`, `res`, `body`, `pathVariables`, and `queryParams`.

pathVariables and queryParams are the objects with the values of the path parameters and query parameters.

Simpler has a response method that will run the default response methods, you can either set a response via simpler or directly in res, below are some examples and their equivalent:

```typescript
//Returning with simpler
simpler.response(res, 200, "application/json", JSON.stringify(parsedBody));

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

//Returning with simpler
simpler.response(res, 200, "text/html", data);

//Equivalent returning directly with res
res.writeHead(200, { "Content-Type": "text/html" });
res.end(data);
```

Below you'll find examples on how to use the `addRoute` method.

```typescript
simpler.router.addRoute(
"/test",
["POST", "GET"],
(_req, res, body, _pathVariables, _queryParams) => {
const parsedBody = JSON.parse(body);
simpler.response(res, 200, "application/json", JSON.stringify(parsedBody));
return;
}
);

simpler.router.addRoute(
"/test/:id",
["POST", "GET"],
(_req, res, body, _pathVariables, _queryParams) => {
const parsedBody = JSON.parse(body);
/*
Path variables example:
pathVariables: {
"id": "{value}"
}
*/
simpler.response(res, 200, "application/json", JSON.stringify(parsedBody));
return;
}
);

simpler.router.addRoute(
"/test/:id/:xpto",
["POST", "GET"],
(_req, res, body, _pathVariables, _queryParams) => {
const parsedBody = JSON.parse(body);
/*
Path variables example:
pathVariables: {
"id": "{value1}",
"xpto": "{value2}",
}
*/
simpler.response(res, 200, "application/json", JSON.stringify(parsedBody));
return;
}
);
```

### Serving Static Files

You can configure Simpler to serve static files from a directory using the `addStaticDirectory` or `addStaticDirectories` methods. Additionally, you can load an HTML page in a route.

```typescript
import path from "path";
import { readFile } from "fs";

simpler.router.addStaticDirectory("static");

simpler.router.addRoute("/static", ["GET"], (_req, res) => {
const testePath = path.join(__dirname, "static", "test.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);
});
});
```

### Starting the Server

To start the server, use the `listen` method. You can specify the port number, which defaults to 3000 if not provided.

```typescript
simpler.listen(3001);
```

### Implementation Example

Here is an example of a full setup using Simpler:

```typescript
import { readFile } from "fs";
import Simpler from "simpler-server";
import path from "path";

const simpler = new Simpler(true);

simpler.router.addRoute("/test", ["POST", "GET"], (_req, res, body) => {
const parsedBody = JSON.parse(body);
simpler.response(res, 200, "application/json", JSON.stringify(parsedBody));
return;
});

simpler.router.addRoute(
"/test/:id",
["POST", "GET"],
(_req, res, body: string, _pathVariables, _queryParams) => {
const parsedBody = JSON.parse(body);
simpler.response(res, 200, "application/json", JSON.stringify(parsedBody));
return;
}
);

simpler.router.addRoute(
"/test/:id/:xpto",
["POST", "GET"],
(_req, res, body, _pathVariables, _queryParams) => {
const parsedBody = JSON.parse(body);
simpler.response(res, 200, "application/json", JSON.stringify(parsedBody));
return;
}
);

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.listen(3001);
```

By following these instructions, you can set up and run your Simpler server, configure routes, handle dynamic path variables, query parameters, and serve static files with ease.

## License

This project is licensed under the MID license. Check file [LICENSE](LICENSE) for more details.

# Other versions

[Readme in Portuguese (PT-BR)](README.pt-br.md)
Loading

0 comments on commit 868b219

Please sign in to comment.