@valkey/valkey-glide
Version:
General Language Independent Driver for the Enterprise (GLIDE) for Valkey
852 lines (851 loc) • 35.6 kB
JavaScript
"use strict";
/**
* Copyright Valkey GLIDE Project Contributors - SPDX Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.GlideClient = exports.GlideClientConfiguration = void 0;
const BaseClient_1 = require("./BaseClient");
const Commands_1 = require("./Commands");
/* eslint-disable-next-line @typescript-eslint/no-namespace */
var GlideClientConfiguration;
(function (GlideClientConfiguration) {
/**
* Enum representing pubsub subscription modes.
* @see {@link https://valkey.io/docs/topics/pubsub/|Valkey PubSub Documentation} for more details.
*/
let PubSubChannelModes;
(function (PubSubChannelModes) {
/**
* Use exact channel names.
*/
PubSubChannelModes[PubSubChannelModes["Exact"] = 0] = "Exact";
/**
* Use channel name patterns.
*/
PubSubChannelModes[PubSubChannelModes["Pattern"] = 1] = "Pattern";
})(PubSubChannelModes = GlideClientConfiguration.PubSubChannelModes || (GlideClientConfiguration.PubSubChannelModes = {}));
})(GlideClientConfiguration || (exports.GlideClientConfiguration = GlideClientConfiguration = {}));
/**
* Client used for connection to standalone servers.
* Use {@link createClient} to request a client.
*
* @see For full documentation refer to {@link https://glide.valkey.io/how-to/client-initialization/#standalone | Valkey GLIDE Documentation}.
*/
class GlideClient extends BaseClient_1.BaseClient {
/**
* @internal
*/
createClientRequest(options) {
const configuration = super.createClientRequest(options);
this.configurePubsub(options, configuration);
if (options.advancedConfiguration) {
this.configureAdvancedConfigurationBase(options.advancedConfiguration, configuration);
}
// Set read-only mode if specified
if (options.readOnly !== undefined) {
configuration.readOnly = options.readOnly;
}
if (options.nodeDiscoveryMode !== undefined) {
configuration.nodeDiscoveryMode =
options.nodeDiscoveryMode;
}
return configuration;
}
/**
* Creates a new `GlideClient` instance and establishes a connection to a standalone Valkey server.
*
* @param options - The configuration options for the client, including server addresses, authentication credentials, TLS settings, database selection, reconnection strategy, and Pub/Sub subscriptions.
* @returns A promise that resolves to a connected `GlideClient` instance.
*
* @remarks
* Use this static method to create and connect a `GlideClient` to a standalone Valkey server.
* The client will automatically handle connection establishment, including any authentication and TLS configurations.
*
* @example
* ```typescript
* // Connecting to a Standalone Server
* import { GlideClient, GlideClientConfiguration } from '@valkey/valkey-glide';
*
* const client = await GlideClient.createClient({
* addresses: [
* { host: 'primary.example.com', port: 6379 },
* { host: 'replica1.example.com', port: 6379 },
* ],
* databaseId: 1,
* credentials: {
* username: 'user1',
* password: 'passwordA',
* },
* useTLS: true,
* connectionBackoff: {
* numberOfRetries: 5,
* factor: 1000,
* exponentBase: 2,
* jitter: 20,
* },
* pubsubSubscriptions: {
* channelsAndPatterns: {
* [GlideClientConfiguration.PubSubChannelModes.Exact]: new Set(['updates']),
* },
* callback: (msg) => {
* console.log(`Received message: ${msg.payload}`);
* },
* },
* });
* ```
*
* @remarks
* - **Authentication**: If `credentials` are provided, the client will attempt to authenticate using the specified username and password.
* - **TLS**: If `useTLS` is set to `true`, the client will establish a secure connection using TLS.
* Should match the TLS configuration of the server/cluster, otherwise the connection attempt will fail.
* For advanced tls configuration, please use the {@link AdvancedGlideClientConfiguration} option.
* - **Reconnection Strategy**: The `connectionBackoff` settings define how the client will attempt to reconnect in case of disconnections.
* - **Pub/Sub Subscriptions**: Any channels or patterns specified in `pubsubSubscriptions` will be subscribed to upon connection.
*/
static async createClient(options) {
return super.createClientInternal(options, (socket, options) => new GlideClient(socket, options));
}
/**
* @internal
*/
static async __createClient(options, connectedSocket) {
return this.__createClientInternal(options, connectedSocket, (socket, options) => new GlideClient(socket, options));
}
/**
* Execute a batch by processing the queued commands.
*
* **Notes:**
* - **Atomic Batches - Transactions:** If the transaction fails due to a `WATCH` command, `EXEC` will return `null`.
*
* @see {@link https://github.com/valkey-io/valkey-glide/wiki/NodeJS-wrapper#transaction|Valkey GLIDE Documentation} for details on Valkey Transactions.
*
* @param batch - A {@link Batch} object containing a list of commands to be executed.
* @param raiseOnError - Determines how errors are handled within the batch response.
* - If `true`, the first the first encountered error in the batch will be raised as an exception of type {@link RequestError}
* after all retries and reconnections have been exhausted.
* - If `false`, errors will be included as part of the batch response, allowing the caller to process both successful and failed commands together.
* In this case, error details will be provided as instances of {@link RequestError} in the response list.
* @param options - (Optional) See {@link BatchOptions} and {@link DecoderOption}.
* @returns A list of results corresponding to the execution of each command in the transaction.
* If a command returns a value, it will be included in the list. If a command doesn't return a value,
* the list entry will be `null`.
* If the transaction failed due to a `WATCH` command, `exec` will return `null`.
*
* @see {@link https://valkey.io/docs/topics/transactions/|Valkey Transactions (Atomic Batches)} for details.
* @see {@link https://valkey.io/docs/topics/pipelining/|Valkey Pipelines (Non-Atomic Batches)} for details.
*
* @example
* ```typescript
* // Example 1: Atomic Batch (Transaction) with Options
* const transaction = new Batch(true) // Atomic (Transactional)
* .set("key", "value")
* .get("key");
*
* const result = await client.exec(transaction, false, {timeout: 1000}); // Execute the transaction with raiseOnError = false and a timeout of 1000ms
* console.log(result); // Output: ['OK', 'value']
* ```
*
* @example
* ```typescript
* // Example 2: Non-Atomic Batch (Pipelining) with Options
* const pipeline = new Batch(false) // Non-Atomic (Pipelining)
* .set("key1", "value1")
* .set("key2", "value2")
* .get("key1")
* .get("key2");
*
* const result = await client.exec(pipeline, false, {timeout: 1000}); // Execute the pipeline with raiseOnError = false and a timeout of 1000ms
* console.log(result); // Output: ['OK', 'OK', 'value1', 'value2']
* ```
*/
async exec(batch, raiseOnError, options) {
return this.createWritePromise(batch.commands, options, batch.isAtomic, raiseOnError).then((result) => this.processResultWithSetCommands(result, batch.setCommandsIndexes));
}
/** Executes a single command, without checking inputs. Every part of the command, including subcommands,
* should be added as a separate value in args.
*
* Note: An error will occur if the string decoder is used with commands that return only bytes as a response.
*
* @see {@link https://glide.valkey.io/concepts/client-features/custom-commands/|Valkey GLIDE Documentation} for details on the restrictions and limitations of the custom command API.
*
* @param args - A list including the command name and arguments for the custom command.
* @param options - (Optional) See {@link DecoderOption}.
* @returns The executed custom command return value.
*
* @example
* ```typescript
* // Example usage of customCommand method to retrieve pub/sub clients
* const result = await client.customCommand(["CLIENT", "LIST", "TYPE", "PUBSUB"]);
* console.log(result); // Output: Returns a list of all pub/sub clients
* ```
*/
async customCommand(args, options) {
return this.createWritePromise((0, Commands_1.createCustomCommand)(args), options);
}
/**
* Pings the server.
*
* @see {@link https://valkey.io/commands/ping/|valkey.io} for details.
*
* @param options - (Optional) Additional parameters:
* - (Optional) `message` : a message to include in the `PING` command.
* + If not provided, the server will respond with `"PONG"`.
* + If provided, the server will respond with a copy of the message.
* - (Optional) `decoder`: see {@link DecoderOption}.
* @returns `"PONG"` if `message` is not provided, otherwise return a copy of `message`.
*
* @example
* ```typescript
* // Example usage of ping method without any message
* const result = await client.ping();
* console.log(result); // Output: 'PONG'
* ```
*
* @example
* ```typescript
* // Example usage of ping method with a message
* const result = await client.ping("Hello");
* console.log(result); // Output: 'Hello'
* ```
*/
async ping(options) {
return this.createWritePromise((0, Commands_1.createPing)(options?.message), options);
}
/**
* Gets information and statistics about the server.
*
* Starting from server version 7, command supports multiple section arguments.
*
* @see {@link https://valkey.io/commands/info/|valkey.io} for details.
*
* @param sections - (Optional) A list of {@link InfoOptions} values specifying which sections of information to retrieve.
* When no parameter is provided, {@link InfoOptions.Default|Default} is assumed.
* @returns A string containing the information for the sections requested.
*
* @example
* ```typescript
* // Example usage of the info method with retrieving total_net_input_bytes from the result
* const result = await client.info(new Section[] { Section.STATS });
* console.log(someParsingFunction(result, "total_net_input_bytes")); // Output: 1
* ```
*/
async info(sections) {
return this.createWritePromise((0, Commands_1.createInfo)(sections), {
decoder: BaseClient_1.Decoder.String,
});
}
/**
* Gets the name of the primary's connection.
*
* @see {@link https://valkey.io/commands/client-getname/|valkey.io} for more details.
*
* @param options - (Optional) See {@link DecoderOption}.
* @returns The name of the client connection as a string if a name is set, or `null` if no name is assigned.
*
* @example
* ```typescript
* // Example usage of client_getname method
* const result = await client.client_getname();
* console.log(result); // Output: 'Client Name'
* ```
*/
async clientGetName(options) {
return this.createWritePromise((0, Commands_1.createClientGetName)(), options);
}
/**
* Rewrites the configuration file with the current configuration.
*
* @see {@link https://valkey.io/commands/config-rewrite/|valkey.io} for details.
*
* @returns "OK" when the configuration was rewritten properly. Otherwise, an error is thrown.
*
* @example
* ```typescript
* // Example usage of configRewrite command
* const result = await client.configRewrite();
* console.log(result); // Output: 'OK'
* ```
*/
async configRewrite() {
return this.createWritePromise((0, Commands_1.createConfigRewrite)(), {
decoder: BaseClient_1.Decoder.String,
});
}
/**
* Resets the statistics reported by the server using the `INFO` and `LATENCY HISTOGRAM` commands.
*
* @see {@link https://valkey.io/commands/config-resetstat/|valkey.io} for details.
*
* @returns always "OK".
*
* @example
* ```typescript
* // Example usage of configResetStat command
* const result = await client.configResetStat();
* console.log(result); // Output: 'OK'
* ```
*/
async configResetStat() {
return this.createWritePromise((0, Commands_1.createConfigResetStat)(), {
decoder: BaseClient_1.Decoder.String,
});
}
/**
* Returns the current connection ID.
*
* @see {@link https://valkey.io/commands/client-id/|valkey.io} for details.
*
* @returns The ID of the connection.
*
* @example
* ```typescript
* const result = await client.clientId();
* console.log("Connection id: " + result);
* ```
*/
async clientId() {
return this.createWritePromise((0, Commands_1.createClientId)());
}
/**
* Reads the configuration parameters of the running server.
* Starting from server version 7, command supports multiple parameters.
*
* @see {@link https://valkey.io/commands/config-get/|valkey.io} for details.
*
* @param parameters - A list of configuration parameter names to retrieve values for.
* @param options - (Optional) See {@link DecoderOption}.
*
* @returns A map of values corresponding to the configuration parameters.
*
* @example
* ```typescript
* // Example usage of configGet method with multiple configuration parameters
* const result = await client.configGet(["timeout", "maxmemory"]);
* console.log(result); // Output: {'timeout': '1000', 'maxmemory': '1GB'}
* ```
*/
async configGet(parameters, options) {
return this.createWritePromise((0, Commands_1.createConfigGet)(parameters), options).then(BaseClient_1.convertGlideRecordToRecord);
}
/**
* Sets configuration parameters to the specified values.
* Starting from server version 7, command supports multiple parameters.
*
* @see {@link https://valkey.io/commands/config-set/|valkey.io} for details.
* @param parameters - A map consisting of configuration parameters and their respective values to set.
* @returns `"OK"` when the configuration was set properly. Otherwise an error is thrown.
*
* @example
* ```typescript
* // Example usage of configSet method to set multiple configuration parameters
* const result = await client.configSet({ timeout: "1000", maxmemory, "1GB" });
* console.log(result); // Output: 'OK'
* ```
*/
async configSet(parameters) {
return this.createWritePromise((0, Commands_1.createConfigSet)(parameters), {
decoder: BaseClient_1.Decoder.String,
});
}
/**
* Echoes the provided `message` back.
*
* @see {@link https://valkey.io/commands/echo|valkey.io} for more details.
*
* @param message - The message to be echoed back.
* @param options - (Optional) See {@link DecoderOption}.
* @returns The provided `message`.
*
* @example
* ```typescript
* // Example usage of the echo command
* const echoedMessage = await client.echo("valkey-glide");
* console.log(echoedMessage); // Output: 'valkey-glide'
* ```
*/
async echo(message, options) {
return this.createWritePromise((0, Commands_1.createEcho)(message), options);
}
/**
* Returns the server time.
*
* @see {@link https://valkey.io/commands/time/|valkey.io} for details.
*
* @returns The current server time as an `array` with two items:
* - A Unix timestamp,
* - The amount of microseconds already elapsed in the current second.
*
* @example
* ```typescript
* console.log(await client.time()); // Output: ['1710925775', '913580']
* ```
*/
async time() {
return this.createWritePromise((0, Commands_1.createTime)(), {
decoder: BaseClient_1.Decoder.String,
});
}
/**
* Displays a piece of generative computer art and the server version.
*
* @see {@link https://valkey.io/commands/lolwut/|valkey.io} for more details.
*
* @param options - (Optional) The LOLWUT options - see {@link LolwutOptions}.
* @returns A piece of generative computer art along with the current server version.
*
* @example
* ```typescript
* const response = await client.lolwut({ version: 6, parameters: [40, 20] });
* console.log(response); // Output: "Valkey ver. 7.2.3" - Indicates the current server version.
* ```
*/
async lolwut(options) {
return this.createWritePromise((0, Commands_1.createLolwut)(options), {
decoder: BaseClient_1.Decoder.String,
});
}
/**
* Deletes a library and all its functions.
*
* @see {@link https://valkey.io/commands/function-delete/|valkey.io} for details.
* @remarks Since Valkey version 7.0.0.
*
* @param libraryCode - The library name to delete.
* @returns A simple `"OK"` response.
*
* @example
* ```typescript
* const result = await client.functionDelete("libName");
* console.log(result); // Output: 'OK'
* ```
*/
async functionDelete(libraryCode) {
return this.createWritePromise((0, Commands_1.createFunctionDelete)(libraryCode), {
decoder: BaseClient_1.Decoder.String,
});
}
/**
* Loads a library to Valkey.
*
* @see {@link https://valkey.io/commands/function-load/|valkey.io} for details.
* @remarks Since Valkey version 7.0.0.
*
* @param libraryCode - The source code that implements the library.
* @param options - (Optional) Additional parameters:
* - (Optional) `replace`: Whether the given library should overwrite a library with the same name if it
* already exists.
* - (Optional) `decoder`: see {@link DecoderOption}.
* @returns The library name that was loaded.
*
* @example
* ```typescript
* const code = "#!lua name=mylib \n redis.register_function('myfunc', function(keys, args) return args[1] end)";
* const result = await client.functionLoad(code, { replace: true });
* console.log(result); // Output: 'mylib'
* ```
*/
async functionLoad(libraryCode, options) {
return this.createWritePromise((0, Commands_1.createFunctionLoad)(libraryCode, options?.replace), options);
}
/**
* Deletes all function libraries.
*
* @see {@link https://valkey.io/commands/function-flush/|valkey.io} for details.
* @remarks Since Valkey version 7.0.0.
*
* @param mode - (Optional) The flushing mode, could be either {@link FlushMode.SYNC} or {@link FlushMode.ASYNC}.
* @returns A simple `"OK"` response.
*
* @example
* ```typescript
* const result = await client.functionFlush(FlushMode.SYNC);
* console.log(result); // Output: 'OK'
* ```
*/
async functionFlush(mode) {
return this.createWritePromise((0, Commands_1.createFunctionFlush)(mode), {
decoder: BaseClient_1.Decoder.String,
});
}
/**
* Returns information about the functions and libraries.
*
* @see {@link https://valkey.io/commands/function-list/|valkey.io} for details.
* @remarks Since Valkey version 7.0.0.
*
* @param options - (Optional) See {@link FunctionListOptions} and {@link DecoderOption}.
* @returns Info about all or selected libraries and their functions in {@link FunctionListResponse} format.
*
* @example
* ```typescript
* // Request info for specific library including the source code
* const result1 = await client.functionList({ libNamePattern: "myLib*", withCode: true });
* // Request info for all libraries
* const result2 = await client.functionList();
* console.log(result2); // Output:
* // [{
* // "library_name": "myLib5_backup",
* // "engine": "LUA",
* // "functions": [{
* // "name": "myfunc",
* // "description": null,
* // "flags": [ "no-writes" ],
* // }],
* // "library_code": "#!lua name=myLib5_backup \n redis.register_function('myfunc', function(keys, args) return args[1] end)"
* // }]
* ```
*/
async functionList(options) {
return this.createWritePromise((0, Commands_1.createFunctionList)(options), options).then((res) => res.map(BaseClient_1.convertGlideRecordToRecord));
}
/**
* Returns information about the function that's currently running and information about the
* available execution engines.
*
* FUNCTION STATS runs on all nodes of the server, including primary and replicas.
* The response includes a mapping from node address to the command response for that node.
*
* @see {@link https://valkey.io/commands/function-stats/|valkey.io} for details.
* @remarks Since Valkey version 7.0.0.
*
* @param options - (Optional) See {@link DecoderOption}.
* @returns A Record where the key is the node address and the value is a Record with two keys:
* - `"running_script"`: Information about the running script, or `null` if no script is running.
* - `"engines"`: Information about available engines and their stats.
* - see example for more details.
* @example
* ```typescript
* const response = await client.functionStats();
* console.log(response); // Example output:
* // {
* // "127.0.0.1:6379": { // Response from the primary node
* // "running_script": {
* // "name": "foo",
* // "command": ["FCALL", "foo", "0", "hello"],
* // "duration_ms": 7758
* // },
* // "engines": {
* // "LUA": {
* // "libraries_count": 1,
* // "functions_count": 1
* // }
* // }
* // },
* // "127.0.0.1:6380": { // Response from a replica node
* // "running_script": null,
* // "engines": {
* // "LUA": {
* // "libraries_count": 1,
* // "functions_count": 1
* // }
* // }
* // }
* // }
* ```
*/
async functionStats(options) {
return this.createWritePromise((0, Commands_1.createFunctionStats)(), options).then((res) => (0, BaseClient_1.convertGlideRecordToRecord)(res));
}
/**
* Kills a function that is currently executing.
* `FUNCTION KILL` terminates read-only functions only.
* `FUNCTION KILL` runs on all nodes of the server, including primary and replicas.
*
* @see {@link https://valkey.io/commands/function-kill/|valkey.io} for details.
* @remarks Since Valkey version 7.0.0.
*
* @returns `"OK"` if function is terminated. Otherwise, throws an error.
* @example
* ```typescript
* await client.functionKill();
* ```
*/
async functionKill() {
return this.createWritePromise((0, Commands_1.createFunctionKill)(), {
decoder: BaseClient_1.Decoder.String,
});
}
/**
* Returns the serialized payload of all loaded libraries.
*
* @see {@link https://valkey.io/commands/function-dump/|valkey.io} for details.
* @remarks Since Valkey version 7.0.0.
*
* @returns The serialized payload of all loaded libraries.
*
* @example
* ```typescript
* const data = await client.functionDump();
* // data can be used to restore loaded functions on any Valkey instance
* ```
*/
async functionDump() {
return this.createWritePromise((0, Commands_1.createFunctionDump)(), {
decoder: BaseClient_1.Decoder.Bytes,
});
}
/**
* Restores libraries from the serialized payload returned by {@link functionDump}.
*
* @see {@link https://valkey.io/commands/function-restore/|valkey.io} for details.
* @remarks Since Valkey version 7.0.0.
*
* @param payload - The serialized data from {@link functionDump}.
* @param policy - (Optional) A policy for handling existing libraries, see {@link FunctionRestorePolicy}.
* {@link FunctionRestorePolicy.APPEND} is used by default.
* @returns `"OK"`.
*
* @example
* ```typescript
* await client.functionRestore(data, FunctionRestorePolicy.FLUSH);
* ```
*/
async functionRestore(payload, policy) {
return this.createWritePromise((0, Commands_1.createFunctionRestore)(payload, policy), {
decoder: BaseClient_1.Decoder.String,
});
}
/**
* Deletes all the keys of all the existing databases. This command never fails.
*
* @see {@link https://valkey.io/commands/flushall/|valkey.io} for more details.
*
* @param mode - (Optional) The flushing mode, could be either {@link FlushMode.SYNC} or {@link FlushMode.ASYNC}.
* @returns `"OK"`.
*
* @example
* ```typescript
* const result = await client.flushall(FlushMode.SYNC);
* console.log(result); // Output: 'OK'
* ```
*/
async flushall(mode) {
return this.createWritePromise((0, Commands_1.createFlushAll)(mode), {
decoder: BaseClient_1.Decoder.String,
});
}
/**
* Deletes all the keys of the currently selected database. This command never fails.
*
* @see {@link https://valkey.io/commands/flushdb/|valkey.io} for more details.
*
* @param mode - (Optional) The flushing mode, could be either {@link FlushMode.SYNC} or {@link FlushMode.ASYNC}.
* @returns `"OK"`.
*
* @example
* ```typescript
* const result = await client.flushdb(FlushMode.SYNC);
* console.log(result); // Output: 'OK'
* ```
*/
async flushdb(mode) {
return this.createWritePromise((0, Commands_1.createFlushDB)(mode), {
decoder: BaseClient_1.Decoder.String,
});
}
/**
* Returns the number of keys in the currently selected database.
*
* @see {@link https://valkey.io/commands/dbsize/|valkey.io} for more details.
*
* @returns The number of keys in the currently selected database.
*
* @example
* ```typescript
* const numKeys = await client.dbsize();
* console.log("Number of keys in the current database: ", numKeys);
* ```
*/
async dbsize() {
return this.createWritePromise((0, Commands_1.createDBSize)());
}
/** Publish a message on pubsub channel.
*
* @see {@link https://valkey.io/commands/publish/|valkey.io} for more details.
*
* @param message - Message to publish.
* @param channel - Channel to publish the message on.
* @returns - Number of subscriptions in primary node that received the message.
* Note that this value does not include subscriptions that configured on replicas.
*
* @example
* ```typescript
* // Example usage of publish command
* const result = await client.publish("Hi all!", "global-channel");
* console.log(result); // Output: 1 - This message was posted to 1 subscription which is configured on primary node
* ```
*/
async publish(message, channel) {
return this.createWritePromise((0, Commands_1.createPublish)(message, channel));
}
/**
* Returns `UNIX TIME` of the last DB save timestamp or startup timestamp if no save
* was made since then.
*
* @see {@link https://valkey.io/commands/lastsave/|valkey.io} for more details.
*
* @returns `UNIX TIME` of the last DB save executed with success.
*
* @example
* ```typescript
* const timestamp = await client.lastsave();
* console.log("Last DB save was done at " + timestamp);
* ```
*/
async lastsave() {
return this.createWritePromise((0, Commands_1.createLastSave)());
}
/**
* Returns a random existing key name from the currently selected database.
*
* @see {@link https://valkey.io/commands/randomkey/|valkey.io} for more details.
* @param options - (Optional) See {@link DecoderOption}.
* @returns A random existing key name from the currently selected database.
*
* @example
* ```typescript
* const result = await client.randomKey();
* console.log(result); // Output: "key12" - "key12" is a random existing key name from the currently selected database.
* ```
*/
async randomKey(options) {
return this.createWritePromise((0, Commands_1.createRandomKey)(), options);
}
/**
* Flushes all the previously watched keys for a transaction. Executing a transaction will
* automatically flush all previously watched keys.
*
* @see {@link https://valkey.io/commands/unwatch/|valkey.io} and {@link https://valkey.io/topics/transactions/#cas|Valkey GLIDE Documentation} for more details.
*
* @returns A simple `"OK"` response.
*
* @example
* ```typescript
* let response = await client.unwatch();
* console.log(response); // Output: "OK"
* ```
*/
async unwatch() {
return this.createWritePromise((0, Commands_1.createUnWatch)(), {
decoder: BaseClient_1.Decoder.String,
});
}
/**
* Checks existence of scripts in the script cache by their SHA1 digest.
*
* @see {@link https://valkey.io/commands/script-exists/|valkey.io} for more details.
*
* @param sha1s - List of SHA1 digests of the scripts to check.
* @returns A list of boolean values indicating the existence of each script.
*
* @example
* ```typescript
* console result = await client.scriptExists(["sha1_digest1", "sha1_digest2"]);
* console.log(result); // Output: [true, false]
* ```
*/
async scriptExists(sha1s) {
return this.createWritePromise((0, Commands_1.createScriptExists)(sha1s));
}
/**
* Flushes the Lua scripts cache.
*
* @see {@link https://valkey.io/commands/script-flush/|valkey.io} for more details.
*
* @param mode - (Optional) The flushing mode, could be either {@link FlushMode.SYNC} or {@link FlushMode.ASYNC}.
* @returns A simple `"OK"` response.
*
* @example
* ```typescript
* console result = await client.scriptFlush(FlushMode.SYNC);
* console.log(result); // Output: "OK"
* ```
*/
async scriptFlush(mode) {
return this.createWritePromise((0, Commands_1.createScriptFlush)(mode), {
decoder: BaseClient_1.Decoder.String,
});
}
/**
* Kills the currently executing Lua script, assuming no write operation was yet performed by the script.
*
* @see {@link https://valkey.io/commands/script-kill/|valkey.io} for more details.
*
* @returns A simple `"OK"` response.
*
* @example
* ```typescript
* console result = await client.scriptKill();
* console.log(result); // Output: "OK"
* ```
*/
async scriptKill() {
return this.createWritePromise((0, Commands_1.createScriptKill)(), {
decoder: BaseClient_1.Decoder.String,
});
}
/**
* Incrementally iterate over a collection of keys.
* `SCAN` is a cursor based iterator. This means that at every call of the method,
* the server returns an updated cursor that the user needs to use as the cursor argument in the next call.
* An iteration starts when the cursor is set to "0", and terminates when the cursor returned by the server is "0".
*
* A full iteration always retrieves all the elements that were present
* in the collection from the start to the end of a full iteration.
* Elements that were not constantly present in the collection during a full iteration, may be returned or not.
*
* @see {@link https://valkey.io/commands/scan|valkey.io} for more details.
*
* @param cursor - The `cursor` used for iteration. For the first iteration, the cursor should be set to "0".
* Using a non-zero cursor in the first iteration,
* or an invalid cursor at any iteration, will lead to undefined results.
* Using the same cursor in multiple iterations will, in case nothing changed between the iterations,
* return the same elements multiple times.
* If the the db has changed, it may result in undefined behavior.
* @param options - (Optional) The options to use for the scan operation, see {@link ScanOptions} and {@link DecoderOption}.
* @returns A List containing the next cursor value and a list of keys,
* formatted as [cursor, [key1, key2, ...]]
*
* @example
* ```typescript
* // Example usage of scan method
* let result = await client.scan('0');
* console.log(result); // Output: ['17', ['key1', 'key2', 'key3', 'key4', 'key5', 'set1', 'set2', 'set3']]
* let firstCursorResult = result[0];
* result = await client.scan(firstCursorResult);
* console.log(result); // Output: ['349', ['key4', 'key5', 'set1', 'hash1', 'zset1', 'list1', 'list2',
* // 'list3', 'zset2', 'zset3', 'zset4', 'zset5', 'zset6']]
* result = await client.scan(result[0]);
* console.log(result); // Output: ['0', ['key6', 'key7']]
*
* result = await client.scan(firstCursorResult, {match: 'key*', count: 2});
* console.log(result); // Output: ['6', ['key4', 'key5']]
*
* result = await client.scan("0", {type: ObjectType.Set});
* console.log(result); // Output: ['362', ['set1', 'set2', 'set3']]
* ```
*/
async scan(cursor, options) {
return this.createWritePromise((0, Commands_1.createScan)(cursor, options), options);
}
/**
* Returns the current subscription state for the client.
*
* @see {@link https://valkey.io/commands/pubsub/|valkey.io} for details.
*
* @returns A promise that resolves to the subscription state containing
* desired and actual subscriptions organized by channel mode.
*
* @example
* ```typescript
* const state = await client.getSubscriptions();
* console.log("Desired exact channels:", state.desiredSubscriptions[GlideClientConfiguration.PubSubChannelModes.Exact]);
* console.log("Actual exact channels:", state.actualSubscriptions[GlideClientConfiguration.PubSubChannelModes.Exact]);
* ```
*/
async getSubscriptions() {
const response = await this.createWritePromise((0, Commands_1.createGetSubscriptions)());
return this.parseGetSubscriptionsResponse(response);
}
}
exports.GlideClient = GlideClient;