Getting Started with Drift KV

Drift KV is a powerful, type-safe ORM designed for Deno KV and modern TypeScript environments. This guide will help you get started with Drift KV and understand its core concepts.

Installation

You can install Drift KV using your preferred package manager:

# Using npm
npm install @drift-kv/core

# Using Deno
deno add jsr:@drift-kv/core

# Using Bun
bun add @drift-kv@core

Quick Start

Here's a basic example to get you started with Drift KV:

import { Drift, DriftEntity } from "@drift-kv/core";

// Initialize Deno KV client
const client = await Deno.openKv();

// Create Drift instance
const drift = new Drift({
  client,
  schemas: {
    entities: {
      user: new DriftEntity({
        name: "user",
        schema: (z) => ({
          id: z.string().uuid(),
          name: z.string().min(3),
          email: z.string().email(),
          createdAt: z.date(),
          updatedAt: z.date(),
        }),
      }),
    },
  },
  hooks: {
    onConnect: async (client) => {
      console.log("Connected successfully!");
    },
    onError: async (error) => {
      console.error("Database error:", error);
    },
  },
});

Core Concepts

1. Database Connection

Drift KV works with Deno KV as its database backend. The connection is managed through the Drift class constructor:

import { Drift, DriftEntity } from "@drift-kv/core";

const drift = new Drift({
  client: await Deno.openKv(),
  // See how to configure your entities and queues in the next sections ...
});

2. Schema Definition

Schemas in Drift KV are defined using Zod, providing runtime type safety and validation:

const userEntity = new DriftEntity({
  name: "user",
  options: {
    timestamps: true,
  },
  schema: (z) => ({
    name: z.string().min(3),
    email: z.string().email(),
    role: z.enum(["user", "admin"]).default("user"),
  }),
});

const drift = new Drift({
  client: await Deno.openKv(),
  schemas: {
    entities: {
      user: userEntity,
    },
  },
});

3. Entity Management

Entities are the core building blocks of Drift KV:

const userEntity = drift.entities.user;

// Create a new user
const user = await userEntity.create({
  data: {
    name: "John Doe",
    email: "john@example.com",
  },
});

// Query users
const users = await userEntity.findMany({
  where: {
    role: "admin",
  },
});

4. Lifecycle Hooks

Drift KV provides various hooks to intercept and modify behavior:

const drift = new Drift({
  hooks: {
    onConnect: async (client) => {
      // Run after successful connection
    },
    onError: async (error) => {
      // Handle errors
    },
    beforeQuery: async (query) => {
      // Run before each query
    },
    afterQuery: async (result) => {
      // Run after each query
    },
  },
});

Basic Operations

Creating Records

const newUser = await drift.entities.user.create({
  data: {
    name: "Jane Doe",
    email: "jane@example.com",
  },
});

Querying Records

// Find one user
const user = await drift.entities.user.findUnique({
  where: { id: "123" },
});

// Find many users with filters
const users = await drift.entities.user.findMany({
  where: {
    role: "admin",
  },
});

Updating Records

const updatedUser = await drift.entities.user.update({
  where: { id: "123" },
  data: {
    name: "Jane Smith",
    updatedAt: new Date(),
  },
});

Deleting Records

const deletedUser = await drift.entities.user.delete({
  where: { id: "123" },
});

Error Handling

Drift KV provides built-in error handling through hooks and try-catch blocks:

try {
  const user = await drift.entities.user.findUnique({
    where: { id: "non-existent" },
  });
} catch (error) {
  if (error instanceof DriftError) {
    console.error("Drift specific error:", error.message);
  } else {
    console.error("Unexpected error:", error);
  }
}

Best Practices

  • Type Safety: Always define proper schemas using Zod, utilize TypeScript's type inference, and keep your types up to date.
  • Error Handling: Implement proper error handling using try-catch, use the built-in error types, and set up error hooks for logging.
  • Connection Management: Initialize connections early, handle connection errors gracefully, and close connections when done.
  • Query Optimization: Use selective queries with select, implement proper filtering with where, and use pagination when dealing with large datasets.

Need Help?

Built for Deno KV

Discover Drift KV: The Ultimate Type-Safe ORM for Deno KV

Experience a powerful ORM with real-time subscriptions, job queues, and seamless compatibility across Deno KV, Node.js, Bun.js, and Edge environments.