npm package: @potonz/shortlinks-manager-cf-d1
Description: Short links manager extension for Cloudflare D1
Author: Thomas Nguyen
Latest version: 0.3.4

# @potonz/shortlinks-manager-cf-d1

Cloudflare D1 backend for short links manager.

## Features

- Cloudflare D1 SQLite support for edge deployment
- Automatic table creation and indexing
- Perfect for Cloudflare Workers environment
- Built-in cache integration for high performance
- Lightweight and efficient SQLite operations

## Installation

```bash
bun add @potonz/shortlinks-manager-cf-d1
```

## Usage

```typescript
import { createManager } from "@potonz/shortlinks-manager";
import { createD1Backend } from "@potonz/shortlinks-manager-cf-d1";
import { env } from "cloudflare:workers";

// Create backend with D1 binding
const backend = createD1Backend(env.DB);

// Initialize tables (run once during setup)
await backend.setupTables();

// Create manager
const manager = await createManager({
    backend,
    shortIdLength: 6,
    onShortIdLengthUpdated: (newLength) => {
        console.log(`Short ID length updated to ${newLength}`);
    },
});

// Create short link
const shortId = await manager.createShortLink("https://example.com");
console.log(`Created short link: ${shortId}`);

// Resolve short link
const targetUrl = await manager.getTargetUrl(shortId);
console.log(`Target URL: ${targetUrl}`);
```

## Database Schema

The backend automatically creates the following table:

```sql
CREATE TABLE IF NOT EXISTS sl_links_map (
    short_id TEXT NOT NULL PRIMARY KEY,
    target_url TEXT NOT NULL,
    last_accessed_at INTEGER DEFAULT (strftime('%s', 'now')),
    created_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now'))
);

CREATE INDEX IF NOT EXISTS idx_sl_links_map_last_accessed_at 
ON sl_links_map(last_accessed_at);
```

## API

### `createD1Backend(db: D1Database)`

Creates a Cloudflare D1 backend instance.

**Parameters:**
- `db` - Cloudflare D1 database binding (typically from `env.DB` in Workers)

**Returns:** `IShortLinksManagerBackend`

### `backend.setupTables()`

Creates the required database tables and indexes. Should be called once during application initialization.

### Backend Methods

Implements all `IShortLinksManagerBackend` methods:

- `getTargetUrl(shortId)` - Get target URL by short ID
- `createShortLink(shortId, targetUrl)` - Create a new short link
- `checkShortIdsExist(shortIds)` - Check which short IDs already exist
- `updateShortLinkLastAccessTime(shortId, time)` - Update last accessed timestamp
- `cleanUnusedLinks(maxAge)` - Remove links not accessed in `maxAge` days
- `removeShortLink(shortId)` - Remove a short link by ID

## Cloudflare Workers Setup

1. Configure D1 binding in `wrangler.jsonc`:

```jsonc
{
    "$schema": "node_modules/wrangler/config-schema.json",
    "name": "your-worker-name",
    "main": "src/index.ts",
    "compatibility_date": "2025-12-25",
    "d1_databases": [
        {
            "binding": "DB",
            "database_id": "your-database-id",
            "database_name": "shortlinks"
        }
    ]
}
```

2. Create D1 database:

```bash
wrangler d1 create shortlinks
```

3. Deploy with Wrangler:

```bash
wrangler deploy
```

## Testing

Tests run against a local D1-compatible SQLite database.

To run tests locally:

```bash
bun test packages/shortlinks-manager-cf-d1
```

## License

MIT