Postgres
Postgres-backed keystore adapter.
Overview
- Postgres-backed keystore that accepts any
pg
-like client exposingquery(sql, params?)
. - Creates the table and indexes if they do not exist.
metadata
can be stored asTEXT
(default) orJSONB
whenuseJsonbMetadata
is enabled.
Usage
import { Client } from "pg";
import { PostgresKeyStore, usefulkey } from "betterkey";
const client = new Client({ connectionString: process.env.DATABASE_URL });
await client.connect();
const keyStore = new PostgresKeyStore(client, {
tableName: "usefulkey_keys",
useJsonbMetadata: true,
});
const uk = usefulkey({ adapters: { keyStore } });
Client compatibility
- Any Postgres client exposing
query(sql, params?)
(e.g.,pg
,postgres.js
).
Options
Option | Type | Default | Description |
---|---|---|---|
tableName | string | "usefulkey_keys" | Name of the table to store keys. |
useJsonbMetadata | boolean | false | When true , uses a JSONB column and casts to ::jsonb on writes; otherwise stores metadata as TEXT . |
Schema
CREATE TABLE IF NOT EXISTS usefulkey_keys (
id TEXT PRIMARY KEY,
user_id TEXT,
prefix TEXT NOT NULL,
key_hash TEXT NOT NULL UNIQUE,
created_at BIGINT NOT NULL,
expires_at BIGINT,
metadata JSONB,
uses_remaining INTEGER,
revoked_at BIGINT
);
CREATE INDEX IF NOT EXISTS idx_usefulkey_keys_user_id ON usefulkey_keys(user_id);
CREATE UNIQUE INDEX IF NOT EXISTS idx_usefulkey_keys_key_hash ON usefulkey_keys(key_hash);
Notes
- When
useJsonbMetadata
isfalse
(default),metadata
is stored as serialized JSON text in aTEXT
column. - When
useJsonbMetadata
istrue
,metadata
is stored in aJSONB
column; passing plain JS objects works transparently. created_at
,expires_at
, andrevoked_at
are epoch milliseconds.