Skip to content

Commit f88a6ed

Browse files
committed
Fix potential uncaught promise rejection
1 parent 303371d commit f88a6ed

File tree

1 file changed

+14
-5
lines changed

1 file changed

+14
-5
lines changed

src/token.ts

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import type { webcrypto } from "node:crypto";
12
import type { TenantTokenGeneratorOptions, TokenSearchRules } from "./types";
23

34
function getOptionsWithDefaults(options: TenantTokenGeneratorOptions) {
@@ -26,10 +27,17 @@ function encodeToBase64(data: unknown): string {
2627
}
2728

2829
// missing crypto global for Node.js 18 https://nodejs.org/api/globals.html#crypto_1
29-
const cryptoPonyfill =
30-
typeof crypto === "undefined"
31-
? import("node:crypto").then((v) => v.webcrypto)
32-
: Promise.resolve(crypto);
30+
let cryptoPonyfill: Promise<Crypto | typeof webcrypto> | undefined;
31+
function getCrypto() {
32+
if (cryptoPonyfill === undefined) {
33+
cryptoPonyfill =
34+
typeof crypto === "undefined"
35+
? import("node:crypto").then((v) => v.webcrypto)
36+
: Promise.resolve(crypto);
37+
}
38+
39+
return cryptoPonyfill;
40+
}
3341

3442
const textEncoder = new TextEncoder();
3543

@@ -39,7 +47,7 @@ async function sign(
3947
encodedPayload: string,
4048
encodedHeader: string,
4149
): Promise<string> {
42-
const crypto = await cryptoPonyfill;
50+
const crypto = await getCrypto();
4351

4452
const cryptoKey = await crypto.subtle.importKey(
4553
// https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/importKey#raw
@@ -149,6 +157,7 @@ function tryDetectEnvironment(): void {
149157
);
150158
}
151159

160+
// TODO: Add option of MeiliSearch instead of apiKeyUid? Or rather raise issue about it for now.
152161
/**
153162
* Generate a tenant token.
154163
*

0 commit comments

Comments
 (0)