@upstash/redis 1.4.0-next.1 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -25,21 +25,15 @@ supported.
25
25
 
26
26
  ## Upgrading to v1.4.0 **(ReferenceError: fetch is not defined)**
27
27
 
28
- If you are running on nodejs v17 and earlier, you need to manually provide a
29
- `fetch` polyfill. The simplest way is using `isomorphic-fetch`
30
-
31
- ```bash
32
- npm install isomorphic-fetch
33
- ```
28
+ If you are running on nodejs v17 and earlier, `fetch` will not be natively
29
+ supported. Platforms like Vercel, Netlify, Deno, Fastly etc. provide a polyfill
30
+ for you. But if you are running on bare node, you need to either specify a
31
+ polyfill yourself or change the import path to:
34
32
 
35
33
  ```typescript
36
- import "isomorphic-fetch";
37
- import { Redis } from "@upstash/redis";
34
+ import { Redis } from "@upstash/redis/with-fetch";
38
35
  ```
39
36
 
40
- `fetch` is natively supported in node18 as well as all major platforms: Vercel,
41
- Netlify, Deno, Fastly etc. and you do not need to do anything.
42
-
43
37
  ## Upgrading from v0.2.0?
44
38
 
45
39
  Please read the
@@ -93,6 +87,15 @@ const redis = new Redis({
93
87
  const redis = Redis.fromEnv()
94
88
  ```
95
89
 
90
+ If you are running on nodejs v17 and earlier, `fetch` will not be natively
91
+ supported. Platforms like Vercel, Netlify, Deno, Fastly etc. provide a polyfill
92
+ for you. But if you are running on bare node, you need to either specify a
93
+ polyfill yourself or change the import path to:
94
+
95
+ ```typescript
96
+ import { Redis } from "@upstash/redis/with-fetch";
97
+ ```
98
+
96
99
  - [Code example](https://github.com/upstash/upstash-redis/blob/main/examples/nodejs)
97
100
 
98
101
  #### Cloudflare Workers
@@ -5,16 +5,7 @@ import { Command } from "./command.js";
5
5
  export class ScriptExistsCommand extends Command {
6
6
  constructor(hashes, opts) {
7
7
  super(["script", "exists", ...hashes], {
8
- deserialize: (result) => {
9
- /**
10
- * This isn't very pretty but it does the job.
11
- * The user facing api is clean and will return a single `string` if they provided
12
- * a single script hash, and an array of strings of the same length when given an
13
- * array of hashes.
14
- */
15
- const parsed = result;
16
- return parsed.length === 1 ? parsed[0] : parsed;
17
- },
8
+ deserialize: (result) => result,
18
9
  ...opts,
19
10
  });
20
11
  }
@@ -0,0 +1,81 @@
1
+ // deno-lint-ignore-file
2
+ import * as core from "../pkg/redis.js";
3
+ import { UpstashError } from "../pkg/error.js";
4
+ import "isomorphic-fetch";
5
+ /**
6
+ * Serverless redis client for upstash.
7
+ */
8
+ export class Redis extends core.Redis {
9
+ constructor(configOrRequester) {
10
+ if ("request" in configOrRequester) {
11
+ super(configOrRequester);
12
+ return;
13
+ }
14
+ if (configOrRequester.url.startsWith(" ") ||
15
+ configOrRequester.url.endsWith(" ") ||
16
+ /\r|\n/.test(configOrRequester.url)) {
17
+ console.warn("The redis url contains whitespace or newline, which can cause errors!");
18
+ }
19
+ if (configOrRequester.token.startsWith(" ") ||
20
+ configOrRequester.token.endsWith(" ") ||
21
+ /\r|\n/.test(configOrRequester.token)) {
22
+ console.warn("The redis token contains whitespace or newline, which can cause errors!");
23
+ }
24
+ const client = defaultRequester({
25
+ baseUrl: configOrRequester.url,
26
+ headers: { authorization: `Bearer ${configOrRequester.token}` },
27
+ // agent: configOrRequester.agent,
28
+ });
29
+ super(client, {
30
+ automaticDeserialization: configOrRequester.automaticDeserialization,
31
+ });
32
+ }
33
+ /**
34
+ * Create a new Upstash Redis instance from environment variables.
35
+ *
36
+ * Use this to automatically load connection secrets from your environment
37
+ * variables. For instance when using the Vercel integration.
38
+ *
39
+ * This tries to load `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN` from
40
+ * your environment using `process.env`.
41
+ */
42
+ static fromEnv(config) {
43
+ // @ts-ignore process will be defined in node
44
+ if (typeof process?.env === "undefined") {
45
+ throw new Error('Unable to get environment variables, `process.env` is undefined. If you are deploying to cloudflare, please import from "@upstash/redis/cloudflare" instead');
46
+ }
47
+ // @ts-ignore process will be defined in node
48
+ const url = process?.env["UPSTASH_REDIS_REST_URL"];
49
+ if (!url) {
50
+ throw new Error("Unable to find environment variable: `UPSTASH_REDIS_REST_URL`");
51
+ }
52
+ // @ts-ignore process will be defined in node
53
+ const token = process?.env["UPSTASH_REDIS_REST_TOKEN"];
54
+ if (!token) {
55
+ throw new Error("Unable to find environment variable: `UPSTASH_REDIS_REST_TOKEN`");
56
+ }
57
+ return new Redis({ url, token, ...config });
58
+ }
59
+ }
60
+ function defaultRequester(config) {
61
+ return {
62
+ request: async function (req) {
63
+ if (!req.path) {
64
+ req.path = [];
65
+ }
66
+ const res = await fetch([config.baseUrl, ...req.path].join("/"), {
67
+ method: "POST",
68
+ headers: { "Content-Type": "application/json", ...config.headers },
69
+ body: JSON.stringify(req.body),
70
+ keepalive: true,
71
+ // @ts-ignore
72
+ agent: config.agent,
73
+ });
74
+ const body = (await res.json());
75
+ if (!res.ok) {
76
+ throw new UpstashError(body.error);
77
+ }
78
+ return body;
79
+ },
80
+ };
81
+ }
package/package.json CHANGED
@@ -3,6 +3,7 @@
3
3
  "main": "./script/platforms/nodejs.js",
4
4
  "types": "./types/platforms/nodejs.d.ts",
5
5
  "name": "@upstash/redis",
6
+ "version": "v1.5.0",
6
7
  "description": "An HTTP/REST based Redis client built on top of Upstash REST API.",
7
8
  "repository": {
8
9
  "type": "git",
@@ -15,21 +16,27 @@
15
16
  "edge",
16
17
  "upstash"
17
18
  ],
18
- "author": "Andreas Thomas <andreas.thomas@chronark.com>",
19
+ "author": "Andreas Thomas <dev@chronark.com>",
19
20
  "license": "MIT",
20
21
  "bugs": {
21
22
  "url": "https://github.com/upstash/upstash-redis/issues"
22
23
  },
23
24
  "homepage": "https://github.com/upstash/upstash-redis#readme",
24
- "browser": {
25
- "isomorphic-fetch": false,
26
- "http": false,
27
- "https": false
28
- },
29
25
  "devDependencies": {
30
26
  "@size-limit/preset-small-lib": "latest",
31
27
  "size-limit": "latest"
32
28
  },
29
+ "dependencies": {
30
+ "isomorphic-fetch": "^3.0.0"
31
+ },
32
+ "typesVersions": {
33
+ "*": {
34
+ "nodejs": "./types/platforms/nodejs.d.ts",
35
+ "cloudflare": "./types/platforms/cloudflare.d.ts",
36
+ "fastly": "./types/platforms/fastly.d.ts",
37
+ "with-fetch": "./types/platforms/node_with_fetch.d.ts"
38
+ }
39
+ },
33
40
  "size-limit": [
34
41
  {
35
42
  "path": "esm/platforms/nodejs.js",
@@ -43,6 +50,10 @@
43
50
  "path": "esm/platforms/cloudflare.js",
44
51
  "limit": "5 KB"
45
52
  },
53
+ {
54
+ "path": "esm/platforms/node_with_fetch.js",
55
+ "limit": "15 KB"
56
+ },
46
57
  {
47
58
  "path": "script/platforms/nodejs.js",
48
59
  "limit": "10 KB"
@@ -54,6 +65,10 @@
54
65
  {
55
66
  "path": "script/platforms/cloudflare.js",
56
67
  "limit": "10 KB"
68
+ },
69
+ {
70
+ "path": "script/platforms/node_with_fetch.js",
71
+ "limit": "15 KB"
57
72
  }
58
73
  ],
59
74
  "exports": {
@@ -76,7 +91,11 @@
76
91
  "import": "./esm/platforms/fastly.js",
77
92
  "require": "./script/platforms/fastly.js",
78
93
  "types": "./types/platforms/fastly.d.ts"
94
+ },
95
+ "./with-fetch": {
96
+ "import": "./esm/platforms/node_with_fetch.js",
97
+ "require": "./script/platforms/node_with_fetch.js",
98
+ "types": "./types/platforms/node_with_fetch.d.ts"
79
99
  }
80
- },
81
- "version": "1.4.0-next.1"
100
+ }
82
101
  }
@@ -8,16 +8,7 @@ const command_js_1 = require("./command.js");
8
8
  class ScriptExistsCommand extends command_js_1.Command {
9
9
  constructor(hashes, opts) {
10
10
  super(["script", "exists", ...hashes], {
11
- deserialize: (result) => {
12
- /**
13
- * This isn't very pretty but it does the job.
14
- * The user facing api is clean and will return a single `string` if they provided
15
- * a single script hash, and an array of strings of the same length when given an
16
- * array of hashes.
17
- */
18
- const parsed = result;
19
- return parsed.length === 1 ? parsed[0] : parsed;
20
- },
11
+ deserialize: (result) => result,
21
12
  ...opts,
22
13
  });
23
14
  }
@@ -0,0 +1,108 @@
1
+ "use strict";
2
+ // deno-lint-ignore-file
3
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
4
+ if (k2 === undefined) k2 = k;
5
+ var desc = Object.getOwnPropertyDescriptor(m, k);
6
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
7
+ desc = { enumerable: true, get: function() { return m[k]; } };
8
+ }
9
+ Object.defineProperty(o, k2, desc);
10
+ }) : (function(o, m, k, k2) {
11
+ if (k2 === undefined) k2 = k;
12
+ o[k2] = m[k];
13
+ }));
14
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
15
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
16
+ }) : function(o, v) {
17
+ o["default"] = v;
18
+ });
19
+ var __importStar = (this && this.__importStar) || function (mod) {
20
+ if (mod && mod.__esModule) return mod;
21
+ var result = {};
22
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
23
+ __setModuleDefault(result, mod);
24
+ return result;
25
+ };
26
+ Object.defineProperty(exports, "__esModule", { value: true });
27
+ exports.Redis = void 0;
28
+ const core = __importStar(require("../pkg/redis.js"));
29
+ const error_js_1 = require("../pkg/error.js");
30
+ require("isomorphic-fetch");
31
+ /**
32
+ * Serverless redis client for upstash.
33
+ */
34
+ class Redis extends core.Redis {
35
+ constructor(configOrRequester) {
36
+ if ("request" in configOrRequester) {
37
+ super(configOrRequester);
38
+ return;
39
+ }
40
+ if (configOrRequester.url.startsWith(" ") ||
41
+ configOrRequester.url.endsWith(" ") ||
42
+ /\r|\n/.test(configOrRequester.url)) {
43
+ console.warn("The redis url contains whitespace or newline, which can cause errors!");
44
+ }
45
+ if (configOrRequester.token.startsWith(" ") ||
46
+ configOrRequester.token.endsWith(" ") ||
47
+ /\r|\n/.test(configOrRequester.token)) {
48
+ console.warn("The redis token contains whitespace or newline, which can cause errors!");
49
+ }
50
+ const client = defaultRequester({
51
+ baseUrl: configOrRequester.url,
52
+ headers: { authorization: `Bearer ${configOrRequester.token}` },
53
+ // agent: configOrRequester.agent,
54
+ });
55
+ super(client, {
56
+ automaticDeserialization: configOrRequester.automaticDeserialization,
57
+ });
58
+ }
59
+ /**
60
+ * Create a new Upstash Redis instance from environment variables.
61
+ *
62
+ * Use this to automatically load connection secrets from your environment
63
+ * variables. For instance when using the Vercel integration.
64
+ *
65
+ * This tries to load `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN` from
66
+ * your environment using `process.env`.
67
+ */
68
+ static fromEnv(config) {
69
+ // @ts-ignore process will be defined in node
70
+ if (typeof process?.env === "undefined") {
71
+ throw new Error('Unable to get environment variables, `process.env` is undefined. If you are deploying to cloudflare, please import from "@upstash/redis/cloudflare" instead');
72
+ }
73
+ // @ts-ignore process will be defined in node
74
+ const url = process?.env["UPSTASH_REDIS_REST_URL"];
75
+ if (!url) {
76
+ throw new Error("Unable to find environment variable: `UPSTASH_REDIS_REST_URL`");
77
+ }
78
+ // @ts-ignore process will be defined in node
79
+ const token = process?.env["UPSTASH_REDIS_REST_TOKEN"];
80
+ if (!token) {
81
+ throw new Error("Unable to find environment variable: `UPSTASH_REDIS_REST_TOKEN`");
82
+ }
83
+ return new Redis({ url, token, ...config });
84
+ }
85
+ }
86
+ exports.Redis = Redis;
87
+ function defaultRequester(config) {
88
+ return {
89
+ request: async function (req) {
90
+ if (!req.path) {
91
+ req.path = [];
92
+ }
93
+ const res = await fetch([config.baseUrl, ...req.path].join("/"), {
94
+ method: "POST",
95
+ headers: { "Content-Type": "application/json", ...config.headers },
96
+ body: JSON.stringify(req.body),
97
+ keepalive: true,
98
+ // @ts-ignore
99
+ agent: config.agent,
100
+ });
101
+ const body = (await res.json());
102
+ if (!res.ok) {
103
+ throw new error_js_1.UpstashError(body.error);
104
+ }
105
+ return body;
106
+ },
107
+ };
108
+ }
@@ -2,8 +2,8 @@ import { Command, CommandOptions } from "./command.js";
2
2
  /**
3
3
  * @see https://redis.io/commands/hmset
4
4
  */
5
- export declare class HMSetCommand<TData> extends Command<number, number> {
5
+ export declare class HMSetCommand<TData> extends Command<"OK", "OK"> {
6
6
  constructor([key, kv]: [key: string, kv: {
7
7
  [field: string]: TData;
8
- }], opts?: CommandOptions<number, number>);
8
+ }], opts?: CommandOptions<"OK", "OK">);
9
9
  }
@@ -1,9 +1,7 @@
1
1
  import { Command, CommandOptions } from "./command.js";
2
- declare type TupleOfLength<T, L extends number, R extends T[] = []> = R["length"] extends L ? R : TupleOfLength<T, L, [...R, T]>;
3
2
  /**
4
3
  * @see https://redis.io/commands/script-exists
5
4
  */
6
- export declare class ScriptExistsCommand<T extends [string, ...string[]]> extends Command<T extends [string] ? string : TupleOfLength<string, T["length"]>, TupleOfLength<string, T["length"]>> {
7
- constructor(hashes: T, opts?: CommandOptions<T extends [string] ? string : TupleOfLength<string, T["length"]>, TupleOfLength<string, T["length"]>>);
5
+ export declare class ScriptExistsCommand<T extends string[]> extends Command<string[], number[]> {
6
+ constructor(hashes: T, opts?: CommandOptions<string[], number[]>);
8
7
  }
9
- export {};
@@ -2,6 +2,6 @@ import { Command, CommandOptions } from "./command.js";
2
2
  /**
3
3
  * @see https://redis.io/commands/sinterstore
4
4
  */
5
- export declare class SInterStoreCommand<TData = string> extends Command<unknown[], TData[]> {
6
- constructor(cmd: [destination: string, key: string, ...keys: string[]], opts?: CommandOptions<unknown[], TData[]>);
5
+ export declare class SInterStoreCommand extends Command<number, number> {
6
+ constructor(cmd: [destination: string, key: string, ...keys: string[]], opts?: CommandOptions<number, number>);
7
7
  }
@@ -2,6 +2,6 @@ import { Command, CommandOptions } from "./command.js";
2
2
  /**
3
3
  * @see https://redis.io/commands/spop
4
4
  */
5
- export declare class SPopCommand<TData = number> extends Command<string | null, TData | null> {
5
+ export declare class SPopCommand<TData> extends Command<string | null, TData | null> {
6
6
  constructor([key, count]: [key: string, count?: number], opts?: CommandOptions<string | null, TData | null>);
7
7
  }
@@ -1,4 +1,4 @@
1
- import { DelCommand, ExistsCommand, FlushAllCommand, PingCommand, ScoreMember, SetCommandOptions, TouchCommand, UnlinkCommand, ZAddCommandOptions, ZAddCommandOptionsWithIncr, ZRangeCommandOptions } from "./commands/mod.js";
1
+ import { DelCommand, ExistsCommand, FlushAllCommand, PingCommand, ScoreMember, ScriptExistsCommand, SetCommandOptions, TouchCommand, UnlinkCommand, ZAddCommandOptions, ZAddCommandOptionsWithIncr, ZRangeCommandOptions } from "./commands/mod.js";
2
2
  import { CommandOptions } from "./commands/command.js";
3
3
  import { Requester } from "./http.js";
4
4
  import { CommandArgs } from "./types.js";
@@ -349,7 +349,7 @@ export declare class Pipeline {
349
349
  /**
350
350
  * @see https://redis.io/commands/script-exists
351
351
  */
352
- scriptExists: (args_0: string, ...args_1: string[]) => this;
352
+ scriptExists: (...args: CommandArgs<typeof ScriptExistsCommand>) => this;
353
353
  /**
354
354
  * @see https://redis.io/commands/script-flush
355
355
  */
@@ -1,4 +1,4 @@
1
- import { CommandOptions, DelCommand, ExistsCommand, FlushAllCommand, PingCommand, ScoreMember, SetCommandOptions, TouchCommand, UnlinkCommand, ZAddCommandOptions, ZAddCommandOptionsWithIncr, ZRangeCommandOptions } from "./commands/mod.js";
1
+ import { CommandOptions, DelCommand, ExistsCommand, FlushAllCommand, PingCommand, ScoreMember, ScriptExistsCommand, SetCommandOptions, TouchCommand, UnlinkCommand, ZAddCommandOptions, ZAddCommandOptionsWithIncr, ZRangeCommandOptions } from "./commands/mod.js";
2
2
  import { Requester } from "./http.js";
3
3
  import { Pipeline } from "./pipeline.js";
4
4
  import type { CommandArgs } from "./types.js";
@@ -160,7 +160,7 @@ export declare class Redis {
160
160
  */
161
161
  hmset: <TData>(key: string, kv: {
162
162
  [field: string]: TData;
163
- }) => Promise<number>;
163
+ }) => Promise<"OK">;
164
164
  /**
165
165
  * @see https://redis.io/commands/hscan
166
166
  */
@@ -322,7 +322,7 @@ export declare class Redis {
322
322
  /**
323
323
  * @see https://redis.io/commands/script-exists
324
324
  */
325
- scriptExists: (args_0: string, ...args_1: string[]) => Promise<[]>;
325
+ scriptExists: (...args: CommandArgs<typeof ScriptExistsCommand>) => Promise<number[]>;
326
326
  /**
327
327
  * @see https://redis.io/commands/script-flush
328
328
  */
@@ -366,7 +366,7 @@ export declare class Redis {
366
366
  /**
367
367
  * @see https://redis.io/commands/sinterstore
368
368
  */
369
- sinterstore: (destination: string, key: string, ...keys: string[]) => Promise<string[]>;
369
+ sinterstore: (destination: string, key: string, ...keys: string[]) => Promise<number>;
370
370
  /**
371
371
  * @see https://redis.io/commands/sismember
372
372
  */
@@ -0,0 +1,63 @@
1
+ import * as core from "../pkg/redis.js";
2
+ import { Requester, UpstashRequest, UpstashResponse } from "../pkg/http.js";
3
+ import "isomorphic-fetch";
4
+ export type { Requester, UpstashRequest, UpstashResponse };
5
+ /**
6
+ * Connection credentials for upstash redis.
7
+ * Get them from https://console.upstash.com/redis/<uuid>
8
+ */
9
+ export declare type RedisConfigNodejs = {
10
+ /**
11
+ * UPSTASH_REDIS_REST_URL
12
+ */
13
+ url: string;
14
+ /**
15
+ * UPSTASH_REDIS_REST_TOKEN
16
+ */
17
+ token: string;
18
+ } & core.RedisOptions;
19
+ /**
20
+ * Serverless redis client for upstash.
21
+ */
22
+ export declare class Redis extends core.Redis {
23
+ /**
24
+ * Create a new redis client by providing the url and token
25
+ *
26
+ * @example
27
+ * ```typescript
28
+ * const redis = new Redis({
29
+ * url: "<UPSTASH_REDIS_REST_URL>",
30
+ * token: "<UPSTASH_REDIS_REST_TOKEN>",
31
+ * });
32
+ * ```
33
+ */
34
+ constructor(config: RedisConfigNodejs);
35
+ /**
36
+ * Create a new redis client by providing a custom `Requester` implementation
37
+ *
38
+ * @example
39
+ * ```ts
40
+ *
41
+ * import { UpstashRequest, Requester, UpstashResponse, Redis } from "@upstash/redis"
42
+ *
43
+ * const requester: Requester = {
44
+ * request: <TResult>(req: UpstashRequest): Promise<UpstashResponse<TResult>> => {
45
+ * // ...
46
+ * }
47
+ * }
48
+ *
49
+ * const redis = new Redis(requester)
50
+ * ```
51
+ */
52
+ constructor(requesters: Requester);
53
+ /**
54
+ * Create a new Upstash Redis instance from environment variables.
55
+ *
56
+ * Use this to automatically load connection secrets from your environment
57
+ * variables. For instance when using the Vercel integration.
58
+ *
59
+ * This tries to load `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN` from
60
+ * your environment using `process.env`.
61
+ */
62
+ static fromEnv(config?: Omit<RedisConfigNodejs, "url" | "token">): Redis;
63
+ }