forked from upstash/redis-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmod.ts
115 lines (106 loc) · 2.78 KB
/
mod.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
import {
HttpClient,
HttpClientConfig,
RequesterConfig,
RetryConfig,
} from "./pkg/http.ts";
import * as core from "./pkg/redis.ts";
export type { Requester, UpstashRequest, UpstashResponse } from "./pkg/http.ts";
import { VERSION } from "./version.ts";
/**
* Connection credentials for upstash redis.
* Get them from https://console.upstash.com/redis/<uuid>
*/
export type RedisConfigDeno =
& {
/**
* UPSTASH_REDIS_REST_URL
*/
url: string;
/**
* UPSTASH_REDIS_REST_TOKEN
*/
token: string;
/**
* Configure the retry behaviour in case of network errors
*
* Set false to disable retries
*/
retry?: RetryConfig;
}
& core.RedisOptions
& RequesterConfig;
/**
* Serverless redis client for upstash.
*/
export class Redis extends core.Redis {
/**
* Create a new redis client
*
* @example
* ```typescript
* const redis = new Redis({
* url: "<UPSTASH_REDIS_REST_URL>",
* token: "<UPSTASH_REDIS_REST_TOKEN>",
* });
* ```
*/
constructor(config: RedisConfigDeno) {
if (
config.url.startsWith(" ") ||
config.url.endsWith(" ") ||
/\r|\n/.test(config.url)
) {
console.warn(
"The redis url contains whitespace or newline, which can cause errors!",
);
}
if (
config.token.startsWith(" ") ||
config.token.endsWith(" ") ||
/\r|\n/.test(config.token)
) {
console.warn(
"The redis token contains whitespace or newline, which can cause errors!",
);
}
const telemetry: HttpClientConfig["telemetry"] = {};
if (!Deno.env.get("UPSTASH_DISABLE_TELEMETRY")) {
// Deno Deploy does not include the version data, so we need to treat it as optional
telemetry.runtime = `deno@${Deno.version?.deno}`;
telemetry.sdk = `@upstash/redis@${VERSION}`;
}
const client = new HttpClient({
retry: config.retry,
baseUrl: config.url,
headers: { authorization: `Bearer ${config.token}` },
responseEncoding: config.responseEncoding,
telemetry,
});
super(client, {
automaticDeserialization: config.automaticDeserialization,
});
}
/*
* Create a new Upstash Redis instance from environment variables on Deno.
*
*/
static fromEnv(opts?: Omit<RedisConfigDeno, "url" | "token">): Redis {
/**
* These should be injected by Deno.
*/
const url = Deno.env.get("UPSTASH_REDIS_REST_URL");
if (!url) {
throw new Error(
"Unable to find environment variable: `UPSTASH_REDIS_REST_URL`.",
);
}
const token = Deno.env.get("UPSTASH_REDIS_REST_TOKEN");
if (!token) {
throw new Error(
"Unable to find environment variable: `UPSTASH_REDIS_REST_TOKEN`.",
);
}
return new Redis({ ...opts, url, token });
}
}