Generate Repository
Generate a repository class for SQLite data access following the repository pattern.
Usage
When user requests to create a repository, ask for:
- Entity name (e.g., "WaterLog", "SleepLog", "WeightTracking")
- Table name (snake_case, e.g., "water_logs", "sleep_logs")
- Fields and their types (with database column names)
- Which fields are JSON (arrays, objects, etc.)
- Whether to include getByDate() method
Implementation Pattern
Based on src/lib/database/repositories/mealLogRepository.ts pattern.
File Structure
Create file: src/lib/database/repositories/{entityName}Repository.ts
import { getDatabase } from '../connection';
import type { EntityType } from '@/lib/types/health';
import { v4 as uuidv4 } from 'uuid';
export class EntityRepository {
private db = getDatabase();
addEntity(data: Omit<EntityType, 'id' | 'createdAt'>): EntityType {
const id = uuidv4();
const createdAt = new Date().toISOString();
const newEntity = { ...data, id, createdAt };
const stmt = this.db.prepare(`
INSERT INTO table_name (id, field1, field2, created_at)
VALUES (?, ?, ?, ?)
`);
stmt.run(
newEntity.id,
newEntity.field1,
JSON.stringify(newEntity.field2), // for JSON fields
newEntity.createdAt
);
return newEntity;
}
getEntitiesByDate(date: string): EntityType[] {
const stmt = this.db.prepare('SELECT * FROM table_name WHERE date = ?');
const rows = stmt.all(date) as any[];
return rows.map((row) => ({
id: row.id,
date: row.date,
field1: row.field_1, // snake_case → camelCase
field2: JSON.parse(row.field_2), // JSON fields
createdAt: row.created_at,
}));
}
getEntityById(id: string): EntityType | null {
const stmt = this.db.prepare('SELECT * FROM table_name WHERE id = ?');
const row = stmt.get(id) as any;
if (!row) return null;
return {
id: row.id,
date: row.date,
field1: row.field_1,
field2: JSON.parse(row.field_2),
createdAt: row.created_at,
};
}
getAllEntities(): EntityType[] {
const stmt = this.db.prepare('SELECT * FROM table_name');
const rows = stmt.all() as any[];
return rows.map((row) => ({
id: row.id,
date: row.date,
field1: row.field_1,
field2: JSON.parse(row.field_2),
createdAt: row.created_at,
}));
}
updateEntity(id: string, updates: Partial<EntityType>): void {
const stmt = this.db.prepare('SELECT * FROM table_name WHERE id = ?');
const current = stmt.get(id) as any;
if (!current) throw new Error('Entity not found');
const updated = {
...current,
...updates,
field_2: JSON.stringify(updates.field2 || JSON.parse(current.field_2)),
};
const updateStmt = this.db.prepare(`
UPDATE table_name SET
field_1 = ?,
field_2 = ?
WHERE id = ?
`);
updateStmt.run(updated.field_1, updated.field_2, id);
}
deleteEntity(id: string): void {
const stmt = this.db.prepare('DELETE FROM table_name WHERE id = ?');
stmt.run(id);
}
}
Key Conventions
- Class name:
{Entity}Repository (PascalCase)
- Private
db property via getDatabase()
- Use
uuid() for IDs, ISO strings for timestamps
- Throw errors with descriptive messages (e.g., 'Entity not found')
- Map DB columns (snake_case) to TS props (camelCase)
- JSON fields use
JSON.stringify() on write, JSON.parse() on read
- Date-based queries use
WHERE date = ? pattern
- Include both getByDate and getById methods when applicable
Steps
- Ask user for entity name, table name, fields, and JSON fields
- Create file:
src/lib/database/repositories/{entityName}Repository.ts
- Generate class with private db connection
- Generate CRUD methods (add, get, update, delete)
- Add row mapping for snake_case → camelCase conversion
- Handle JSON fields with JSON.stringify/parse
- Export class for use in API routes
Implementation Checklist
1---
2name: generate-repository
3description: Generate repository class for SQLite data access with CRUD methods, row mapping, and TypeScript types. Use when creating new database tables or data access layers.
4allowed-tools: Read, Write, Glob, Grep
5metadata:
6 source: https://skillmd.com/skills/aibot88/generate-repository
7---
8
9# Generate Repository
10
11Generate a repository class for SQLite data access following the repository pattern.
12
13## Usage
14
15When user requests to create a repository, ask for:
16
171. **Entity name** (e.g., "WaterLog", "SleepLog", "WeightTracking")
182. **Table name** (snake_case, e.g., "water_logs", "sleep_logs")
193. **Fields** and their types (with database column names)
204. **Which fields are JSON** (arrays, objects, etc.)
215. **Whether to include getByDate() method**
22
23## Implementation Pattern
24
25Based on `src/lib/database/repositories/mealLogRepository.ts` pattern.
26
27### File Structure
28
29Create file: `src/lib/database/repositories/{entityName}Repository.ts`
30
31```typescript
32import { getDatabase } from '../connection';
33import type { EntityType } from '@/lib/types/health';
34import { v4 as uuidv4 } from 'uuid';
35
36export class EntityRepository {
37 private db = getDatabase();
38
39 addEntity(data: Omit<EntityType, 'id' | 'createdAt'>): EntityType {
40 const id = uuidv4();
41 const createdAt = new Date().toISOString();
42 const newEntity = { ...data, id, createdAt };
43
44 const stmt = this.db.prepare(`
45 INSERT INTO table_name (id, field1, field2, created_at)
46 VALUES (?, ?, ?, ?)
47 `);
48
49 stmt.run(
50 newEntity.id,
51 newEntity.field1,
52 JSON.stringify(newEntity.field2), // for JSON fields
53 newEntity.createdAt
54 );
55
56 return newEntity;
57 }
58
59 getEntitiesByDate(date: string): EntityType[] {
60 const stmt = this.db.prepare('SELECT * FROM table_name WHERE date = ?');
61 const rows = stmt.all(date) as any[];
62
63 return rows.map((row) => ({
64 id: row.id,
65 date: row.date,
66 field1: row.field_1, // snake_case → camelCase
67 field2: JSON.parse(row.field_2), // JSON fields
68 createdAt: row.created_at,
69 }));
70 }
71
72 getEntityById(id: string): EntityType | null {
73 const stmt = this.db.prepare('SELECT * FROM table_name WHERE id = ?');
74 const row = stmt.get(id) as any;
75
76 if (!row) return null;
77
78 return {
79 id: row.id,
80 date: row.date,
81 field1: row.field_1,
82 field2: JSON.parse(row.field_2),
83 createdAt: row.created_at,
84 };
85 }
86
87 getAllEntities(): EntityType[] {
88 const stmt = this.db.prepare('SELECT * FROM table_name');
89 const rows = stmt.all() as any[];
90
91 return rows.map((row) => ({
92 id: row.id,
93 date: row.date,
94 field1: row.field_1,
95 field2: JSON.parse(row.field_2),
96 createdAt: row.created_at,
97 }));
98 }
99
100 updateEntity(id: string, updates: Partial<EntityType>): void {
101 const stmt = this.db.prepare('SELECT * FROM table_name WHERE id = ?');
102 const current = stmt.get(id) as any;
103 if (!current) throw new Error('Entity not found');
104
105 const updated = {
106 ...current,
107 ...updates,
108 field_2: JSON.stringify(updates.field2 || JSON.parse(current.field_2)),
109 };
110
111 const updateStmt = this.db.prepare(`
112 UPDATE table_name SET
113 field_1 = ?,
114 field_2 = ?
115 WHERE id = ?
116 `);
117
118 updateStmt.run(updated.field_1, updated.field_2, id);
119 }
120
121 deleteEntity(id: string): void {
122 const stmt = this.db.prepare('DELETE FROM table_name WHERE id = ?');
123 stmt.run(id);
124 }
125}
126```
127
128## Key Conventions
129
130- Class name: `{Entity}Repository` (PascalCase)
131- Private `db` property via `getDatabase()`
132- Use `uuid()` for IDs, ISO strings for timestamps
133- Throw errors with descriptive messages (e.g., 'Entity not found')
134- Map DB columns (snake_case) to TS props (camelCase)
135- JSON fields use `JSON.stringify()` on write, `JSON.parse()` on read
136- Date-based queries use `WHERE date = ?` pattern
137- Include both getByDate and getById methods when applicable
138
139## Steps
140
1411. Ask user for entity name, table name, fields, and JSON fields
1422. Create file: `src/lib/database/repositories/{entityName}Repository.ts`
1433. Generate class with private db connection
1444. Generate CRUD methods (add, get, update, delete)
1455. Add row mapping for snake_case → camelCase conversion
1466. Handle JSON fields with JSON.stringify/parse
1477. Export class for use in API routes
148
149## Implementation Checklist
150
151- [ ] Repository class properly exported
152- [ ] CRUD methods implemented
153- [ ] Row mapping handles snake_case to camelCase
154- [ ] JSON fields properly serialized
155- [ ] Error handling for not found cases
156- [ ] Timestamps use ISO format
157- [ ] UUIDs generated for new records