or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

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

database-operations.mddocs/

0

# Database Operations

1

2

Core CRUD operations for managing data in the JSON database, including data retrieval, storage, updates, and deletion with DataPath navigation.

3

4

## Capabilities

5

6

### Data Retrieval

7

8

#### Get Data

9

10

Retrieves data at the specified DataPath.

11

12

```typescript { .api }

13

/**

14

* Get the wanted data

15

* @param dataPath - Path of the data to retrieve (e.g., "/users/1/name")

16

* @returns Promise resolving to the data at the path

17

* @throws DataError when path doesn't exist

18

*/

19

getData(dataPath: string): Promise<any>;

20

```

21

22

**Usage Examples:**

23

24

```typescript

25

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

26

27

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

28

29

// Get entire object

30

const user = await db.getData("/users/1");

31

32

// Get specific property

33

const userName = await db.getData("/users/1/name");

34

35

// Get array

36

const tags = await db.getData("/posts/1/tags");

37

38

// Get root data

39

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

40

```

41

42

#### Get Typed Object

43

44

Same as getData but with TypeScript type safety.

45

46

```typescript { .api }

47

/**

48

* Same as getData only here it's directly typed to your object

49

* @param dataPath - Path of the data to retrieve

50

* @returns Promise resolving to typed data

51

*/

52

getObject<T>(dataPath: string): Promise<T>;

53

```

54

55

**Usage Examples:**

56

57

```typescript

58

interface User {

59

name: string;

60

email: string;

61

age: number;

62

}

63

64

// Get with type safety

65

const user = await db.getObject<User>("/users/1");

66

console.log(user.name); // TypeScript knows this is a string

67

68

// Get array with typing

69

const users = await db.getObject<User[]>("/users");

70

```

71

72

#### Get Object with Default

73

74

Retrieves data with a fallback default value when the path doesn't exist.

75

76

```typescript { .api }

77

/**

78

* Same as getData but with your own object type and a possible default value when we can't find the data path

79

* @param dataPath - Path of the data to retrieve

80

* @param defaultValue - Value to use when the dataPath doesn't lead to data

81

* @returns Promise resolving to data or default value

82

* @throws DataError for errors other than path not found

83

*/

84

getObjectDefault<T>(dataPath: string, defaultValue?: T): Promise<T>;

85

```

86

87

**Usage Examples:**

88

89

```typescript

90

// Get with default value

91

const settings = await db.getObjectDefault("/user/1/settings", {

92

theme: "light",

93

notifications: true

94

});

95

96

// Get array with empty array default

97

const posts = await db.getObjectDefault<Post[]>("/user/1/posts", []);

98

```

99

100

#### Check Existence

101

102

Checks if a DataPath exists without retrieving the data.

103

104

```typescript { .api }

105

/**

106

* Check for existing datapath

107

* @param dataPath - Path to check for existence

108

* @returns Promise resolving to true if path exists, false otherwise

109

*/

110

exists(dataPath: string): Promise<boolean>;

111

```

112

113

**Usage Examples:**

114

115

```typescript

116

// Check before accessing

117

if (await db.exists("/users/1")) {

118

const user = await db.getData("/users/1");

119

}

120

121

// Conditional operations

122

const hasSettings = await db.exists("/users/1/settings");

123

if (!hasSettings) {

124

await db.push("/users/1/settings", { theme: "light" });

125

}

126

```

127

128

### Data Modification

129

130

#### Push Data

131

132

Stores or updates data at the specified DataPath. Can override existing data or merge with it.

133

134

```typescript { .api }

135

/**

136

* Pushing data into the database

137

* @param dataPath - Path leading to the data

138

* @param data - Data to push

139

* @param override - Overriding or not the data, if not, it will merge them (default: true)

140

* @returns Promise that resolves when operation completes

141

* @throws DataError for type mismatches during merge operations

142

*/

143

push(dataPath: string, data: any, override?: boolean): Promise<void>;

144

```

145

146

**Usage Examples:**

147

148

```typescript

149

// Create new data (override mode - default)

150

await db.push("/users/1", {

151

name: "Alice",

152

email: "alice@example.com",

153

age: 25

154

});

155

156

// Update specific property

157

await db.push("/users/1/age", 26);

158

159

// Merge mode - combines with existing data

160

await db.push("/users/1", {

161

active: true,

162

lastLogin: new Date()

163

}, false);

164

165

// Merge arrays

166

await db.push("/users/1/tags", ["premium"], false);

167

// Results in concatenation: existing tags + ["premium"]

168

169

// Create nested structure automatically

170

await db.push("/posts/1/comments/0", {

171

author: "Bob",

172

text: "Great post!"

173

});

174

```

175

176

**Merge Behavior:**

177

- **Objects**: Properties are merged recursively

178

- **Arrays**: New array elements are concatenated to existing array

179

- **Primitives**: Cannot be merged, will throw DataError

180

181

#### Delete Data

182

183

Removes data at the specified DataPath.

184

185

```typescript { .api }

186

/**

187

* Delete the data

188

* @param dataPath - Path leading to the data to delete

189

* @returns Promise that resolves when deletion completes

190

*/

191

delete(dataPath: string): Promise<void>;

192

```

193

194

**Usage Examples:**

195

196

```typescript

197

// Delete specific property

198

await db.delete("/users/1/temporaryField");

199

200

// Delete entire object

201

await db.delete("/users/1");

202

203

// Delete array element

204

await db.delete("/posts/1/comments/0");

205

206

// Clear entire database

207

await db.delete("/");

208

```

209

210

### Database Management

211

212

#### Load Database

213

214

Manually loads the database from storage. Called automatically on first data access.

215

216

```typescript { .api }

217

/**

218

* Manually load the database

219

* It is automatically called when the first getData is done

220

* @returns Promise that resolves when loading completes

221

* @throws DatabaseError if loading fails

222

*/

223

load(): Promise<void>;

224

```

225

226

#### Save Database

227

228

Manually saves the database to storage.

229

230

```typescript { .api }

231

/**

232

* Manually save the database

233

* By default you can't save the database if it's not loaded

234

* @param force - Force the save of the database even if not loaded

235

* @returns Promise that resolves when saving completes

236

* @throws DatabaseError if saving fails

237

*/

238

save(force?: boolean): Promise<void>;

239

```

240

241

**Usage Examples:**

242

243

```typescript

244

// Configure for manual saving

245

const db = new JsonDB(new Config("database.json", false)); // saveOnPush = false

246

247

// Make changes

248

await db.push("/users/1", userData);

249

await db.push("/users/2", userData2);

250

251

// Save manually

252

await db.save();

253

254

// Force save even if not loaded

255

await db.save(true);

256

```

257

258

#### Reload Database

259

260

Reloads the database from storage, discarding any unsaved changes.

261

262

```typescript { .api }

263

/**

264

* Reload the database from the file

265

* @returns Promise that resolves when reloading completes

266

*/

267

reload(): Promise<void>;

268

```

269

270

**Usage Examples:**

271

272

```typescript

273

// Discard changes and reload from file

274

await db.reload();

275

276

// Useful for multi-process scenarios

277

setInterval(async () => {

278

await db.reload(); // Refresh every 30 seconds

279

}, 30000);

280

```

281

282

#### Reset Data

283

284

Directly resets the entire database content. Use with caution.

285

286

```typescript { .api }

287

/**

288

* Only use this if you know what you're doing.

289

* It reset the full data of the database.

290

* @param data - New data to replace entire database content

291

*/

292

resetData(data: any): void;

293

```

294

295

**Usage Examples:**

296

297

```typescript

298

// Reset to empty database

299

db.resetData({});

300

301

// Replace with new structure

302

db.resetData({

303

users: {},

304

posts: {},

305

settings: { version: "1.0" }

306

});

307

```

308

309

## DataPath Syntax

310

311

DataPaths use a slash-separated syntax similar to XMLPath:

312

313

- **Root**: `/` - Entire database

314

- **Object property**: `/users` - Access the "users" property

315

- **Nested property**: `/users/1/name` - Access nested properties

316

- **Array element**: `/users/0` - Access array by index

317

- **Array operations**: `/users[]` - Append to array

318

- **Negative index**: `/users[-1]` - Last element

319

- **Multi-dimensional**: `/matrix[0][1]` - 2D array access

320

321

**Examples:**

322

323

```javascript

324

// Given data structure:

325

{

326

"users": [

327

{ "name": "Alice", "posts": [1, 2, 3] },

328

{ "name": "Bob", "posts": [4, 5] }

329

],

330

"settings": {

331

"theme": "dark",

332

"notifications": true

333

}

334

}

335

336

// DataPath examples:

337

"/users/0/name" // "Alice"

338

"/users/1/posts/0" // 4

339

"/settings/theme" // "dark"

340

"/users/0/posts[]" // Append to Alice's posts

341

"/users[-1]" // Last user (Bob)

342

```