-
Notifications
You must be signed in to change notification settings - Fork 10
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: add in memory db doc en-pt (#25)
- Loading branch information
Showing
3 changed files
with
274 additions
and
0 deletions.
There are no files selected for viewing
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,137 @@ | ||
--- | ||
sidebar_position: 2 | ||
--- | ||
|
||
# In Memory DB | ||
|
||
In Memory DB is a provider that uses a simple in memory database to store data. It is a class injected in the ExpressoTS dependency injection system as a singleton. | ||
|
||
This class manages tables, represented by key-value pairs, where the key is the table name and the value is an array of entities. | ||
|
||
The InMemoryDB class provides a simple and efficient way to simulate a database entirely in-memory, which can be particularly useful for testing and rapid development where a full-fledged database might be overkill. | ||
|
||
## DB Inspector | ||
|
||
Another cool feature added to the InMemoryDB class is the ability to print tables to the console using console.table. This feature is particularly useful for debugging and testing purposes. It can also be used to quickly inspect the contents of a table. | ||
|
||
The table content will be printed to the console every time the repository is used by any endpoint that have operations that read or write to the database. | ||
|
||
Here is an image showing the output in the console of the InMemoryDB when we create a new user: | ||
|
||
![Application Overview](../overview/img/inMemoryDB.png) | ||
|
||
:::info | ||
The DB inspector is enabled by default. As soon as you create a new entity and extend the BaseRepository class, the InMemoryDB will print the table to the console. | ||
::: | ||
|
||
## Class Definition | ||
|
||
Detail explanation of InMemoryDB class definition. | ||
|
||
```typescript | ||
@provideSingleton(InMemoryDB) | ||
class InMemoryDB { | ||
private tables: Record<string, IEntity[]> = {}; | ||
// Method definitions ... | ||
} | ||
``` | ||
|
||
This decorator indicates that the InMemoryDB class is a Singleton within the dependency injection system. | ||
|
||
```typescript | ||
@provideSingleton(InMemoryDB) | ||
``` | ||
|
||
Class Properties tables is a private property that holds the in-memory tables. Each table is a key-value pair where the key is the table name, and the value is an array of entities (IEntity[]). | ||
|
||
```typescript | ||
private tables: Record<string, IEntity[]> = {}; | ||
``` | ||
|
||
## Class Methods | ||
|
||
InMemoryDB class provides the following methods: | ||
|
||
### Get Table Method | ||
|
||
```typescript | ||
getTable(tableName: string): IEntity[] | ||
``` | ||
|
||
Parameters | ||
|
||
- tableName (string): The name of the table to retrieve. | ||
- Returns: IEntity[]: An array of entities stored in the specified table. | ||
- Description: Retrieves a table by its name from the in-memory database. If the table doesn't exist, it initializes an empty table. | ||
|
||
### Show Tables Method | ||
|
||
```typescript | ||
showTables(): void | ||
``` | ||
|
||
Description: Prints a list of all existing tables in the in-memory database to the standard output. If no tables exist, it outputs "No tables exist." | ||
|
||
### Print Table Method | ||
|
||
```typescript | ||
printTable(tableName: string): void | ||
``` | ||
|
||
Parameters | ||
|
||
- tableName (string): The name of the table whose records should be printed. | ||
- Description: Prints all records in a specific table to the console using console.table. If the table doesn't exist or is empty, it notifies the user through standard output. | ||
|
||
:::info | ||
In the opinionated template the InMemoryDB is already implemented in the BaseRepository class. You don't need to use it directly. | ||
::: | ||
|
||
## How to Extend BaseRepository | ||
|
||
Here is a code snippet that shows how to extend the BaseRepository class to implement a custom repository. | ||
|
||
```typescript | ||
@provide(UserRepository) | ||
class UserRepository extends BaseRepository<User> { | ||
constructor() { | ||
super("users"); | ||
} | ||
} | ||
``` | ||
|
||
The UserRepository class is a specialized repository tailored for managing User entities. It extends the generic BaseRepository class and sets its table name to "users" upon construction. This class is part of the dependency injection system and is marked by the @provide decorator. | ||
|
||
Any custom methods can be added to the UserRepository class. For example, the following code snippet shows how to implement a findByEmail method that searches for a user by email. | ||
|
||
```typescript | ||
@provide(UserRepository) | ||
class UserRepository extends BaseRepository<User> { | ||
constructor() { | ||
super("users"); | ||
} | ||
|
||
// Custom method implemented for the UserRepository only | ||
findByEmail(email: string): User | null { | ||
const user = this.table.find((item) => item.email === email); | ||
return user || null; | ||
} | ||
} | ||
``` | ||
|
||
:::caution SPOILER ALERT | ||
In the future, we plan to extend the repository pattern to support various databases, all easily scaffoldable through our CLI | ||
::: | ||
|
||
--- | ||
|
||
## Support the Project | ||
|
||
ExpressoTS is an MIT-licensed open source project. It's an independent project with ongoing development made possible thanks to your support. If you'd like to help, please consider: | ||
|
||
- Become a **[sponsor on GitHub](https://github.com/sponsors/expressots)** | ||
- Follow the **[organization](https://github.com/expressots)** on GitHub and Star ⭐ the project | ||
- Subscribe to the Twitch channel: **[Richard Zampieri](https://www.twitch.tv/richardzampieri)** | ||
- Join our **[Discord](https://discord.com/invite/PyPJfGK)** | ||
- Contribute submitting **[issues and pull requests](https://github.com/expressots/expressots/issues/new/choose)** | ||
- Share the project with your friends and colleagues |
137 changes: 137 additions & 0 deletions
137
i18n/pt/docusaurus-plugin-content-docs/current/providers/in-memory-db.md
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,137 @@ | ||
--- | ||
sidebar_position: 2 | ||
--- | ||
|
||
# BD em Memória | ||
|
||
O BD em Memória é um provedor que usa um banco de dados simples em memória para armazenar dados. É uma classe injetada no sistema de injeção de dependência do ExpressoTS como um singleton. | ||
|
||
Essa classe gerencia tabelas, representadas por pares chave-valor, onde a chave é o nome da tabela e o valor é um array de entidades. | ||
|
||
A classe InMemoryDB fornece uma forma simples e eficiente de simular um banco de dados totalmente em memória, o que pode ser particularmente útil para testes e desenvolvimento rápido onde um banco de dados completo pode ser excessivo. | ||
|
||
## Inspetor de BD | ||
|
||
Outra característica interessante adicionada à classe InMemoryDB é a capacidade de imprimir tabelas no console usando console.table. Esta característica é particularmente útil para fins de depuração e teste. Também pode ser usada para inspecionar rapidamente o conteúdo de uma tabela. | ||
|
||
O conteúdo da tabela será impresso no console sempre que o repositório for utilizado por qualquer endpoint que tenha operações de leitura ou gravação no banco de dados. | ||
|
||
Aqui está uma imagem mostrando a saída no console do InMemoryDB quando criamos um novo usuário: | ||
|
||
![Application Overview](../overview/img/inMemoryDB.png) | ||
|
||
:::info | ||
O Inspetor de BD está ativado por padrão. Assim que você criar uma nova entidade e estender a classe BaseRepository, o InMemoryDB imprimirá a tabela no console. | ||
::: | ||
|
||
## Definição da Classe | ||
|
||
Explicação detalhada da definição da classe InMemoryDB. | ||
|
||
```typescript | ||
@provideSingleton(InMemoryDB) | ||
class InMemoryDB { | ||
private tables: Record<string, IEntity[]> = {}; | ||
// Definições de métodos ... | ||
} | ||
``` | ||
|
||
Este decorador indica que a classe InMemoryDB é um Singleton dentro do sistema de injeção de dependência. | ||
|
||
```typescript | ||
@provideSingleton(InMemoryDB) | ||
``` | ||
|
||
Propriedades da classe tables é uma propriedade privada que mantém as tabelas em memória. Cada tabela é um par chave-valor onde a chave é o nome da tabela, e o valor é um array de entidades (IEntity[]). | ||
|
||
```typescript | ||
private tables: Record<string, IEntity[]> = {}; | ||
``` | ||
|
||
## Métodos da Classe | ||
|
||
A classe InMemoryDB fornece os seguintes métodos: | ||
|
||
### Método Get Table | ||
|
||
```typescript | ||
getTable(tableName: string): IEntity[] | ||
``` | ||
|
||
Parâmetros | ||
|
||
- tableName (string): O nome da tabela a ser recuperada. | ||
- Retorna: IEntity[]: Um array de entidades armazenadas na tabela especificada. | ||
- Descrição: Recupera uma tabela pelo nome do banco de dados em memória. Se a tabela não existir, inicializa uma tabela vazia. | ||
|
||
### Método Show Tables | ||
|
||
```typescript | ||
showTables(): void | ||
``` | ||
|
||
Descrição: Imprime uma lista de todas as tabelas existentes no banco de dados em memória na saída padrão. Se não existirem tabelas, ele exibe "Nenhuma tabela existe". | ||
|
||
### Método Print Table | ||
|
||
```typescript | ||
printTable(tableName: string): void | ||
``` | ||
|
||
Parâmetros | ||
|
||
- tableName (string): O nome da tabela cujos registros devem ser impressos. | ||
- Descrição: Imprime todos os registros em uma tabela específica no console usando console.table. Se a tabela não existir ou estiver vazia, notifica o usuário pela saída padrão. | ||
|
||
:::info | ||
No modelo opinativo, o InMemoryDB já está implementado na classe BaseRepository. Você não precisa usá-lo diretamente. | ||
::: | ||
|
||
## Como Estender BaseRepository | ||
|
||
Aqui está um trecho de código que mostra como estender a classe BaseRepository para implementar um repositório personalizado. | ||
|
||
```typescript | ||
@provide(UserRepository) | ||
class UserRepository extends BaseRepository<User> { | ||
constructor() { | ||
super("users"); | ||
} | ||
} | ||
``` | ||
|
||
A classe UserRepository é um repositório especializado voltado para o gerenciamento de entidades de usuário. Ela estende a classe genérica BaseRepository e define seu nome de tabela como "users" durante a construção. Esta classe faz parte do sistema de injeção de dependência e é marcada pelo decorador @provide. | ||
|
||
Qualquer método personalizado pode ser adicionado à classe UserRepository. Por exemplo, o seguinte trecho de código mostra como implementar um método findByEmail que procura um usuário por e-mail. | ||
|
||
```typescript | ||
@provide(UserRepository) | ||
class UserRepository extends BaseRepository<User> { | ||
constructor() { | ||
super("users"); | ||
} | ||
|
||
// Método personalizado implementado apenas para o UserRepository | ||
findByEmail(email: string): User | null { | ||
const user = this.table.find((item) => item.email === email); | ||
return user || null; | ||
} | ||
} | ||
``` | ||
|
||
:::caution SPOILER ALERT | ||
No futuro, planejamos estender o padrão de repositório para suportar vários bancos de dados, todos facilmente montáveis através do nosso CLI | ||
::: | ||
|
||
--- | ||
|
||
## Apoie o projeto | ||
|
||
ExpressoTS é um projeto de código aberto licenciado sob o MIT. É um projeto independente com desenvolvimento contínuo possibilitado graças ao seu suporte. Se você deseja ajudar, por favor considere: | ||
|
||
- Se tornar um **[Sponsor no GitHub](https://github.com/sponsors/expressots)** | ||
- Siga a **[organização](https://github.com/expressots)** no GitHub e de um Star ⭐ no projeto | ||
- Subscreva no nosso canal na Twitch: **[Richard Zampieri](https://www.twitch.tv/richardzampieri)** | ||
- Entre no nosso **[Discord](https://discord.com/invite/PyPJfGK)** | ||
- Contribua submetendo **[issues e pull requests](https://github.com/expressots/expressots/issues/new/choose)** | ||
- Compartilhe o projeto com seus amigos e colegas |