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

Removes crypto dependency so this can be used in edge runtimes #12

Merged
merged 2 commits into from
Jul 10, 2024
Merged
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: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
"@types/node": "^20.8.9",
"@upstash/redis": "^1.24.1",
"bun-types": "^1.0.7",
"crypto": "^1.0.1",
"tsup": "^7.2.0",
"typescript": "^5.2.2"
},
Expand Down
14 changes: 12 additions & 2 deletions src/lock.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { randomUUID } from "crypto";
import type { LockAcquireConfig, LockConfig, LockCreateConfig, LockStatus } from "./types";

export class Lock {
Expand Down Expand Up @@ -35,7 +34,18 @@ export class Lock {
const retryDelay = acquireConfig?.retry?.delay ?? this.config.retry?.delay;

let attempts = 0;
const UUID = randomUUID();

let UUID: string;
if (acquireConfig?.uuid) {
UUID = acquireConfig.uuid;
} else {
try {
UUID = crypto.randomUUID();
} catch (error) {
throw new Error('No UUID provided and crypto module is not available in this environment.');
}
}

while (attempts < retryAttempts) {
const upstashResult = await this.config.redis.set(this.config.id, UUID, {
nx: true,
Expand Down
5 changes: 5 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,11 @@ export type LockAcquireConfig = {
* The config for retrying to acquire the lock.
*/
retry?: RetryConfig;

/**
* The uuid to be used for the lock.
*/
uuid?: string;
};

export type LockConfig = {
Expand Down
Loading