npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

prisma-entity-gen

v0.1.5

Published

AST-based entity generator for Prisma schemas — type, interface or class output

Readme

prisma-entity-gen

Gerador de entities TypeScript a partir do schema.prisma via AST.

Resolve o problema de lentidão do TypeScript em projetos com muitos modelos Prisma — cada model é gerado em um arquivo isolado com tipos explícitos, eliminando a inferência pesada do @prisma/client.


Instalação

npm install -D prisma-entity-gen
# ou
pnpm add -D prisma-entity-gen

Uso rápido

npx prisma-entity-gen

Por padrão lê prisma/schema.prisma e gera em src/entities.


Configuração

Crie um .entitygenrc.json na raiz do projeto:

{
  "schemaPath": "prisma/schema.prisma",
  "outputDir": "src/entities",
  "mode": "type",
  "relations": "optional",
  "enumOutput": "enum",
  "barrel": true,
  "suffix": "entity",
  "exclude": [],
  "include": [],
  "classValidator": false,
  "classTransformer": false,
  "dryRun": false,
  "logLevel": "info"
}

Opções de configuração

schemaPath

Tipo: stringPadrão: "prisma/schema.prisma"

Caminho para o arquivo schema.prisma. Aceita caminhos relativos e absolutos.

Se seu projeto usa Prisma multi-file schema, aponte para o schema consolidado:

{
  "schemaPath": "node_modules/.prisma/client/schema.prisma"
}

outputDir

Tipo: stringPadrão: "src/entities"

Diretório onde os arquivos de entity serão gerados. Criado automaticamente se não existir.


mode

Tipo: "type" | "class" | "both"Padrão: "type"

Define o formato de saída das entities.

| Valor | Saída | Uso indicado | |---|---|---| | "type" | export interface UserEntity | Projetos TypeScript puros, melhor performance de compilação | | "class" | export class UserEntity | NestJS com class-validator / class-transformer | | "both" | Ambos em subpastas /types e /classes | Projetos que precisam dos dois formatos |

{ "mode": "class" }

relations

Tipo: "optional" | "required"Padrão: "optional"

Controla se campos de relação são opcionais ou obrigatórios na entity gerada.

| Valor | Comportamento | Quando usar | |---|---|---| | "optional" | Company?: CompanyEntity | Queries sem include — o campo pode não existir | | "required" | Company: CompanyEntity | Sempre usa include nas queries que retornam o tipo |

"optional" (padrão):

export interface UserEntity {
  id: bigint;
  Company?: CompanyEntity;  // só existe se vier com include
}

// funciona sem include
const user = await prisma.user.findUnique({ where: { id } });
// user.Company → undefined (sem erro de tipo)

"required":

export interface UserEntity {
  id: bigint;
  Company: CompanyEntity;  // sempre obrigatório
}

// requer include em toda query que retornar UserEntity
const user = await prisma.user.findUnique({
  where: { id },
  include: { Company: true },
});
{ "relations": "required" }

enumOutput

Tipo: "enum" | "union"Padrão: "enum"

Define o formato de saída dos enums.

| Valor | Saída | |---|---| | "enum" | export enum Role { ADMIN = "ADMIN" } | | "union" | export type Role = "ADMIN" \| "USER" |

Use "union" para evitar conflitos de tipo nominal com enums gerados pelo @prisma/client. Enums são nominais no TypeScript — dois enums com o mesmo nome e valores são tipos incompatíveis. union usa tipagem estrutural, aceitando qualquer string que corresponda ao valor.

{ "enumOutput": "union" }

barrel

Tipo: booleanPadrão: true

Gera um arquivo index.ts na raiz do outputDir que re-exporta todas as entities.

// src/entities/index.ts — gerado automaticamente
export * from "./user.entity.js";
export * from "./post.entity.js";
export * from "./role.enum.js";
// ...

Permite imports limpos no projeto:

import { UserEntity, PostEntity } from '@/entities';

suffix

Tipo: stringPadrão: "entity"

Sufixo dos arquivos gerados. O nome do model é convertido para kebab-case.

{ "suffix": "entity" }

Resulta em: user.entity.ts, post.entity.ts, etc.


exclude

Tipo: string[]Padrão: []

Lista de models a ignorar na geração. Útil para models internos ou de auditoria.

{ "exclude": ["AuditLog", "Session", "MigrationHistory"] }

include

Tipo: string[]Padrão: [] (todos)

Quando preenchido, gera apenas os models listados. Ignora todos os outros.

{ "include": ["User", "Post", "Company"] }

classValidator

Tipo: booleanPadrão: false

Quando mode é "class" ou "both", adiciona decorators do class-validator.

Requer instalação: npm install class-validator

// gerado com classValidator: true
import { IsString, IsOptional, IsDate } from 'class-validator';

export class UserEntity {
  @IsString()
  email!: string;

  @IsOptional()
  @IsString()
  name?: string | null;
}

classTransformer

Tipo: booleanPadrão: false

Quando mode é "class" ou "both", adiciona decorators do class-transformer.

Requer instalação: npm install class-transformer

// gerado com classTransformer: true
import { Type } from 'class-transformer';

export class UserEntity {
  @Type(() => PostEntity)
  posts?: PostEntity[];
}

dryRun

Tipo: booleanPadrão: false

Simula a geração sem escrever arquivos no disco. Útil para visualizar o que seria gerado.

npx prisma-entity-gen --dry-run

logLevel

Tipo: "silent" | "info" | "verbose"Padrão: "info"

| Valor | Comportamento | |---|---| | "silent" | Sem output | | "info" | Mostra arquivos gerados e resumo | | "verbose" | Mostra detalhes de cada etapa |


Flags CLI

Todas as opções do .entitygenrc.json podem ser passadas via CLI. Flags sobrescrevem o arquivo de configuração.

npx prisma-entity-gen [opções]

Opções:
  -s, --schema <path>        Caminho para o schema.prisma
  -o, --output <dir>         Diretório de saída
  -m, --mode <mode>          type | class | both
  --relations <mode>         optional | required
  --enum-output <format>     enum | union
  --dry-run                  Simula sem escrever arquivos
  --log-level <level>        silent | info | verbose
  -V, --version              Exibe a versão
  -h, --help                 Exibe ajuda

Integração com Prisma generate

Adicione no package.json para rodar automaticamente após prisma generate:

{
  "scripts": {
    "generate": "prisma generate && prisma-entity-gen"
  }
}

Uso com BaseRepository

A lib gera apenas as entities. O BaseRepository do seu projeto usa o T genérico:

// antes — tipo do Prisma
export class UserRepository extends BaseRepository<User> {}

// depois — entity gerada
export class UserRepository extends BaseRepository<UserEntity> {}

Os métodos do BaseRepository continuam funcionando com Partial<T> nos filtros:

// where tipado pela entity
const users = await userRepository.findMany({ email: '[email protected]' });
// → UserEntity[]

const user = await userRepository.getById(id);
// → UserEntity

Comportamento dos tipos

| Campo no schema | Entity gerada | |---|---| | field String | field: string | | field String? | field?: string \| null | | field String @default(...) | field: string | | field Model (relação) com relations: "optional" | field?: ModelEntity | | field Model (relação) com relations: "required" | field: ModelEntity | | field Model? (relação opcional) | field?: ModelEntity \| null |

Tipos escalares Prisma → TypeScript

| Prisma | TypeScript | |---|---| | String | string | | Boolean | boolean | | Int | number | | Float | number | | BigInt | bigint | | Decimal | string | | DateTime | Date | | Json | Record<string, unknown> | | Bytes | Buffer |


Arquivos de configuração suportados

O gerador procura por arquivos de configuração nesta ordem:

  1. .entitygenrc.json
  2. entitygen.config.json
  3. .entitygenrc