layerify
TypeScript icon, indicating that this package has built-in type declarations

1.0.7 • Public • Published

layerify homepage

npm The MIT License Travis CI GitHub David Coveralls Greenkeeper badge semantic-release Commitizen friendly Type definitions Known Vulnerabilities code style: prettier manpm

make an un-nested object into a nested object by object keys

Why? start with 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

docs

License

MIT © xiechao <xiechao06@gmail.com>

Readme

Keywords

none

Package Sidebar

Install

npm i layerify

Weekly Downloads

1

Version

1.0.7

License

MIT

Unpacked Size

27 kB

Total Files

25

Last publish

Collaborators

  • xiechao06