Integrating with Databases
1. Connecting to SQL Databases
| Driver | DB |
|---|---|
| pg | PostgreSQL |
| mysql2 | MySQL/MariaDB |
| better-sqlite3 | SQLite (sync) |
| tedious | SQL Server |
2. Connecting to NoSQL Databases
| DB | Driver |
|---|---|
| MongoDB | mongodb / mongoose |
| DynamoDB | @aws-sdk/client-dynamodb |
| Redis | ioredis / @upstash/redis |
| Cassandra | cassandra-driver |
3. Using ORM Integration
| ORM | Detail |
|---|---|
| Prisma | Schema-first, generates type-safe client |
| Drizzle | SQL-like, lightweight, edge-friendly |
| TypeORM | Decorator-based |
| MikroORM | Unit-of-work pattern |
4. Mapping Types to Tables
Example: Prisma → GraphQL
// prisma model User { id Int @id; email String; name String? }
type User {
id: ID!
email: EmailAddress!
name: String # nullable matches Prisma optional
}
5. Generating Schema from Database
| Tool | Detail |
|---|---|
| Hasura | Auto GraphQL from Postgres/MS-SQL/etc. |
| PostGraphile | Postgres → GraphQL with introspection |
| Prisma + Pothos | Code-first with prisma-plugin |
| Nexus prisma | Generates types from Prisma schema |
6. Implementing Query Builders
| Library | Detail |
|---|---|
| Kysely | Type-safe SQL builder |
| Knex | Mature, multi-dialect |
| Drizzle | Schema-aware builder |
7. Using Connection Pooling
| Setting | Detail |
|---|---|
| max | Match DB max_connections / pods |
| idleTimeout | 30s to release stale |
| Serverless | Use PgBouncer / Prisma Accelerate / Neon proxy |
8. Handling Transactions
Example: Prisma transaction
const result = await prisma.$transaction(async (tx) => {
const order = await tx.order.create({ data: { userId, total } });
await tx.inventory.update({ where: { sku }, data: { qty: { decrement: 1 } } });
return order;
}, { isolationLevel: "Serializable" });
9. Implementing Database Migrations
| Tool | Detail |
|---|---|
| Prisma Migrate | SQL migrations from schema diff |
| Drizzle Kit | generate + migrate commands |
| node-pg-migrate | Plain SQL/JS migrations |
| Sqitch / Flyway | Standalone, language-agnostic |
10. Optimizing Database Access
| Practice | Detail |
|---|---|
| Project only requested columns | Inspect info in resolver |
| Indexes on join + sort columns | Avoid sequential scans |
| Batch via DataLoader | Solve N+1 |
| Cursor pagination | Avoid OFFSET |
| Materialized views | For heavy aggregates |