@getgitops/gitdb
v0.2.0
Published
GitDB is a lightweight, fast, and simple Git-based database for Node.js. It allows you to store and retrieve data in a Git repository, making it easy to version control your data.
Readme
@getgitops/gitdb
Un ORM ligero y type-safe construido sobre Git como almacenamiento. Perfect para aplicaciones que necesitan versionado, auditoría y sincronización distribuida de datos.
GitDB transforma repositorios Git en bases de datos relacionales, permitiendo CRUD operations con control de versiones automático, relaciones tipadas y queries type-safe.
Características
- 🔐 Type-Safe: TypeScript first, validación de tipos en tiempo de compilación
- 📦 Git-Powered: Cada cambio es un commit automático con historial completo
- 🔗 Relaciones Tipadas: Soporte para relaciones One-to-Many y Many-to-One
- 🎯 Queries Type-Safe: Operadores WHERE validados por tipos
- 📊 Agregaciones: Soporte para COUNT, SUM, AVG
- 🚀 Ligero: Sin dependencias externas, basado en Git nativo
Instalación
npm install @getgitops/gitdbRequisitos:
- Node.js >= 20
- Git 2.20+
Uso Rápido
1. Definir Schema
import { entity, uuid, text, int, timestamp } from '@getgitops/gitdb';
export const User = entity('users', {
id: uuid().primary(),
email: text().unique(),
name: text(),
age: int(),
createdAt: timestamp()
});
export const Post = entity('posts', {
id: uuid().primary(),
userId: uuid(),
title: text(),
content: text(),
createdAt: timestamp()
});2. Inicializar GitDB
import { gitDb } from '@getgitops/gitdb';
const db = await gitDb({
dir: '/path/to/repo',
author: {
name: 'App Bot',
email: '[email protected]'
}
});3. Operaciones CRUD
Insert
const newUser = await db.insert(User).values({
id: 'uuid-1',
email: '[email protected]',
name: 'John Doe',
age: 30,
createdAt: new Date()
});Select
// Obtener todos
const allUsers = await db.select().from(User);
// Con WHERE
const adults = await db
.select()
.from(User)
.where(gte('age', 18));
// Campos específicos
const emails = await db
.select(['email', 'name'])
.from(User);
// Con AND/OR
const filtered = await db
.select()
.from(User)
.where(
and(
eq('age', 30),
ilike('email', '%@example.com')
)
);Update
await db
.update(User)
.set({ name: 'Jane Doe', age: 31 })
.where(eq('id', 'uuid-1'));Delete
await db
.delete()
.from(User)
.where(eq('id', 'uuid-1'));4. Relaciones
import { defineRelations } from '@getgitops/gitdb';
defineRelations(User, {
posts: {
type: 'many',
entity: Post,
foreignKey: 'userId'
}
});
defineRelations(Post, {
author: {
type: 'one',
entity: User,
foreignKey: 'userId'
}
});
// Usar con include
const userWithPosts = await db
.select()
.from(User)
.where(eq('id', 'uuid-1'))
.include({
posts: true
});5. Agregaciones
// COUNT
const totalUsers = await db.$count(User);
const adults = await db.$count(User, gte('age', 18));
// SUM
const totalAge = await db.$sum(User, 'age');
// AVG
const avgAge = await db.$avg(User, 'age');Tipos Soportados
uuid()- UUID/GUIDtext()- Textovarchar(n)- Texto con límiteint()/integer()- Enterosbigint()- Enteros grandesreal()/double()/doublePrecision()- Decimalesnumeric(precision, scale)- Decimales precisosbool()/boolean()- Booleanosdate()- Solo fechatimestamp()- Fecha y horachar(n)- Carácter fijojson()- Objeto JSON
Operadores WHERE
eq(field, value)- Igualne(field, value)- No igualgt(field, value)- Mayor quegte(field, value)- Mayor o iguallt(field, value)- Menor quelte(field, value)- Menor o igualilike(field, pattern)- Case-insensitive LIKEand(...predicates)- AND lógicoor(...predicates)- OR lógiconot(predicate)- Negación
Desarrollo
Scripts
npm run build # Build distribución
npm run typecheck # Verificar tipos TypeScript
npm run test # Ejecutar tests
npm run test:watch # Tests en modo watch
npm run dev # Build en watch mode
npm run demo # Demo interactivoPublicación y Release
Workflow de Changesets
Crear cambios - Edita los archivos normalmente
Generar changeset - Ejecuta:
npm run changesetEsto crea un archivo en
.changeset/describiendo los cambiosCrear PR de versión - Push a
main/develop, GitHub Actions crea PR de versión automáticamenteMerge PR - Se publica automáticamente en NPM
Publicación Manual
npm run releaseEsto:
- Ejecuta type check y tests
- Genera version automática (Semantic Versioning)
- Publica en NPM
Secretos Requeridos
Configura en GitHub (Settings → Secrets):
NPM_TOKEN- Token de acceso a NPM
GitHub Actions
test.yml
Ejecuta tests en push/PR a main y develop con Node 20 y 22.
publish-npm.yml
Publica en NPM en push a main o con tag gitdb-vX.Y.Z.
changesets-release.yml
Maneja releases automáticos basado en changesets.
Estructura de Proyectos
.
├── src/
│ ├── core/
│ │ ├── gitdb.ts # Clase principal GitDB
│ │ ├── schema.ts # Builder de schema y tipos
│ │ └── relations.ts # Definición de relaciones
│ ├── infrastructure/
│ │ ├── git-repository.ts # Abstracciones Git
│ │ ├── file-manager.ts # Operaciones con filesystem
│ │ └── logger.ts # Logging
│ ├── queries/
│ │ ├── select-query.ts
│ │ ├── insert-query.ts
│ │ ├── update-query.ts
│ │ ├── delete-query.ts
│ │ └── where-operators.ts
│ ├── types.ts # Tipos globales
│ └── index.ts # Exports públicos
├── tests/ # E2E tests
└── .changeset/ # Changesets para releasesLicencia
MIT
- Publica automaticamente al mergear la PR de version
Requiere el secreto de repositorio:
- NPM_TOKEN (token con permisos de publish en npm)
