layerify
v1.0.7
Published
make an un-nested object into a nested object by object keys
Downloads
6
Readme
layerify homepage
make an un-nested object into a nested object by object keys
Why?
I prefer to use query builders like knex rather than ORM like bookshelf, because they are more explicit and still you could get validations compared to writing plain sql.
But it is a headache to write a bunch of mess like:
async function getUser (id) {
let [user] = await db('users')
.join('departments', 'users.department_id', 'departments.id')
.select(
'users.*',
'departments.id as departmentId',
'departments.name as departmentName'
)
.where('users.id', id)
user = {
id: user.id
name: user.name,
department: {
id: user.departmentId,
name: user.departmentName
}
}
return user
}
I still need a way to make joined-query elegantly. so I make this utility library. So the aforementioned codes could be written as:
async function getUser (id) {
let [user] = await db('users')
.join('departments', 'users.department_id', 'departments.id')
.select(
'users.*',
// assume departments is an object that defines the schema
Object.keys(departments).map(k => `department.${k} as department__${k}`)
)
.where('users.id', id)
return layerify(user)
}
Installation
npm i layerify
Basic Usage
const layerify = require('layerify') // or import layerify from 'layerify'
layerify({
a: 1,
b__a: 2,
}) // { a: 1, b: { a: 2 } }
layerify([{
a: 1,
b__a: 2,
}, {
c__a: 3
}]) // [{ a: 1, b: { a: 2 } }, { c: { a: 3 } }]
check test/test.js for more examples.
See also
Development
git clone https://github.com/xiechao06/layerify
cd layerify
npm test
npm test:watch
npm build
npm deploy:doc # deploy gh-pages
Documentation
License
MIT © xiechao <[email protected]>