vsrepo 2.6.0 → 2.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +45 -3
- package/README.md +40 -102
- package/README.pt-BR.md +40 -102
- package/dist/VSRepoAdapter.d.ts +12 -0
- package/dist/VSRepoAdapter.js.map +1 -1
- package/dist/VSRepository.d.ts +50 -4
- package/dist/VSRepository.js +57 -28
- package/dist/VSRepository.js.map +1 -1
- package/dist/decorators/query-method.decorator.d.ts +3 -24
- package/dist/decorators/query-method.decorator.js +4 -27
- package/dist/decorators/query-method.decorator.js.map +1 -1
- package/dist/index.d.ts +4 -0
- package/dist/index.js +5 -1
- package/dist/index.js.map +1 -1
- package/dist/internal/resolvers/dynamic-methods.resolver.d.ts +6 -5
- package/dist/internal/resolvers/dynamic-methods.resolver.js +118 -100
- package/dist/internal/resolvers/dynamic-methods.resolver.js.map +1 -1
- package/dist/internal/utils/vs-placeholder-parser.util.d.ts +2 -0
- package/dist/internal/utils/vs-placeholder-parser.util.js +62 -0
- package/dist/internal/utils/vs-placeholder-parser.util.js.map +1 -0
- package/dist/internal/utils/vs-query-builder.util.d.ts +5 -1
- package/dist/internal/utils/vs-query-builder.util.js +1 -13
- package/dist/internal/utils/vs-query-builder.util.js.map +1 -1
- package/dist/internal/utils/vs-raw-query-builder.util.d.ts +238 -0
- package/dist/internal/utils/vs-raw-query-builder.util.js +433 -0
- package/dist/internal/utils/vs-raw-query-builder.util.js.map +1 -0
- package/dist/internal/utils/vs-sql.util.d.ts +100 -0
- package/dist/internal/utils/vs-sql.util.js +151 -0
- package/dist/internal/utils/vs-sql.util.js.map +1 -0
- package/dist/internal/validators/decorators.validator.js +1 -1
- package/dist/internal/validators/decorators.validator.js.map +1 -1
- package/dist/internal/validators/vsrepo.validator.js +1 -0
- package/dist/internal/validators/vsrepo.validator.js.map +1 -1
- package/dist/types/vsrepo/vs-raw-query-builder-cte-query.type.d.ts +8 -0
- package/dist/types/vsrepo/vs-raw-query-builder-cte-query.type.js +3 -0
- package/dist/types/vsrepo/vs-raw-query-builder-cte-query.type.js.map +1 -0
- package/dist/types/vsrepo/vs-raw-query-builder-target.type.d.ts +7 -0
- package/dist/types/vsrepo/vs-raw-query-builder-target.type.js +3 -0
- package/dist/types/vsrepo/vs-raw-query-builder-target.type.js.map +1 -0
- package/dist/types/vsrepo/vsrepo-options.type.d.ts +18 -0
- package/package.json +4 -3
package/CHANGELOG.md
CHANGED
|
@@ -6,6 +6,48 @@ All notable changes to this project will be documented in this file.
|
|
|
6
6
|
|
|
7
7
|
---
|
|
8
8
|
|
|
9
|
+
## [2.7.1] - 2026-09-28
|
|
10
|
+
|
|
11
|
+
### Fixed
|
|
12
|
+
- A dynamic method now resolves every parameter by its own position instead of relying on the end of the argument list — the `options` are read from the first argument after the expected parameters, and the payload (`data`/`create`/`update`), `order` and `pagination` of a method called with more than one extra argument are now read from the correct slots instead of shifting onto the `options` object. Arguments beyond the expected parameters plus `options` are ignored
|
|
13
|
+
- A failing dynamic method is no longer logged at `ERROR` by the resolver — the error is simply rethrown to the caller and the execution time is still recorded by `endPerformLog`, leaving `ERROR` for validation and guard-clause failures. This is the last call site that still logged it: the base methods, `query()` and the query methods had already stopped in **2.0.0**
|
|
14
|
+
|
|
15
|
+
### Documentation
|
|
16
|
+
- Both logging guides now describe `ERROR` accurately: it is logged for validation and guard-clause failures right before the `VSRepoError` is thrown, while a failure raised by the adapter itself is no longer logged and simply propagates to the caller
|
|
17
|
+
|
|
18
|
+
## [2.7.1] - 2026-09-28 (Português)
|
|
19
|
+
|
|
20
|
+
### Corrigido
|
|
21
|
+
- Um método dinâmico agora resolve cada parâmetro pela sua própria posição em vez de depender do fim da lista de argumentos — as `options` são lidas do primeiro argumento depois dos parâmetros esperados, e o payload (`data`/`create`/`update`), o `order` e a `pagination` de um método chamado com mais de um argumento extra passam a ser lidos dos slots corretos, em vez de deslocarem para o objeto de options. Argumentos além dos parâmetros esperados mais as options são ignorados
|
|
22
|
+
- Um método dinâmico que falha não é mais logado em `ERROR` pelo resolver — o erro simplesmente é relançado para quem chamou e o tempo de execução continua sendo registrado por `endPerformLog`, deixando o `ERROR` para falhas de validação e de guarda. Esta é a última chamada que ainda registrava o erro: os métodos base, o `query()` e os query methods já haviam parado na **2.0.0**
|
|
23
|
+
|
|
24
|
+
### Documentação
|
|
25
|
+
- Os dois guias de logging agora descrevem o `ERROR` com precisão: ele é registrado para falhas de validação e de guarda logo antes do `VSRepoError` ser lançado, enquanto uma falha lançada pelo próprio adapter não é mais registrada e simplesmente propaga para quem chamou
|
|
26
|
+
|
|
27
|
+
## [2.7.0] - 2026-09-26
|
|
28
|
+
|
|
29
|
+
### Added
|
|
30
|
+
- **`createRawQueryBuilder(db?)`** — new method on every `VSRepository` that returns a fluent, SQL-agnostic `VSRawQueryBuilder` for hand-written `SELECT` queries too SQL-specific (window functions, vendor-specific syntax, ad-hoc subqueries, CTEs, ...) for `createQueryBuilder()`'s `where`/`relations` model. Chain `select`, `from`, `innerJoin`/`leftJoin`/`rightJoin`/`fullJoin`, `where`/`andWhere`/`orWhere`, `groupBy`, `having`/`andHaving`/`orHaving`, `orderBy`, `limit` and `offset` — each accepting either a raw, trusted string (an identifier, or a parameter-free condition for `on`/`where`/`having`, e.g. `.andWhere("deleted_at is null")`) or a `VSSql` fragment for anything parameterized. `from()`/joins also accept another `VSRawQueryBuilder`, or a subquery function (`sub => sub.select(...)...`) that receives a fresh builder sharing the same `db`/adapter/logger, compiled inline as a subquery; any subquery can also be spliced directly into a `VSSql` fragment via `toVSSql()` (e.g. inside a `WHERE ... IN (...)`). `with(name, query, columns?)`/`withRecursive(name, query, columns?)` add named CTEs (a single `WITH RECURSIVE` clause once any CTE is recursive) that the rest of the query can reference like real tables. Run it with `toVSSql()` (the compiled `VSSql` fragment), `toSql()` (the plain SQL string, rendered with the adapter's placeholder syntax) or `execute<T>()` (runs it through the adapter and returns the result); all three require the adapter to implement `getPlaceholder()`. The builder respects `clone()` and lazy `setDb()`, same as `createQueryBuilder()`, and is exported as `VSRawQueryBuilder`/`VSRawQueryBuilderTarget`/`VSRawQueryBuilderCteQuery`. Every raw string accepted as an identifier, condition, alias or CTE name/column is validated as non-empty/non-blank as soon as it's passed, throwing a `VSRepoError` instead of silently compiling into broken SQL
|
|
31
|
+
- **`VSSql`** — ORM-agnostic, composable SQL fragments for raw queries: build one with `VSSql.sql` (a tagged template where every interpolated value becomes a bound parameter), `VSSql.raw` (inserts trusted, unparameterized text — for identifiers only, never user input), `VSSql.join` (builds a parameterized list, e.g. an `IN (...)`) and `VSSql.empty` (contributes no text/params, for conditional fragments). Fragments nest freely and the placeholder numbering stays correct; passing one to `VSRepository.query()` compiles it through `adapter.getPlaceholder()` — so `VSSql` works with every database and is safe from SQL injection by construction
|
|
32
|
+
- **`vsPlaceholders`** constructor option — when `true`, raw SQL strings passed to `query()` and `@QueryMethod` use VSRepository's own agnostic, 1-based, positional placeholders (`?1`, `?2`, ...) instead of the adapter's native syntax; the same index can repeat (`?1 ... ?1`) to reuse an argument. Requires the adapter to implement `getPlaceholder()` — enabling it without one throws a `VSRepoError`
|
|
33
|
+
- **`VSRepoAdapter.getPlaceholder?`** — new optional adapter method declaring the placeholder syntax for the Nth (0-based) bound parameter (e.g. `` `$${index + 1}` `` for PostgreSQL, `"?"` for SQLite/MySQL). Implementing it is what enables `VSSql` fragments and `vsPlaceholders`
|
|
34
|
+
- **Query method logs** — `query()` and `@QueryMethod` now log the compiled query and its args at `DEBUG` (the `db` is never logged) and time the execution (`Took Xms ...`, promoted to `WARN` above `logSlowThresholdMs`), like the rest of the library
|
|
35
|
+
|
|
36
|
+
### Documentation
|
|
37
|
+
- New [Raw query builder](./docs/raw-query-builder.md) guide, covering `createRawQueryBuilder()`, building the query, subqueries (builder or function), CTEs with `with()`/`withRecursive()`, running it (`toVSSql`/`toSql`/`execute`), transactions/`setDb()`, cloning, validation and logs — added to both READMEs' documentation index, with a cross-link from the [Query builder](./docs/query-builder.md) guide
|
|
38
|
+
|
|
39
|
+
## [2.7.0] - 2026-09-26 (Português)
|
|
40
|
+
|
|
41
|
+
### Adicionado
|
|
42
|
+
- **`createRawQueryBuilder(db?)`** — novo método em todo `VSRepository` que retorna um `VSRawQueryBuilder` fluente e agnóstico de SQL para queries `SELECT` escritas à mão, específicas demais (funções de janela, sintaxe específica do banco, subqueries ad-hoc, CTEs, ...) para o modelo `where`/`relations` do `createQueryBuilder()`. Encadeie `select`, `from`, `innerJoin`/`leftJoin`/`rightJoin`/`fullJoin`, `where`/`andWhere`/`orWhere`, `groupBy`, `having`/`andHaving`/`orHaving`, `orderBy`, `limit` e `offset` — cada um aceitando uma string crua e confiável (um identificador, ou uma condição sem parâmetros para `on`/`where`/`having`, ex.: `.andWhere("deleted_at is null")`) ou um fragmento `VSSql` para qualquer coisa parametrizada. `from()`/joins também aceitam outro `VSRawQueryBuilder`, ou uma função de subquery (`sub => sub.select(...)...`) que recebe um builder novo compartilhando o mesmo `db`/adapter/logger, compilada inline como subquery; qualquer subquery também pode ser inserida diretamente num fragmento `VSSql` via `toVSSql()` (ex.: dentro de um `WHERE ... IN (...)`). `with(name, query, columns?)`/`withRecursive(name, query, columns?)` adicionam CTEs nomeadas (uma única cláusula `WITH RECURSIVE` quando qualquer CTE é recursiva) que o resto da query pode referenciar como tabelas normais. Execute com `toVSSql()` (o fragmento `VSSql` compilado), `toSql()` (a string SQL simples, renderizada com a sintaxe de placeholder do adapter) ou `execute<T>()` (executa através do adapter e retorna o resultado); os três exigem que o adapter implemente `getPlaceholder()`. O builder respeita `clone()` e `setDb()` lazy, igual ao `createQueryBuilder()`, e é exportado como `VSRawQueryBuilder`/`VSRawQueryBuilderTarget`/`VSRawQueryBuilderCteQuery`. Toda string crua aceita como identificador, condição, alias ou nome/coluna de CTE é validada como não-vazia/não-em-branco assim que é passada, lançando um `VSRepoError` em vez de compilar silenciosamente em SQL quebrado
|
|
43
|
+
- **`VSSql`** — fragmentos SQL agnósticos de ORM e componíveis para queries raw: monte um com `VSSql.sql` (um template literal com tag em que todo valor interpolado vira um parâmetro ligado), `VSSql.raw` (insere texto confiável e não parametrizado — só para identificadores, nunca input do usuário), `VSSql.join` (monta uma lista parametrizada, ex.: um `IN (...)`) e `VSSql.empty` (não contribui com texto nem parâmetros, para fragmentos condicionais). Fragmentos aninham livremente e a numeração dos placeholders continua correta; passar um para o `VSRepository.query()` compila via `adapter.getPlaceholder()` — então `VSSql` funciona com qualquer banco e é seguro contra SQL injection por construção
|
|
44
|
+
- **Option `vsPlaceholders`** no construtor — quando `true`, strings SQL cruas passadas para `query()` e `@QueryMethod` usam os placeholders próprios, agnósticos, posicionais e de base 1 do VSRepository (`?1`, `?2`, ...) em vez da sintaxe nativa do adapter; o mesmo índice pode se repetir (`?1 ... ?1`) para reutilizar um argumento. Exige que o adapter implemente `getPlaceholder()` — ligar essa option sem ele lança um `VSRepoError`
|
|
45
|
+
- **`VSRepoAdapter.getPlaceholder?`** — novo método opcional no adapter que declara a sintaxe de placeholder para o N-ésimo (base 0) parâmetro ligado (ex.: `` `$${index + 1}` `` para o PostgreSQL, `"?"` para SQLite/MySQL). Implementá-lo é o que habilita os fragmentos `VSSql` e o `vsPlaceholders`
|
|
46
|
+
- **Logs dos métodos de query** — `query()` e `@QueryMethod` agora logam a query compilada e seus args em `DEBUG` (o `db` nunca é logado) e medem a execução (`Took Xms ...`, promovido para `WARN` acima do `logSlowThresholdMs`), como no resto da biblioteca
|
|
47
|
+
|
|
48
|
+
### Documentação
|
|
49
|
+
- Novo guia [Raw query builder](./docs/raw-query-builder.pt-BR.md), cobrindo o `createRawQueryBuilder()`, a construção da query, subqueries (builder ou função), CTEs com `with()`/`withRecursive()`, execução (`toVSSql`/`toSql`/`execute`), transações/`setDb()`, clonagem, validação e logs — adicionado ao índice de documentação dos dois READMEs, com um cross-link a partir do guia [Query builder](./docs/query-builder.pt-BR.md)
|
|
50
|
+
|
|
9
51
|
## [2.6.0] - 2026-09-24
|
|
10
52
|
|
|
11
53
|
### Added
|
|
@@ -14,7 +56,7 @@ All notable changes to this project will be documented in this file.
|
|
|
14
56
|
- **`VSRepoErrorType.QUERY_BUILDER`** — new error type, thrown as a `VSRepoError` when an invalid argument is passed to a query builder method
|
|
15
57
|
- **Query builder logs** — the builder uses the repository's logger: at `DEBUG` it traces every chained call and the resolved query of each terminal method (the `db` is never logged), and each terminal method is timed (`Took Xms to run query builder <method>`, promoted to `WARN` above `logSlowThresholdMs`)
|
|
16
58
|
- **`Equals` / `NotEquals`** field-filter suffixes for dynamic methods — same effect as no suffix and `Not`, respectively; useful to disambiguate a field name that ends at the same camelCase boundary as an existing keyword suffix (e.g. `findByCheckInEquals` resolves to the field `checkIn`, instead of the default `check` + `In` reading)
|
|
17
|
-
- **`lazyDynamicMethods`** constructor option — when `true`, postpones resolving `@DynamicMethod`/`@QueryMethod` methods until the subclass calls the `protected resolveDynamicMethods()` itself, instead of resolving them synchronously in the constructor. Useful for deferring the resolution cost to a more convenient point in the app's lifecycle (e.g. an async init hook), and lets fields annotated with `@DynamicMethod`/`@QueryMethod` skip the `declare` modifier as long as `resolveDynamicMethods()` is called after calls `
|
|
59
|
+
- **`lazyDynamicMethods`** constructor option — when `true`, postpones resolving `@DynamicMethod`/`@QueryMethod` methods until the subclass calls the `protected resolveDynamicMethods()` itself, instead of resolving them synchronously in the constructor. Useful for deferring the resolution cost to a more convenient point in the app's lifecycle (e.g. an async init hook), and lets fields annotated with `@DynamicMethod`/`@QueryMethod` skip the `declare` modifier as long as `resolveDynamicMethods()` is called after calls `super()`. Calling `resolveDynamicMethods()` again after it already resolved once logs a `WARN`, since it's redundant
|
|
18
60
|
|
|
19
61
|
### Changed
|
|
20
62
|
- `pagination` validation is now stricter: `limit` and `offset` must be non-negative integers. Negative, decimal and infinite values, previously accepted, are now rejected
|
|
@@ -254,7 +296,7 @@ All notable changes to this project will be documented in this file.
|
|
|
254
296
|
|
|
255
297
|
## [2.0.0] - 2026-09-01
|
|
256
298
|
|
|
257
|
-
> Major rewrite. If you're upgrading from v1, see the [
|
|
299
|
+
> Major rewrite. If you're upgrading from v1, see the [Migrating from v1](./docs/migrating-from-v1.md) guide for the full breakdown before migrating.
|
|
258
300
|
|
|
259
301
|
### Changed
|
|
260
302
|
- **BREAKING:** VSRepository is now **ORM-agnostic** — the core no longer talks to Prisma directly, it delegates every operation to a pluggable `VSRepoAdapter`. ORM support now ships as separate packages (e.g. `@vsrepo/prisma7-adapter`) instead of being bundled in the core `vsrepo` package
|
|
@@ -291,7 +333,7 @@ All notable changes to this project will be documented in this file.
|
|
|
291
333
|
|
|
292
334
|
## [2.0.0] - 2026-09-01 (Português)
|
|
293
335
|
|
|
294
|
-
> Reescrita major. Se você está migrando da v1, veja
|
|
336
|
+
> Reescrita major. Se você está migrando da v1, veja o guia [Migrando da v1](./docs/migrating-from-v1.pt-BR.md) para o detalhamento completo antes de migrar.
|
|
295
337
|
|
|
296
338
|
### Alterado
|
|
297
339
|
- **BREAKING:** O VSRepository agora é **agnóstico de ORM** — o core não conversa mais diretamente com o Prisma, delegando toda operação a um `VSRepoAdapter` plugável. O suporte a ORMs agora é publicado em pacotes separados (ex.: `@vsrepo/prisma7-adapter`) em vez de vir embutido no pacote core `vsrepo`
|
package/README.md
CHANGED
|
@@ -13,63 +13,21 @@
|
|
|
13
13
|
|
|
14
14
|
🇺🇸 You're reading the English version. [🇧🇷 Ler em português](./README.pt-BR.md)
|
|
15
15
|
|
|
16
|
-
**ORM-agnostic
|
|
16
|
+
VSRepository is an **ORM-agnostic repository pattern library for TypeScript**. It provides a consistent repository API, derived query methods, query builders, transactions, and other persistence concerns through pluggable **ORM adapters**.
|
|
17
17
|
|
|
18
18
|
VSRepository lets you create strongly-typed repositories with:
|
|
19
19
|
|
|
20
20
|
- Automatic **base methods**: `get`, `getOrThrow`, `getList`, `save`, `saveList`, `remove`, `removeList`, `patch`, `merge`, `getAll`, `total`, `has`
|
|
21
21
|
- **Native soft-delete**: `softRemove`, `softRemoveList`, `restore`, `restoreList`
|
|
22
22
|
- **Dynamic methods** inferred from a `declare` field name via the `@DynamicMethod` decorator: `findOneByEmail`, `findByStatusPaginated`, `updateById`
|
|
23
|
-
- **Raw SQL query methods** via the `@QueryMethod` decorator
|
|
24
|
-
- Ad-hoc **`select`/`relations`** per call
|
|
25
|
-
-
|
|
23
|
+
- **Raw SQL query methods** via the `@QueryMethod` decorator (bypassing the name-parsing engine entirely), parameterized `VSSql` fragments for ad-hoc `query()` calls, and agnostic `?1`, `?2` placeholders with `vsPlaceholders`
|
|
24
|
+
- Ad-hoc **`select`/`relations`** per call
|
|
25
|
+
- Strong **TypeScript** typing across the repository API
|
|
26
26
|
- Native ORM **transactions**, shared across repositories
|
|
27
27
|
- An **ORM-agnostic core** — the same repository class works with any `VSRepoAdapter` implementation
|
|
28
28
|
|
|
29
29
|
---
|
|
30
30
|
|
|
31
|
-
## Documentation
|
|
32
|
-
|
|
33
|
-
The sections below (adapter status, installation, basic usage) are the essentials to get you started. Everything about a specific feature — with more detail and more examples — lives in its own guide under [`docs/`](./docs/README.md), each available in English and in [Português](./docs/README.pt-BR.md):
|
|
34
|
-
|
|
35
|
-
| Guide | Covers |
|
|
36
|
-
| --- | --- |
|
|
37
|
-
| [Base methods, configuration & soft-delete](./docs/base-methods.md) | Constructor options, the 12 automatic CRUD methods, native soft-delete, and the 8 atomic/aggregate methods (`increment`, `sum`, ...). |
|
|
38
|
-
| [`select` and `relations`](./docs/select-and-relations.md) | Ad-hoc field selection and eager relation loading on any call, and `InferMethodReturn` to narrow the return type accordingly. |
|
|
39
|
-
| [Dynamic methods](./docs/dynamic-methods.md) | `findByEmail`-style methods parsed from a `declare`d method name: prefixes, field filters, logical operators, relation filters, ordering/pagination/distinct. |
|
|
40
|
-
| [Query methods (raw SQL)](./docs/query-methods.md) | Raw SQL methods via `@QueryMethod`, bypassing the dynamic-method name parser entirely. |
|
|
41
|
-
| [Query builder](./docs/query-builder.md) | The fluent `createQueryBuilder()` API for queries assembled at runtime, including pagination, soft-delete visibility and transactions. |
|
|
42
|
-
| [Transactions](./docs/transactions.md) | Running several repositories against the same native ORM transaction. |
|
|
43
|
-
| [Utility types](./docs/utility-types.md) | The exported helper types (`InferMethodType`, `InferMethodReturn`, `KeysOfType`, ...) and where each one is used. |
|
|
44
|
-
| [Writing your own adapter](./docs/writing-an-adapter.md) | How to implement `VSRepoAdapter` for a new ORM or database, method by method. |
|
|
45
|
-
| [Error handling](./docs/error-handling.md) | `VSRepoError`, `VSRepoErrorType`, and `VSRepoAdapterError`/`AdapterErrorCode`. |
|
|
46
|
-
| [Logging](./docs/logging.md) | `logLevel`, `logSlowThresholdMs`, and the log format used by the repository and the query builder. |
|
|
47
|
-
| [Migrating from v1](./docs/migrating-from-v1.md) | Everything that changed between v1 and v2 — API, config, renamed suffixes, removed features — in a single reference for migrating existing repositories. |
|
|
48
|
-
|
|
49
|
-
---
|
|
50
|
-
|
|
51
|
-
## Adapter status
|
|
52
|
-
|
|
53
|
-
VSRepository is **ORM-agnostic by design**. The core package (`vsrepo`) only ships the repository class, the decorators, the name-parsing engine, error handling and logging — it does **not** ship a production adapter. Actual ORM/database support is meant to live in **separate, independently versioned packages**, one per ORM (and, where it makes sense, one per major ORM version), for example:
|
|
54
|
-
|
|
55
|
-
- `@vsrepo/prisma7-adapter`
|
|
56
|
-
- `@vsrepo/prisma8-adapter`
|
|
57
|
-
- `@vsrepo/typeorm-adapter`
|
|
58
|
-
- `@vsrepo/drizzle-adapter`
|
|
59
|
-
|
|
60
|
-
The Prisma 7 adapter is published to npm as `@vsrepo/prisma7-adapter`. The Drizzle adapter is available as an **alpha** release — install it with `@vsrepo/drizzle-adapter@alpha`. Adapters for other ORMs are **planned** but not published yet. Until an official `@vsrepo/*-adapter` package exists for your ORM, you're welcome to write your own for your project, and if you'd like, publish it and open a PR to help grow the ecosystem — contributions here are very welcome.
|
|
61
|
-
|
|
62
|
-
| Adapter | Status |
|
|
63
|
-
| ------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
64
|
-
| Prisma 7 (`@vsrepo/prisma7-adapter`) | 🟢 **Released** — published to npm, implements the `VSRepoAdapter` contract (CRUD, relations, transactions, `merge`, logging, etc.) with tests; see [`VSRepoPrisma7Adapter`](https://github.com/jaobrabo123/VSRepoPrisma7Adapter) for source and docs. |
|
|
65
|
-
| Drizzle (`@vsrepo/drizzle-adapter`) | 🔵 **Alpha** — an early release is available on npm; install it with `npm i @vsrepo/drizzle-adapter@alpha`. The API may still change before the stable release. Check the [`DrizzleAdapter`](https://github.com/jaobrabo123/VSRepoDrizzleAdapter) repository for the current status and known limitations, and feel free to contribute. |
|
|
66
|
-
| Other ORMs (Prisma 8, TypeORM, etc.) | 🟡 **Planned, not published yet.** No official package exists yet — write your own adapter for now (see [Writing your own adapter](./docs/writing-an-adapter.md#writing-your-own-adapter)), and consider publishing/contributing it back. |
|
|
67
|
-
| Custom adapters | 🟢 Fully supported today — implement the [`VSRepoAdapter`](./docs/writing-an-adapter.md#writing-your-own-adapter) abstract class yourself for any ORM/database you need, in your own project or package. |
|
|
68
|
-
|
|
69
|
-
In short: the repository class, the `@DynamicMethod`/`@QueryMethod` decorators, the name-parsing engine, error handling and logging are all working end-to-end, and Prisma 7 support is a released, published adapter. The Drizzle adapter is available in alpha. Official adapters for the remaining ORMs are on the roadmap and will ship as separate `@vsrepo/*-adapter` packages rather than as part of the core `vsrepo` package — but you don't have to wait for that: writing (and optionally publishing) your own adapter in the meantime is a fully supported way to use VSRepository today and to contribute back to the project.
|
|
70
|
-
|
|
71
|
-
---
|
|
72
|
-
|
|
73
31
|
## Installation
|
|
74
32
|
|
|
75
33
|
VSRepository is installed as the core package plus one adapter package for your ORM, for example:
|
|
@@ -82,26 +40,12 @@ npm i vsrepo @vsrepo/prisma7-adapter
|
|
|
82
40
|
|
|
83
41
|
## Basic usage
|
|
84
42
|
|
|
85
|
-
### Implementing/choosing an adapter
|
|
86
|
-
|
|
87
|
-
```typescript
|
|
88
|
-
// src/configs/db.ts
|
|
89
|
-
import { PrismaClient } from "../../generated/prisma/client";
|
|
90
|
-
import { PrismaPg } from "@prisma/adapter-pg";
|
|
91
|
-
import "dotenv/config";
|
|
92
|
-
|
|
93
|
-
const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL });
|
|
94
|
-
const prisma = new PrismaClient({ adapter });
|
|
95
|
-
|
|
96
|
-
export default prisma;
|
|
97
|
-
```
|
|
98
|
-
|
|
99
43
|
### Creating a repository
|
|
100
44
|
|
|
101
45
|
```typescript
|
|
102
46
|
// src/repositories/user.repository.ts
|
|
103
47
|
import { VSRepository, DynamicMethod } from "vsrepo";
|
|
104
|
-
import {
|
|
48
|
+
import { Prisma7Adapter } from "@vsrepo/prisma7-adapter";
|
|
105
49
|
import prisma from "../configs/db";
|
|
106
50
|
import type { UserGetPayload } from "../../generated/prisma/models";
|
|
107
51
|
|
|
@@ -110,8 +54,7 @@ type User = UserGetPayload<{ include: { address: true } }>;
|
|
|
110
54
|
class UserRepository extends VSRepository<User, string> {
|
|
111
55
|
constructor() {
|
|
112
56
|
super({
|
|
113
|
-
pkName: "id",
|
|
114
|
-
adapter: new VSRepoPrisma7Adapter<User>(prisma, { tableName: "user", pkName: "id" }),
|
|
57
|
+
adapter: new Prisma7Adapter(prisma, { tableName: "user", pkName: "id" }),
|
|
115
58
|
softRemoveKey: "deletedAt",
|
|
116
59
|
defaultOrdering: { createdAt: "desc" },
|
|
117
60
|
});
|
|
@@ -129,20 +72,6 @@ export default new UserRepository();
|
|
|
129
72
|
|
|
130
73
|
> The core API (`VSRepository`, `VSRepoAdapter`, `DynamicMethod`, `QueryMethod`, `VSRepoError`, enums and types) is imported from the single `vsrepo` entry point. The concrete adapter comes from a **separate** package (`@vsrepo/*-adapter`). On Prisma 7, install the [`@vsrepo/prisma7-adapter`](https://github.com/jaobrabo123/VSRepoPrisma7Adapter).
|
|
131
74
|
|
|
132
|
-
> **The third generic parameter (`OrmTypes`):** `VSRepository<Entity, PKType, OrmTypes>` accepts an optional third type parameter describing your ORM's client/transaction types, via `VSRepoOrmTypes` (`{ dbClient; dbTransaction }`). Supplying it gives you a correctly-typed `getDbClient()`, `transaction()` callback, and `db` option on every method, instead of `any`:
|
|
133
|
-
>
|
|
134
|
-
> ```typescript
|
|
135
|
-
> import { Prisma7OrmTypes } from "@vsrepo/prisma7-adapter";
|
|
136
|
-
>
|
|
137
|
-
> type MyOrmTypes = Prisma7OrmTypes<PrismaClient>;
|
|
138
|
-
>
|
|
139
|
-
> class UserRepository extends VSRepository<User, string, MyOrmTypes> {
|
|
140
|
-
> // getDbClient() now returns PrismaClient, and transaction(fn) types `tx` as Prisma.TransactionClient
|
|
141
|
-
> }
|
|
142
|
-
> ```
|
|
143
|
-
>
|
|
144
|
-
> If omitted, it defaults to `VSRepoOrmTypes` (`dbClient`/`dbTransaction` both `any`).
|
|
145
|
-
|
|
146
75
|
### Using the repository
|
|
147
76
|
|
|
148
77
|
```typescript
|
|
@@ -164,29 +93,43 @@ await userRepository.remove(user.id);
|
|
|
164
93
|
|
|
165
94
|
---
|
|
166
95
|
|
|
167
|
-
##
|
|
168
|
-
|
|
169
|
-
```bash
|
|
170
|
-
# 1. Install dependencies
|
|
171
|
-
bun install
|
|
96
|
+
## Documentation
|
|
172
97
|
|
|
173
|
-
|
|
174
|
-
|
|
98
|
+
The sections above (installation, basic usage) are the essentials to get you started. Everything about a specific feature — with more detail and more examples — lives in its own guide under [`docs/`](./docs/README.md), each available in English and in [Português](./docs/README.pt-BR.md):
|
|
99
|
+
|
|
100
|
+
### Guides
|
|
101
|
+
|
|
102
|
+
| Guide | Covers |
|
|
103
|
+
| ------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
104
|
+
| [Adapter status](./docs/adapters.md) | Which ORM adapters exist today, what "ORM-agnostic by design" means in practice, and how to install, write or publish your own. |
|
|
105
|
+
| [Base methods, configuration & soft-delete](./docs/base-methods.md) | Constructor options, the 12 automatic CRUD methods, native soft-delete, and the 8 atomic/aggregate methods (`increment`, `sum`, ...). |
|
|
106
|
+
| [`select` and `relations`](./docs/select-and-relations.md) | Ad-hoc field selection and eager relation loading on any call, and `InferMethodReturn` to narrow the return type accordingly. |
|
|
107
|
+
| [Dynamic methods](./docs/dynamic-methods.md) | `findByEmail`-style methods parsed from a `declare`d method name: prefixes, field filters, logical operators, relation filters, ordering/pagination/distinct. |
|
|
108
|
+
| [Query methods (raw SQL)](./docs/query-methods.md) | Raw SQL via `@QueryMethod`, parameterized `VSSql` fragments and the agnostic `?1`/`?2` placeholders (`vsPlaceholders`). |
|
|
109
|
+
| [Query builder](./docs/query-builder.md) | The fluent `createQueryBuilder()` API for queries assembled at runtime, including pagination, soft-delete visibility and transactions. |
|
|
110
|
+
| [Raw query builder](./docs/raw-query-builder.md) | The fluent `createRawQueryBuilder()` API for hand-written `SELECT` queries too SQL-specific for the query builder — joins, subqueries, CTEs (`with`/`withRecursive`). |
|
|
111
|
+
| [Transactions](./docs/transactions.md) | Running several repositories against the same native ORM transaction. |
|
|
112
|
+
| [Utility types](./docs/utility-types.md) | The exported helper types (`InferMethodType`, `InferMethodReturn`, `KeysOfType`, ...) and where each one is used. |
|
|
113
|
+
| [Writing your own adapter](./docs/writing-an-adapter.md) | What an adapter is responsible for, and how to implement the `VSRepoAdapter` contract for a new ORM or database. |
|
|
114
|
+
| [Error handling](./docs/error-handling.md) | `VSRepoError`, `VSRepoErrorType`, and `VSRepoAdapterError`/`AdapterErrorCode`. |
|
|
115
|
+
| [Logging](./docs/logging.md) | `logLevel`, `logSlowThresholdMs`, and the log format used by the repository and the query builder. |
|
|
116
|
+
| [Contributing](./CONTRIBUTING.md) | Repository layout, the key scripts, conventions and CI — plus the contribution flow itself (issues, pull requests, review). |
|
|
117
|
+
| [Migrating from v1](./docs/migrating-from-v1.md) | Everything that changed between v1 and v2 — API, config, renamed suffixes, removed features — in a single reference for migrating existing repositories. |
|
|
175
118
|
|
|
176
|
-
|
|
177
|
-
npm pack --dry-run
|
|
119
|
+
---
|
|
178
120
|
|
|
179
|
-
|
|
180
|
-
npm pack
|
|
121
|
+
## Adapter status
|
|
181
122
|
|
|
182
|
-
|
|
183
|
-
npm install ../path/to/vsrepo-*.tgz
|
|
184
|
-
```
|
|
123
|
+
VSRepository is **ORM-agnostic by design**: the core package (`vsrepo`) ships only the repository class, the decorators, the name-parsing engine, error handling and logging — no production adapter. ORM support lives in separate, independently versioned `@vsrepo/*-adapter` packages, so each one can follow its own ORM's release cycle.
|
|
185
124
|
|
|
186
|
-
|
|
125
|
+
| Adapter | Status |
|
|
126
|
+
| ------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
127
|
+
| Prisma 7 (`@vsrepo/prisma7-adapter`) | 🟢 **Released** — published to npm, with tests. [Source and docs](https://github.com/jaobrabo123/VSRepoPrisma7Adapter). |
|
|
128
|
+
| Drizzle (`@vsrepo/drizzle-adapter`) | 🔵 **Alpha** — `npm i @vsrepo/drizzle-adapter@alpha`. The API may still change. [Repo](https://github.com/jaobrabo123/VSRepoDrizzleAdapter). |
|
|
129
|
+
| Other ORMs (Prisma 8, TypeORM, etc.) | 🟡 **Planned, not published yet.** Write your own in the meantime — it's fully supported. |
|
|
130
|
+
| Custom adapters | 🟢 Fully supported — implement `VSRepoAdapter` yourself, in your own project or package. |
|
|
187
131
|
|
|
188
|
-
|
|
189
|
-
- The published package contains **only** the `dist/` folder, the READMEs, `CHANGELOG.md` and `LICENSE` (see `files` in `package.json`). The adapters will live in their own `@vsrepo/*-adapter` packages.
|
|
132
|
+
The full status and how to install each one: [Adapter status](./docs/adapters.md). To publish your own, see [Publishing your own adapter](./docs/writing-an-adapter.md#publishing-your-own-adapter).
|
|
190
133
|
|
|
191
134
|
---
|
|
192
135
|
|
|
@@ -204,17 +147,12 @@ Notes:
|
|
|
204
147
|
```
|
|
205
148
|
|
|
206
149
|
- `reflect-metadata` (bundled as a dependency, imported internally — you don't need to import it yourself)
|
|
207
|
-
- At least one working `VSRepoAdapter` for your database — on Prisma 7, install the published [`@vsrepo/prisma7-adapter`](https://github.com/jaobrabo123/VSRepoPrisma7Adapter) (see [Adapter status](#adapter-status))
|
|
150
|
+
- At least one working `VSRepoAdapter` for your database — on Prisma 7, install the published [`@vsrepo/prisma7-adapter`](https://github.com/jaobrabo123/VSRepoPrisma7Adapter) (see [Adapter status](#adapter-status))
|
|
208
151
|
|
|
209
152
|
---
|
|
210
153
|
|
|
211
154
|
## Contributing
|
|
212
155
|
|
|
213
|
-
Contributions are welcome,
|
|
214
|
-
|
|
215
|
-
1. **Fork** the project.
|
|
216
|
-
2. Create a branch for your change: `git checkout -b my-change`.
|
|
217
|
-
3. Push your branch: `git push origin my-change`.
|
|
218
|
-
4. Open a **Pull Request**.
|
|
156
|
+
Contributions are welcome — adapters, bug reports and documentation alike. The core is ORM-agnostic, so ORM-specific work belongs in your own adapter package; see the scope rules before opening a PR.
|
|
219
157
|
|
|
220
|
-
|
|
158
|
+
- **[CONTRIBUTING.md](./CONTRIBUTING.md)** — how to report a bug, request a feature, and submit a pull request.
|
package/README.pt-BR.md
CHANGED
|
@@ -13,63 +13,21 @@
|
|
|
13
13
|
|
|
14
14
|
🇧🇷 Você está lendo a versão em português. [🇺🇸 Read in English](./README.md)
|
|
15
15
|
|
|
16
|
-
|
|
16
|
+
O VSRepository é uma **biblioteca de repository pattern agnóstica de ORM para TypeScript**. Ela fornece uma API de repository consistente, métodos de consulta derivados, query builders, transações e outros recursos relacionados à persistência por meio de **adapters de ORM plugáveis**.
|
|
17
17
|
|
|
18
18
|
O VSRepository permite criar repositories fortemente tipados com:
|
|
19
19
|
|
|
20
20
|
- **Métodos base** automáticos: `get`, `getOrThrow`, `getList`, `save`, `saveList`, `remove`, `removeList`, `patch`, `merge`, `getAll`, `total`, `has`
|
|
21
21
|
- **Soft-delete nativo**: `softRemove`, `softRemoveList`, `restore`, `restoreList`
|
|
22
22
|
- **Métodos dinâmicos** inferidos a partir do nome de um campo `declare` via o decorador `@DynamicMethod`: `findOneByEmail`, `findByStatusPaginated`, `updateById`
|
|
23
|
-
- **Métodos de query SQL raw** através do decorador `@QueryMethod
|
|
24
|
-
- **`select`/`relations`** ad-hoc em cada chamada
|
|
25
|
-
-
|
|
23
|
+
- **Métodos de query SQL raw** através do decorador `@QueryMethod` (ignorando totalmente o engine de parsing por nome), fragmentos parametrizados `VSSql` para chamadas pontuais de `query()`, e placeholders agnósticos `?1`, `?2` com `vsPlaceholders`
|
|
24
|
+
- **`select`/`relations`** ad-hoc em cada chamada
|
|
25
|
+
- Tipagem forte com **TypeScript** em toda a API do repositório
|
|
26
26
|
- **Transações** nativas do ORM, compartilhadas entre repositories
|
|
27
27
|
- Um **núcleo agnóstico de ORM** — a mesma classe de repository funciona com qualquer implementação de `VSRepoAdapter`
|
|
28
28
|
|
|
29
29
|
---
|
|
30
30
|
|
|
31
|
-
## Documentação
|
|
32
|
-
|
|
33
|
-
As seções abaixo (status dos adapters, instalação, uso básico) são o essencial para começar. Tudo sobre uma funcionalidade específica — com mais detalhe e mais exemplos — vive em um guia próprio dentro de [`docs/`](./docs/README.pt-BR.md), cada um disponível em português e em [English](./docs/README.md):
|
|
34
|
-
|
|
35
|
-
| Guia | Cobre |
|
|
36
|
-
| --- | --- |
|
|
37
|
-
| [Métodos base, configuração & soft-delete](./docs/base-methods.pt-BR.md) | Options do construtor, os 12 métodos CRUD automáticos, soft-delete nativo, e os 8 métodos atômicos/de agregação (`increment`, `sum`, ...). |
|
|
38
|
-
| [`select` e `relations`](./docs/select-and-relations.pt-BR.md) | Seleção de campos e carregamento de relações ad-hoc em qualquer chamada, e o `InferMethodReturn` para estreitar o tipo de retorno de acordo. |
|
|
39
|
-
| [Métodos dinâmicos](./docs/dynamic-methods.pt-BR.md) | Métodos no estilo `findByEmail`, resolvidos a partir de um nome de método `declare`d: prefixos, filtros de campo, operadores lógicos, filtros de relação, ordenação/paginação/distinct. |
|
|
40
|
-
| [Query methods (SQL raw)](./docs/query-methods.pt-BR.md) | Métodos de SQL raw via `@QueryMethod`, ignorando totalmente o parser de nomes dos métodos dinâmicos. |
|
|
41
|
-
| [Query builder](./docs/query-builder.pt-BR.md) | A API fluente `createQueryBuilder()` para queries montadas em tempo de execução, incluindo paginação, visibilidade de soft-delete e transações. |
|
|
42
|
-
| [Transações](./docs/transactions.pt-BR.md) | Rodando vários repositories na mesma transação nativa do ORM. |
|
|
43
|
-
| [Tipos utilitários](./docs/utility-types.pt-BR.md) | Os tipos utilitários exportados (`InferMethodType`, `InferMethodReturn`, `KeysOfType`, ...) e onde cada um é usado. |
|
|
44
|
-
| [Escrevendo seu próprio adapter](./docs/writing-an-adapter.pt-BR.md) | Como implementar o `VSRepoAdapter` para um novo ORM ou banco, método a método. |
|
|
45
|
-
| [Tratamento de erros](./docs/error-handling.pt-BR.md) | `VSRepoError`, `VSRepoErrorType`, e `VSRepoAdapterError`/`AdapterErrorCode`. |
|
|
46
|
-
| [Logging](./docs/logging.pt-BR.md) | `logLevel`, `logSlowThresholdMs`, e o formato de log usado pelo repository e pelo query builder. |
|
|
47
|
-
| [Migrando da v1](./docs/migrating-from-v1.pt-BR.md) | Tudo o que mudou entre a v1 e a v2 — API, config, sufixos renomeados, funcionalidades removidas — em uma única referência para migrar repositories existentes. |
|
|
48
|
-
|
|
49
|
-
---
|
|
50
|
-
|
|
51
|
-
## Status dos adapters
|
|
52
|
-
|
|
53
|
-
O VSRepository é **agnóstico de ORM por design**. O pacote core (`vsrepo`) traz apenas a classe de repository, os decoradores, o engine de parsing de nomes, o tratamento de erros e o logging — ele **não** inclui um adapter de produção. O suporte de fato a cada ORM/banco deve viver em **pacotes separados, versionados de forma independente**, um por ORM (e, quando fizer sentido, um por versão principal do ORM), por exemplo:
|
|
54
|
-
|
|
55
|
-
- `@vsrepo/prisma7-adapter`
|
|
56
|
-
- `@vsrepo/prisma8-adapter`
|
|
57
|
-
- `@vsrepo/typeorm-adapter`
|
|
58
|
-
- `@vsrepo/drizzle-adapter`
|
|
59
|
-
|
|
60
|
-
O adapter do Prisma 7 já foi publicado no npm como `@vsrepo/prisma7-adapter`. O adapter do Drizzle está disponível em versão **alpha** — instale com `npm i @vsrepo/drizzle-adapter@alpha`. Os adapters para outros ORMs estão **planejados**, mas ainda não foram publicados. Até que exista um pacote `@vsrepo/*-adapter` oficial para o seu ORM, você pode escrever o seu próprio para o seu projeto e, se quiser, publicá-lo e abrir um PR para ajudar a fazer o ecossistema crescer — contribuições nesse sentido são muito bem-vindas.
|
|
61
|
-
|
|
62
|
-
| Adapter | Status |
|
|
63
|
-
| ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
64
|
-
| Prisma 7 (`@vsrepo/prisma7-adapter`) | 🟢 **Lançado** — publicado no npm, implementa o contrato de `VSRepoAdapter` (CRUD, relations, transactions, `merge`, logging, etc.) com testes; veja o [`VSRepoPrisma7Adapter`](https://github.com/jaobrabo123/VSRepoPrisma7Adapter) para o código-fonte e docs. |
|
|
65
|
-
| Drizzle (`@vsrepo/drizzle-adapter`) | 🔵 **Alpha** — uma versão inicial já está disponível no npm; instale com `npm i @vsrepo/drizzle-adapter@alpha`. A API ainda pode mudar antes do release estável. Veja o repositório do [`DrizzleAdapter`](https://github.com/jaobrabo123/VSRepoDrizzleAdapter) para o estado atual e limitações conhecidas, e sinta-se à vontade para contribuir. |
|
|
66
|
-
| Outros ORMs (Prisma 8, TypeORM, etc.) | 🟡 **Planejados, ainda não publicados.** Nenhum pacote oficial existe ainda — por enquanto, escreva o seu próprio adapter (veja [Escrevendo seu próprio adapter](./docs/writing-an-adapter.pt-BR.md#escrevendo-seu-próprio-adapter)) e considere publicá-lo/contribuir de volta com o projeto. |
|
|
67
|
-
| Adapters customizados | 🟢 Totalmente suportados hoje — implemente você mesmo a classe abstrata [`VSRepoAdapter`](./docs/writing-an-adapter.pt-BR.md#escrevendo-seu-próprio-adapter) para qualquer ORM/banco que precisar, no seu próprio projeto ou pacote. |
|
|
68
|
-
|
|
69
|
-
Resumindo: a classe de repository, os decoradores `@DynamicMethod`/`@QueryMethod`, o engine de parsing de nomes, o tratamento de erros e o logging já funcionam de ponta a ponta, e o suporte ao Prisma 7 é um adapter lançado e publicado. O adapter do Drizzle está disponível em alpha. Adapters oficiais para os demais ORMs estão no roadmap e serão distribuídos como pacotes `@vsrepo/*-adapter` separados, e não como parte do pacote core `vsrepo` — mas você não precisa esperar por isso: escrever (e opcionalmente publicar) o seu próprio adapter enquanto isso é uma forma totalmente suportada de usar o VSRepository hoje e de contribuir de volta com o projeto.
|
|
70
|
-
|
|
71
|
-
---
|
|
72
|
-
|
|
73
31
|
## Instalação
|
|
74
32
|
|
|
75
33
|
O VSRepository é instalado como o pacote core mais um pacote de adapter para o seu ORM, por exemplo:
|
|
@@ -82,26 +40,12 @@ npm i vsrepo @vsrepo/prisma7-adapter
|
|
|
82
40
|
|
|
83
41
|
## Uso básico
|
|
84
42
|
|
|
85
|
-
### Implementando/escolhendo um adapter
|
|
86
|
-
|
|
87
|
-
```typescript
|
|
88
|
-
// src/configs/db.ts
|
|
89
|
-
import { PrismaClient } from "../../generated/prisma/client";
|
|
90
|
-
import { PrismaPg } from "@prisma/adapter-pg";
|
|
91
|
-
import "dotenv/config";
|
|
92
|
-
|
|
93
|
-
const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL });
|
|
94
|
-
const prisma = new PrismaClient({ adapter });
|
|
95
|
-
|
|
96
|
-
export default prisma;
|
|
97
|
-
```
|
|
98
|
-
|
|
99
43
|
### Criando um repository
|
|
100
44
|
|
|
101
45
|
```typescript
|
|
102
46
|
// src/repositories/user.repository.ts
|
|
103
47
|
import { VSRepository, DynamicMethod } from "vsrepo";
|
|
104
|
-
import {
|
|
48
|
+
import { Prisma7Adapter } from "@vsrepo/prisma7-adapter";
|
|
105
49
|
import prisma from "../configs/db";
|
|
106
50
|
import type { UserGetPayload } from "../../generated/prisma/models";
|
|
107
51
|
|
|
@@ -110,8 +54,7 @@ type User = UserGetPayload<{ include: { address: true } }>;
|
|
|
110
54
|
class UserRepository extends VSRepository<User, string> {
|
|
111
55
|
constructor() {
|
|
112
56
|
super({
|
|
113
|
-
pkName: "id",
|
|
114
|
-
adapter: new VSRepoPrisma7Adapter<User>(prisma, { tableName: "user", pkName: "id" }),
|
|
57
|
+
adapter: new Prisma7Adapter(prisma, { tableName: "user", pkName: "id" }),
|
|
115
58
|
softRemoveKey: "deletedAt",
|
|
116
59
|
defaultOrdering: { createdAt: "desc" },
|
|
117
60
|
});
|
|
@@ -129,20 +72,6 @@ export default new UserRepository();
|
|
|
129
72
|
|
|
130
73
|
> A API do core (`VSRepository`, `VSRepoAdapter`, `DynamicMethod`, `QueryMethod`, `VSRepoError`, enums e tipos) é importada do entry point único `vsrepo`. O adapter concreto vem de um pacote **separado** (`@vsrepo/*-adapter`). No Prisma 7, instale o [`@vsrepo/prisma7-adapter`](https://github.com/jaobrabo123/VSRepoPrisma7Adapter).
|
|
131
74
|
|
|
132
|
-
> **O terceiro generic (`OrmTypes`):** `VSRepository<Entity, PKType, OrmTypes>` aceita um terceiro type parameter opcional descrevendo os tipos de client/transaction do seu ORM, via `VSRepoOrmTypes` (`{ dbClient; dbTransaction }`). Ao fornecê-lo, `getDbClient()`, o callback de `transaction()` e a option `db` de todo método passam a ser tipados corretamente, em vez de `any`:
|
|
133
|
-
>
|
|
134
|
-
> ```typescript
|
|
135
|
-
> import { Prisma7OrmTypes } from "@vsrepo/prisma7-adapter";
|
|
136
|
-
>
|
|
137
|
-
> type MyOrmTypes = Prisma7OrmTypes<PrismaClient>;
|
|
138
|
-
>
|
|
139
|
-
> class UserRepository extends VSRepository<User, string, MyOrmTypes> {
|
|
140
|
-
> // getDbClient() agora retorna PrismaClient, e transaction(fn) tipa `tx` como Prisma.TransactionClient
|
|
141
|
-
> }
|
|
142
|
-
> ```
|
|
143
|
-
>
|
|
144
|
-
> Se omitido, o padrão é `VSRepoOrmTypes` (`dbClient`/`dbTransaction` como `any`).
|
|
145
|
-
|
|
146
75
|
### Usando o repository
|
|
147
76
|
|
|
148
77
|
```typescript
|
|
@@ -164,29 +93,43 @@ await userRepository.remove(usuario.id);
|
|
|
164
93
|
|
|
165
94
|
---
|
|
166
95
|
|
|
167
|
-
##
|
|
168
|
-
|
|
169
|
-
```bash
|
|
170
|
-
# 1. Instalar as dependências
|
|
171
|
-
bun install
|
|
96
|
+
## Documentação
|
|
172
97
|
|
|
173
|
-
|
|
174
|
-
|
|
98
|
+
As seções acima (instalação, uso básico) são o essencial para começar. Tudo sobre uma funcionalidade específica — com mais detalhe e mais exemplos — vive em um guia próprio dentro de [`docs/`](./docs/README.pt-BR.md), cada um disponível em português e em [English](./docs/README.md):
|
|
99
|
+
|
|
100
|
+
### Guias
|
|
101
|
+
|
|
102
|
+
| Guia | Cobre |
|
|
103
|
+
| ------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
104
|
+
| [Status dos adapters](./docs/adapters.pt-BR.md) | Quais adapters de ORM existem hoje, o que "agnóstico de ORM por design" significa na prática, e como instalar, escrever ou publicar o seu. |
|
|
105
|
+
| [Métodos base, configuração & soft-delete](./docs/base-methods.pt-BR.md) | Options do construtor, os 12 métodos CRUD automáticos, soft-delete nativo, e os 8 métodos atômicos/de agregação (`increment`, `sum`, ...). |
|
|
106
|
+
| [`select` e `relations`](./docs/select-and-relations.pt-BR.md) | Seleção de campos e carregamento de relações ad-hoc em qualquer chamada, e o `InferMethodReturn` para estreitar o tipo de retorno de acordo. |
|
|
107
|
+
| [Métodos dinâmicos](./docs/dynamic-methods.pt-BR.md) | Métodos no estilo `findByEmail`, resolvidos a partir de um nome de método `declare`d: prefixos, filtros de campo, operadores lógicos, filtros de relação, ordenação/paginação/distinct. |
|
|
108
|
+
| [Query methods (SQL raw)](./docs/query-methods.pt-BR.md) | SQL raw via `@QueryMethod`, fragmentos parametrizados `VSSql` e os placeholders agnósticos `?1`/`?2` (`vsPlaceholders`). |
|
|
109
|
+
| [Query builder](./docs/query-builder.pt-BR.md) | A API fluente `createQueryBuilder()` para queries montadas em tempo de execução, incluindo paginação, visibilidade de soft-delete e transações. |
|
|
110
|
+
| [Raw query builder](./docs/raw-query-builder.pt-BR.md) | A API fluente `createRawQueryBuilder()` para queries `SELECT` escritas à mão, específicas demais para o query builder — joins, subqueries, CTEs (`with`/`withRecursive`). |
|
|
111
|
+
| [Transações](./docs/transactions.pt-BR.md) | Rodando vários repositories na mesma transação nativa do ORM. |
|
|
112
|
+
| [Tipos utilitários](./docs/utility-types.pt-BR.md) | Os tipos utilitários exportados (`InferMethodType`, `InferMethodReturn`, `KeysOfType`, ...) e onde cada um é usado. |
|
|
113
|
+
| [Escrevendo seu próprio adapter](./docs/writing-an-adapter.pt-BR.md) | Do que um adapter é responsável, e como implementar o contrato `VSRepoAdapter` para um novo ORM ou banco. |
|
|
114
|
+
| [Tratamento de erros](./docs/error-handling.pt-BR.md) | `VSRepoError`, `VSRepoErrorType`, e `VSRepoAdapterError`/`AdapterErrorCode`. |
|
|
115
|
+
| [Logging](./docs/logging.pt-BR.md) | `logLevel`, `logSlowThresholdMs`, e o formato de log usado pelo repository e pelo query builder. |
|
|
116
|
+
| [Contribuindo](./CONTRIBUTING.pt-BR.md) | Estrutura do repositório, os principais scripts, convenções e CI — mais o próprio fluxo de contribuição (issues, pull requests, revisão). |
|
|
117
|
+
| [Migrando da v1](./docs/migrating-from-v1.pt-BR.md) | Tudo o que mudou entre a v1 e a v2 — API, config, sufixos renomeados, funcionalidades removidas — em uma única referência para migrar repositories existentes. |
|
|
175
118
|
|
|
176
|
-
|
|
177
|
-
npm pack --dry-run
|
|
119
|
+
---
|
|
178
120
|
|
|
179
|
-
|
|
180
|
-
npm pack
|
|
121
|
+
## Status dos adapters
|
|
181
122
|
|
|
182
|
-
|
|
183
|
-
npm install ../caminho/vsrepo-*.tgz
|
|
184
|
-
```
|
|
123
|
+
O VSRepository é **agnóstico de ORM por design**: o pacote core (`vsrepo`) traz apenas a classe de repository, os decoradores, o engine de parsing de nomes, o tratamento de erros e o logging — nenhum adapter de produção. O suporte a ORM vive em pacotes `@vsrepo/*-adapter` separados e versionados de forma independente, então cada um pode acompanhar o ciclo de releases do seu próprio ORM.
|
|
185
124
|
|
|
186
|
-
|
|
125
|
+
| Adapter | Status |
|
|
126
|
+
| ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
127
|
+
| Prisma 7 (`@vsrepo/prisma7-adapter`) | 🟢 **Lançado** — publicado no npm, com testes. [Código e docs](https://github.com/jaobrabo123/VSRepoPrisma7Adapter). |
|
|
128
|
+
| Drizzle (`@vsrepo/drizzle-adapter`) | 🔵 **Alpha** — `npm i @vsrepo/drizzle-adapter@alpha`. A API ainda pode mudar. [Repositório](https://github.com/jaobrabo123/VSRepoDrizzleAdapter). |
|
|
129
|
+
| Outros ORMs (Prisma 8, TypeORM, etc.) | 🟡 **Planejados, ainda não publicados.** Escreva o seu enquanto isso — é totalmente suportado. |
|
|
130
|
+
| Adapters customizados | 🟢 Totalmente suportados — implemente o `VSRepoAdapter` você mesmo, no seu projeto ou pacote. |
|
|
187
131
|
|
|
188
|
-
|
|
189
|
-
- O pacote publicado contém **apenas** a pasta `dist/`, os READMEs, o `CHANGELOG.md` e a `LICENSE` (veja `files` no `package.json`). Os adapters viverão em seus próprios pacotes `@vsrepo/*-adapter`.
|
|
132
|
+
O status completo e como instalar cada um: [Status dos adapters](./docs/adapters.pt-BR.md). Para publicar o seu, veja [Publicando o seu próprio adapter](./docs/writing-an-adapter.pt-BR.md#publicando-o-seu-próprio-adapter).
|
|
190
133
|
|
|
191
134
|
---
|
|
192
135
|
|
|
@@ -204,17 +147,12 @@ Observações:
|
|
|
204
147
|
```
|
|
205
148
|
|
|
206
149
|
- `reflect-metadata` (já incluso como dependência, importado internamente — você não precisa importá-lo você mesmo)
|
|
207
|
-
- Pelo menos um `VSRepoAdapter` funcional para o seu banco — no Prisma 7, instale o [`@vsrepo/prisma7-adapter`](https://github.com/jaobrabo123/VSRepoPrisma7Adapter) já publicado (veja [Status dos adapters](#status-dos-adapters))
|
|
150
|
+
- Pelo menos um `VSRepoAdapter` funcional para o seu banco — no Prisma 7, instale o [`@vsrepo/prisma7-adapter`](https://github.com/jaobrabo123/VSRepoPrisma7Adapter) já publicado (veja [Status dos adapters](#status-dos-adapters))
|
|
208
151
|
|
|
209
152
|
---
|
|
210
153
|
|
|
211
154
|
## Contribuindo
|
|
212
155
|
|
|
213
|
-
Contribuições são bem-vindas,
|
|
214
|
-
|
|
215
|
-
1. Faça um **Fork** do projeto.
|
|
216
|
-
2. Crie uma branch para sua alteração: `git checkout -b minha-alteracao`.
|
|
217
|
-
3. Faça o push da sua branch: `git push origin minha-alteracao`.
|
|
218
|
-
4. Abra um **Pull Request**.
|
|
156
|
+
Contribuições são bem-vindas — adapters, reports de bug e documentação. O core é agnóstico de ORM, então trabalho específico de ORM pertence ao seu próprio pacote de adapter; veja as regras de escopo antes de abrir um PR.
|
|
219
157
|
|
|
220
|
-
|
|
158
|
+
- **[CONTRIBUTING.pt-BR.md](./CONTRIBUTING.pt-BR.md)** — como reportar um bug, pedir uma feature e enviar um pull request.
|
package/dist/VSRepoAdapter.d.ts
CHANGED
|
@@ -108,4 +108,16 @@ export declare abstract class VSRepoAdapter<T> {
|
|
|
108
108
|
abstract max(field: NumericKeys<T>, where?: VSRepoWhere<T>, options?: AdapterMethodOptions<T>): Promise<number | null>;
|
|
109
109
|
/** Optional method for the adapter itself to return the "pkName", instead of the user having to configure it manually in the VSRepository constructor. */
|
|
110
110
|
getPkName?(): string;
|
|
111
|
+
/**
|
|
112
|
+
* Optional method for the adapter to declare the placeholder syntax its
|
|
113
|
+
* database/driver expects in a raw `query()` string, given the 0-based
|
|
114
|
+
* position of the parameter in the `args` array (e.g. Postgres would
|
|
115
|
+
* return `` `$${index + 1}` ``, SQLite/MySQL would ignore `index` and
|
|
116
|
+
* always return `"?"`).
|
|
117
|
+
*
|
|
118
|
+
* Implementing this is what lets `VSRepository.query()` accept a `VSSql`
|
|
119
|
+
* fragment (built with `VSSql.sql`/`raw`/`join`/`empty`) in addition to a
|
|
120
|
+
* plain string: without it, passing a `VSSql` fragment throws.
|
|
121
|
+
*/
|
|
122
|
+
getPlaceholder?(index: number): string;
|
|
111
123
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"VSRepoAdapter.js","sourceRoot":"","sources":["../src/VSRepoAdapter.ts"],"names":[],"mappings":";;;AAQA;;;;;;;;;;;GAWG;AACH,MAAsB,aAAa;
|
|
1
|
+
{"version":3,"file":"VSRepoAdapter.js","sourceRoot":"","sources":["../src/VSRepoAdapter.ts"],"names":[],"mappings":";;;AAQA;;;;;;;;;;;GAWG;AACH,MAAsB,aAAa;CA6LlC;AA7LD,sCA6LC"}
|