or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

adapters.mdadvanced-features.mddatabase-operations.mdindex.md

adapters.mddocs/

0

# Adapters and Configuration

1

2

Flexible configuration system with built-in file storage adapter and support for custom storage backends through the adapter pattern.

3

4

## Capabilities

5

6

### Configuration Classes

7

8

#### Config Class

9

10

Standard configuration class that uses file-based JSON storage with built-in adapters.

11

12

```typescript { .api }

13

/**

14

* Standard configuration using file-based storage

15

* @param filename - Database filename (automatically adds .json if no extension)

16

* @param saveOnPush - Whether to save automatically after each push operation (default: true)

17

* @param humanReadable - Format JSON with indentation for readability (default: false)

18

* @param separator - DataPath separator character (default: "/")

19

* @param syncOnSave - Use synchronous file operations for guaranteed persistence (default: false)

20

*/

21

class Config implements JsonDBConfig {

22

constructor(

23

filename: string,

24

saveOnPush?: boolean,

25

humanReadable?: boolean,

26

separator?: string,

27

syncOnSave?: boolean

28

);

29

30

readonly filename: string;

31

readonly adapter: IAdapter<any>;

32

readonly saveOnPush: boolean;

33

readonly separator: string;

34

}

35

```

36

37

**Usage Examples:**

38

39

```typescript

40

import { JsonDB, Config } from "node-json-db";

41

42

// Basic configuration

43

const db1 = new JsonDB(new Config("database.json"));

44

45

// With custom settings

46

const db2 = new JsonDB(new Config(

47

"users", // filename (will become users.json)

48

true, // saveOnPush - auto-save on changes

49

true, // humanReadable - formatted JSON

50

"/", // separator for DataPaths

51

false // syncOnSave - async file operations

52

));

53

54

// Production config with sync saves for data integrity

55

const db3 = new JsonDB(new Config(

56

"/var/data/production.json",

57

true, // auto-save

58

false, // compact JSON

59

"/", // standard separator

60

true // sync saves for guaranteed persistence

61

));

62

```

63

64

#### ConfigWithAdapter Class

65

66

Configuration class for use with custom adapters, providing full control over storage backend.

67

68

```typescript { .api }

69

/**

70

* Configuration with custom adapter

71

* @param adapter - Custom storage adapter implementing IAdapter interface

72

* @param saveOnPush - Whether to save automatically after each push operation (default: true)

73

* @param separator - DataPath separator character (default: "/")

74

*/

75

class ConfigWithAdapter implements JsonDBConfig {

76

constructor(

77

adapter: IAdapter<any>,

78

saveOnPush?: boolean,

79

separator?: string

80

);

81

82

readonly adapter: IAdapter<any>;

83

readonly saveOnPush: boolean;

84

readonly separator: string;

85

}

86

```

87

88

**Usage Examples:**

89

90

```typescript

91

import { JsonDB, ConfigWithAdapter, JsonAdapter, FileAdapter } from "node-json-db";

92

93

// Custom adapter configuration

94

const fileAdapter = new FileAdapter("/custom/path/data.json", true);

95

const jsonAdapter = new JsonAdapter(fileAdapter, true); // human readable

96

const config = new ConfigWithAdapter(jsonAdapter, false, "|"); // custom separator

97

98

const db = new JsonDB(config);

99

```

100

101

### Adapter Interfaces

102

103

#### IAdapter Interface

104

105

Base interface for all storage adapters, defining the contract for reading and writing data.

106

107

```typescript { .api }

108

/**

109

* Base adapter interface for data storage

110

* Use to read and write data of type T

111

*/

112

interface IAdapter<T> {

113

/**

114

* Read the data from the storage medium

115

* @returns Promise resolving to data of type T or null if no data exists

116

*/

117

readAsync(): Promise<T | null>;

118

119

/**

120

* Write data into the storage medium

121

* @param data - Data to write to storage

122

* @returns Promise that resolves when write operation completes

123

*/

124

writeAsync(data: T): Promise<void>;

125

}

126

127

```

128

129

130

### Built-in Adapters

131

132

#### JsonAdapter Class

133

134

Handles JSON serialization and deserialization, including automatic date parsing and formatting options.

135

136

```typescript { .api }

137

/**

138

* JSON serialization adapter with date handling and formatting options

139

* @param adapter - Underlying string-based adapter (typically FileAdapter)

140

* @param humanReadable - Format JSON with indentation (default: false)

141

*/

142

class JsonAdapter implements IAdapter<any> {

143

constructor(adapter: IAdapter<string>, humanReadable?: boolean);

144

145

/**

146

* Read and parse JSON data with automatic date parsing

147

* @returns Promise resolving to parsed JavaScript object

148

*/

149

readAsync(): Promise<any>;

150

151

/**

152

* Stringify and write JSON data

153

* @param data - JavaScript object to serialize

154

* @returns Promise that resolves when write completes

155

*/

156

writeAsync(data: any): Promise<void>;

157

}

158

```

159

160

**Usage Examples:**

161

162

```typescript

163

import { JsonAdapter, FileAdapter } from "node-json-db";

164

165

// Basic JSON adapter

166

const fileAdapter = new FileAdapter("data.json", false);

167

const jsonAdapter = new JsonAdapter(fileAdapter);

168

169

// Human readable JSON with indentation

170

const readableAdapter = new JsonAdapter(fileAdapter, true);

171

172

// Custom usage

173

await jsonAdapter.writeAsync({ users: [], posts: [] });

174

const data = await jsonAdapter.readAsync();

175

```

176

177

**Date Handling:**

178

The JsonAdapter automatically converts ISO date strings back to Date objects when reading:

179

180

```typescript

181

// Writing

182

await db.push("/created", new Date());

183

184

// Reading - automatically converted back to Date object

185

const created = await db.getData("/created");

186

console.log(created instanceof Date); // true

187

```

188

189

#### FileAdapter Class

190

191

File system storage adapter that handles reading from and writing to files with directory creation and error handling.

192

193

```typescript { .api }

194

/**

195

* File system storage adapter

196

* @param filename - Path to the file for storage

197

* @param fsync - Use synchronous file operations for guaranteed persistence

198

*/

199

class FileAdapter implements IAdapter<string> {

200

constructor(filename: string, fsync: boolean);

201

202

readonly filename: string;

203

204

/**

205

* Read file content as string

206

* @returns Promise resolving to file content or null if file doesn't exist

207

*/

208

readAsync(): Promise<string | null>;

209

210

/**

211

* Write string content to file, creating directories as needed

212

* @param data - String data to write to file

213

* @returns Promise that resolves when write operation completes

214

*/

215

writeAsync(data: string): Promise<void>;

216

}

217

```

218

219

**Usage Examples:**

220

221

```typescript

222

import { FileAdapter } from "node-json-db";

223

224

// Basic file adapter

225

const adapter = new FileAdapter("database.json", false);

226

227

// With sync operations for data integrity

228

const syncAdapter = new FileAdapter("/critical/data.json", true);

229

230

// Directory creation is automatic

231

const nestedAdapter = new FileAdapter("data/backups/db.json", false);

232

233

// Read/write operations

234

await adapter.writeAsync('{"test": "data"}');

235

const content = await adapter.readAsync(); // '{"test": "data"}'

236

```

237

238

**Features:**

239

- **Automatic directory creation**: Creates parent directories if they don't exist

240

- **Error handling**: Properly handles file not found, permission errors, etc.

241

- **Atomic writes**: Uses file handles for safe write operations

242

- **Sync option**: Optional fsync for guaranteed disk persistence

243

244

### Custom Adapter Implementation

245

246

You can implement custom adapters for different storage backends:

247

248

```typescript

249

import { IAdapter } from "node-json-db";

250

251

// Example: Memory adapter

252

class MemoryAdapter implements IAdapter<any> {

253

private data: any = null;

254

255

async readAsync(): Promise<any> {

256

return this.data;

257

}

258

259

async writeAsync(data: any): Promise<void> {

260

this.data = data;

261

}

262

}

263

264

// Example: Redis adapter

265

class RedisAdapter implements IAdapter<any> {

266

constructor(private client: RedisClient, private key: string) {}

267

268

async readAsync(): Promise<any> {

269

const data = await this.client.get(this.key);

270

return data ? JSON.parse(data) : null;

271

}

272

273

async writeAsync(data: any): Promise<void> {

274

await this.client.set(this.key, JSON.stringify(data));

275

}

276

}

277

278

// Usage with custom adapter

279

const config = new ConfigWithAdapter(new MemoryAdapter());

280

const db = new JsonDB(config);

281

```

282

283

### Configuration Interface

284

285

#### JsonDBConfig Interface

286

287

Base configuration interface that all configuration classes must implement.

288

289

```typescript { .api }

290

/**

291

* Database configuration interface

292

*/

293

interface JsonDBConfig {

294

/**

295

* Storage adapter for reading/writing data

296

*/

297

readonly adapter: IAdapter<any>;

298

299

/**

300

* Whether to automatically save after push operations

301

*/

302

readonly saveOnPush: boolean;

303

304

/**

305

* Character used to separate DataPath segments

306

*/

307

readonly separator: string;

308

}

309

```

310

311

## Configuration Best Practices

312

313

### Development vs Production

314

315

```typescript

316

// Development - readable JSON, auto-save, async operations

317

const devConfig = new Config("dev-database.json", true, true, "/", false);

318

319

// Production - compact JSON, manual saves, sync operations for reliability

320

const prodConfig = new Config("prod-database.json", false, false, "/", true);

321

```

322

323

### Memory vs Disk

324

325

```typescript

326

// For caching or temporary data

327

const memoryConfig = new ConfigWithAdapter(new MemoryAdapter());

328

329

// For persistent data

330

const diskConfig = new Config("persistent.json", true, false, "/", true);

331

```

332

333

### Custom Separators

334

335

```typescript

336

// Windows-style paths

337

const windowsConfig = new Config("database.json", true, false, "\\");

338

339

// Dot notation

340

const dotConfig = new Config("database.json", true, false, ".");

341

342

// Usage with custom separator

343

await db.getData("\\users\\1\\name"); // Windows style

344

await db.getData(".users.1.name"); // Dot notation

345

```