Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: added redis store #50

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file modified bun.lockb
Binary file not shown.
1 change: 1 addition & 0 deletions packages/openauth/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"@types/node": "22.10.1",
"arctic": "2.2.2",
"hono": "4.6.9",
"ioredis": "5.4.1",
"typescript": "5.6.3",
"valibot": "1.0.0-beta.5"
},
Expand Down
71 changes: 71 additions & 0 deletions packages/openauth/src/storage/redis.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import { Redis, RedisOptions } from "ioredis"
import { joinKey, splitKey, StorageAdapter } from "./storage.js"

export interface RedisStorageOptions {
connectionUrl: string
}

export interface RedisStorageCredentials extends RedisOptions {}

type OnlyOne<T> = T extends RedisStorageCredentials
? Required<RedisStorageCredentials> extends T
? T
: never
: RedisStorageOptions extends T
? T
: never

export function RedisStorage<
T extends RedisStorageOptions | RedisStorageCredentials,
>(opts: OnlyOne<T>): StorageAdapter {
const client =
"connectionUrl" in opts ? new Redis(opts.connectionUrl) : new Redis(opts)

return {
async get(key: string[]) {
const value = await client.get(joinKey(key))
if (!value) return
return JSON.parse(value) as Record<string, any>
},
async set(key: string[], value: any, ttl?: number) {
if (ttl !== undefined && ttl > 0) {
await client.set(
joinKey(key),
JSON.stringify(value),
"EX",
Math.trunc(ttl),
)
} else {
await client.set(joinKey(key), JSON.stringify(value))
}
},
async remove(key: string[]) {
await client.del(joinKey(key))
},
async *scan(prefix: string[]) {
let cursor = "0"

while (true) {
let [next, keys] = await client.scan(
cursor,
"MATCH",
`${joinKey(prefix)}*`,
)

for (const key of keys) {
const value = await client.get(key)
if (value !== null) {
yield [splitKey(key), JSON.parse(value)]
}
}

// Number(..) cant handle 64bit integer
if (BigInt(next) === BigInt(0)) {
break
}

cursor = next
}
},
}
}