Skip to content

Commit

Permalink
feat(typing): Add basic typing to the lib for TS
Browse files Browse the repository at this point in the history
Only in the case of the get
  • Loading branch information
Belphemur committed Mar 7, 2021
1 parent efe29a5 commit 5309e9e
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 1 deletion.
20 changes: 20 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,26 @@ import { Config } from 'node-json-db/dist/lib/JsonDBConfig'
const db = new JsonDB(new Config("myDataBase", true, false, '/'));
```

#### Typing
With TypeScript, you have access to a new method: getObject<T> that will take care of typing your return object.
```typescript
import { JsonDB } from 'node-json-db';
import { Config } from 'node-json-db/dist/lib/JsonDBConfig'

const db = new JsonDB(new Config("myDataBase", true, false, '/'));

interface FooBar {
Hello: string
World: number
}
const object = {Hello: "World", World: 5} as FooBar;

db.push("/test", object);

//Will be typed as FooBar in your IDE
const result = db.getObject<FooBar>("/test");
```


### Array Support
You can also access the information stored into arrays and manipulate them.
Expand Down
10 changes: 9 additions & 1 deletion src/JsonDB.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,13 +133,21 @@ export class JsonDB {

/**
* Get the wanted data
* @param dataPath
* @param dataPath path of the data to retrieve
*/
public getData(dataPath: string): any {
const path = this.processDataPath(dataPath)
return this.retrieveData(path, false)
}

/**
* Same as getData only here it's directly typed to your object
* @param dataPath path of the data to retrieve
*/
public getObject<T>(dataPath: string): T {
return this.getData(dataPath);
}

/**
* Check for existing datapath
* @param dataPath
Expand Down
11 changes: 11 additions & 0 deletions test/02-jsondb.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,11 @@ const testFile4 = "test/array_file"
const testFile5 = "test/test_file_empty"
const testFile6 = "test/test_delete"


interface Test {
Hello: string
World: number
}
describe('JsonDB', () => {
describe('Exception/Error', () => {
test('should create create a DataError', () => {
Expand Down Expand Up @@ -102,6 +107,12 @@ describe('JsonDB', () => {
expect(db.getData("@")).toBe(object)
})

test('should store the data with typing', () => {
const object = {Hello: "test", World: 0} as Test;
db.push("@/hello", object)
const result = db.getObject<Test>("@");
expect(result).toBe(object)
})
test('should have data at root', () => {
expect(db.exists('@test@test')).toBeTruthy()
})
Expand Down

0 comments on commit 5309e9e

Please sign in to comment.