or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/npm-keyv

Simple key-value storage with support for multiple backends

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/keyv@5.5.x

To install, run

npx @tessl/cli install tessl/npm-keyv@5.5.0

0

# Keyv

1

2

Keyv is a simple key-value storage library that provides a consistent interface for key-value storage across multiple backends via storage adapters. It supports TTL-based expiry, making it suitable as both a cache and persistent key-value store, with built-in event handling, hooks system, and comprehensive type safety.

3

4

## Package Information

5

6

- **Package Name**: keyv

7

- **Package Type**: npm

8

- **Language**: TypeScript

9

- **Installation**: `npm install keyv`

10

11

## Core Imports

12

13

```typescript

14

import Keyv from "keyv";

15

import { KeyvHooks, type KeyvOptions, type KeyvStoreAdapter } from "keyv";

16

```

17

18

For CommonJS:

19

20

```javascript

21

const Keyv = require("keyv");

22

const { KeyvHooks } = require("keyv");

23

```

24

25

## Basic Usage

26

27

```typescript

28

import Keyv from "keyv";

29

30

// Create instance with in-memory storage

31

const keyv = new Keyv();

32

33

// Basic operations

34

await keyv.set('user:1', { name: 'Alice', age: 30 }); // true

35

const user = await keyv.get('user:1'); // { name: 'Alice', age: 30 }

36

await keyv.delete('user:1'); // true

37

38

// TTL support (expires in 1 minute)

39

await keyv.set('temp-data', 'expires soon', 60000);

40

41

// Type safety

42

const keyv_typed = new Keyv<string>();

43

await keyv_typed.set('message', 'hello world');

44

const message = await keyv_typed.get('message'); // string | undefined

45

```

46

47

## Architecture

48

49

Keyv is built around several key components:

50

51

- **Core Storage Operations**: Promise-based get/set/delete with TTL support and batch operations

52

- **Storage Adapter System**: Pluggable backends (Redis, MongoDB, SQLite, PostgreSQL, MySQL, etc.)

53

- **Event System**: Built-in EventEmitter for connection errors, clear, and disconnect events

54

- **Hook System**: Pre/post operation hooks for custom functionality on all CRUD operations

55

- **Statistics Tracking**: Built-in hit/miss/set/delete operation counters

56

- **Compression Support**: Optional compression with gzip, brotli, and lz4 adapters

57

- **Namespace Support**: Key isolation to avoid collisions in shared storage backends

58

59

## Capabilities

60

61

### Core Storage Operations

62

63

Primary key-value storage functionality including get, set, delete operations with TTL support and batch operations for performance.

64

65

```typescript { .api }

66

class Keyv<GenericValue = any> {

67

constructor(options?: KeyvOptions);

68

constructor(store?: KeyvStoreAdapter | KeyvOptions | Map<any, any>, options?: Omit<KeyvOptions, 'store'>);

69

70

get<Value = GenericValue>(key: string, options?: {raw?: boolean}): Promise<StoredDataNoRaw<Value> | StoredDataRaw<Value>>;

71

get<Value = GenericValue>(key: string[], options?: {raw?: boolean}): Promise<Array<StoredDataNoRaw<Value>> | Array<StoredDataRaw<Value>>>;

72

set<Value = GenericValue>(key: string, value: Value, ttl?: number): Promise<boolean>;

73

delete(key: string | string[]): Promise<boolean>;

74

clear(): Promise<void>;

75

has(key: string | string[]): Promise<boolean | boolean[]>;

76

77

// Iterator for async iteration over entries (when supported by storage adapter)

78

iterator?: IteratorFunction;

79

}

80

```

81

82

[Core Storage Operations](./core-storage.md)

83

84

### Batch Operations

85

86

High-performance batch operations for working with multiple keys simultaneously, with optimizations for storage adapters that support native batch operations.

87

88

```typescript { .api }

89

getMany<Value = GenericValue>(keys: string[], options?: {raw?: boolean}): Promise<Array<StoredDataNoRaw<Value>> | Array<StoredDataRaw<Value>>>;

90

setMany<Value = GenericValue>(entries: KeyvEntry[]): Promise<boolean[]>;

91

deleteMany(keys: string[]): Promise<boolean>;

92

hasMany(keys: string[]): Promise<boolean[]>;

93

94

interface KeyvEntry {

95

key: string;

96

value: any;

97

ttl?: number;

98

}

99

```

100

101

[Batch Operations](./batch-operations.md)

102

103

### Raw Data Access

104

105

Direct access to internal data structures including TTL metadata, useful for debugging and advanced use cases where expiry information is needed.

106

107

```typescript { .api }

108

getRaw<Value = GenericValue>(key: string): Promise<StoredDataRaw<Value> | undefined>;

109

getManyRaw<Value = GenericValue>(keys: string[]): Promise<Array<StoredDataRaw<Value>>>;

110

111

type DeserializedData<Value> = {

112

value?: Value;

113

expires?: number | undefined;

114

};

115

116

type StoredDataRaw<Value> = DeserializedData<Value> | undefined;

117

```

118

119

[Raw Data Access](./raw-data-access.md)

120

121

### Storage Adapters

122

123

Pluggable storage backend system with support for Redis, MongoDB, SQLite, PostgreSQL, MySQL, and any Map-compatible storage.

124

125

```typescript { .api }

126

interface KeyvStoreAdapter {

127

opts: any;

128

namespace?: string;

129

get<Value>(key: string): Promise<StoredData<Value> | undefined>;

130

set(key: string, value: any, ttl?: number): any;

131

delete(key: string): Promise<boolean>;

132

clear(): Promise<void>;

133

// Optional methods

134

setMany?(values: Array<{key: string; value: any; ttl?: number}>): Promise<void>;

135

getMany?<Value>(keys: string[]): Promise<Array<StoredData<Value | undefined>>>;

136

has?(key: string): Promise<boolean>;

137

hasMany?(keys: string[]): Promise<boolean[]>;

138

deleteMany?(key: string[]): Promise<boolean>;

139

disconnect?(): Promise<void>;

140

iterator?<Value>(namespace?: string): AsyncGenerator<Array<string | Awaited<Value> | undefined>, void>;

141

}

142

```

143

144

[Storage Adapters](./storage-adapters.md)

145

146

### Events and Hooks

147

148

Event system for connection monitoring and lifecycle management, plus hooks system for custom functionality on CRUD operations.

149

150

```typescript { .api }

151

enum KeyvHooks {

152

PRE_SET = 'preSet',

153

POST_SET = 'postSet',

154

PRE_GET = 'preGet',

155

POST_GET = 'postGet',

156

PRE_GET_MANY = 'preGetMany',

157

POST_GET_MANY = 'postGetMany',

158

PRE_GET_RAW = 'preGetRaw',

159

POST_GET_RAW = 'postGetRaw',

160

PRE_GET_MANY_RAW = 'preGetManyRaw',

161

POST_GET_MANY_RAW = 'postGetManyRaw',

162

PRE_DELETE = 'preDelete',

163

POST_DELETE = 'postDelete'

164

}

165

```

166

167

[Events and Hooks](./events-hooks.md)

168

169

### Configuration and Properties

170

171

Configuration options and runtime property management for customizing serialization, compression, namespacing, and error handling behavior.

172

173

```typescript { .api }

174

interface KeyvOptions {

175

emitErrors?: boolean;

176

namespace?: string;

177

serialize?: Serialize;

178

deserialize?: Deserialize;

179

store?: KeyvStoreAdapter | Map<any, any> | any;

180

ttl?: number;

181

compression?: CompressionAdapter | any;

182

stats?: boolean;

183

useKeyPrefix?: boolean;

184

throwOnErrors?: boolean;

185

}

186

187

interface CompressionAdapter {

188

compress(value: any, options?: any): Promise<any>;

189

decompress(value: any, options?: any): Promise<any>;

190

serialize<Value>(data: DeserializedData<Value>): Promise<string> | string;

191

deserialize<Value>(data: string): Promise<DeserializedData<Value> | undefined> | DeserializedData<Value> | undefined;

192

}

193

```

194

195

[Configuration and Properties](./configuration.md)

196

197

## Types

198

199

```typescript { .api }

200

type StoredDataNoRaw<Value> = Value | undefined;

201

type StoredData<Value> = StoredDataNoRaw<Value> | StoredDataRaw<Value>;

202

203

type Serialize = <Value>(data: DeserializedData<Value>) => Promise<string> | string;

204

type Deserialize = <Value>(data: string) => Promise<DeserializedData<Value> | undefined> | DeserializedData<Value> | undefined;

205

206

type IteratorFunction = (argument: any) => AsyncGenerator<any, void>;

207

```