Skip to content

Commit

Permalink
feat: new toPath method
Browse files Browse the repository at this point in the history
  • Loading branch information
alexsad committed Oct 9, 2023
1 parent 582f5da commit 7d224c3
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 0 deletions.
32 changes: 32 additions & 0 deletions src/JsonDB.ts
Original file line number Diff line number Diff line change
Expand Up @@ -413,4 +413,36 @@ export class JsonDB {
throw new DatabaseError("Can't save the database", 2, err)
}
}


/**
* Convert a router style path to a normal path
* @param path router based path to a correct base path
*/
public async toPath(path: string ): Promise<string> {

const [,...pathToQuery] = path.split("/")

const pathObject = pathToQuery.reduce((prev, curr, indexPath) => {
const isKey = indexPath % 2 === 0
if (isKey) {
prev[`${curr}`] = ''
} else {
const keys = Object.keys(prev)
prev[`${keys[keys.length - 1]}`] = `${curr}`
}
return prev
}, {} as {[key: string]:string})

let router = ''

for await (const pathKey of Object.keys(pathObject)) {
router += `/${pathKey}`
const pathValue = pathObject[pathKey]
const pathIndex = await this.getIndex(router, pathValue)
router += `[${pathIndex}]`
}

return router
}
}
42 changes: 42 additions & 0 deletions test/04-array-utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,48 @@ describe('Array Utils', () => {
expect(nestedArrayIndicies[1]).toEqual('2')
})
})
describe('To router path style to normal path', () => {
test('should convert a router style path to a normal path', async () => {
const recipe_1 = {
id: '78687873783',
name: 'Gratin',
category: 'Dish',
}
const recipe_2 = {
id: '65464646155',
name: 'Cheesecake',
category: 'Dessert',
nested: [
{
id: '458445',
name: 'test-1',
},
{
id: '88488',
name: 'test-2',
},
{
id: '458455',
name: 'test-3',
},
],
}
const recipe_3 = {
id: '12335373873',
name: 'Soupe',
category: 'Starter',
}
await db.push('/recipes[0]', recipe_1, true)
await db.push('/recipes[1]', recipe_2, true)
await db.push('/recipes[2]', recipe_3, true)

const routerPathStyle = '/recipes/65464646155/nested/88488'

const normalPath = await db.toPath(routerPathStyle)

expect(normalPath).toEqual('/recipes[1]/nested[1]')
})
})
describe('Cleanup', () => {
test('should remove the test files', async () => {
fs.unlinkSync('test/recipe.json')
Expand Down

0 comments on commit 7d224c3

Please sign in to comment.