@potonz/shortlinks-manager-cf-d1
v0.3.4
Published
Short links manager extension for Cloudflare D1
Readme
@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
bun add @potonz/shortlinks-manager-cf-d1Usage
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:
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 fromenv.DBin 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 IDcreateShortLink(shortId, targetUrl)- Create a new short linkcheckShortIdsExist(shortIds)- Check which short IDs already existupdateShortLinkLastAccessTime(shortId, time)- Update last accessed timestampcleanUnusedLinks(maxAge)- Remove links not accessed inmaxAgedaysremoveShortLink(shortId)- Remove a short link by ID
Cloudflare Workers Setup
- Configure D1 binding in
wrangler.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"
}
]
}- Create D1 database:
wrangler d1 create shortlinks- Deploy with Wrangler:
wrangler deployTesting
Tests run against a local D1-compatible SQLite database.
To run tests locally:
bun test packages/shortlinks-manager-cf-d1License
MIT
