0.0.3 • Published 6 years ago

abject v0.0.3

Weekly downloads
7
License
MIT
Repository
github
Last release
6 years ago

abject

Get property value from an object by alias name

npm: abject CircleCI Coverage Status tested with jest code style: prettier license: mit TypeScript

Install

yarn add [-D] abject

Usage

import abject = require('./abject');

const post = {
  post: {
    id: 1,
    title: 'title',
    url: 'https://example.com',
    category: {
      id: 1,
      name: 'hoge'
    },
    tags: [
      {
        id: 1,
        name: 'foo',
      },
      {
        id: 2,
        name: 'bar',
      }
    ]
  }
}
interface IdealPost {
  id: number
  title: string,
  url: string,
  category: string,
  tags: [string, string]
}

const idealPostAbject = abject as abject.Fn<typeof post, IdealPost>;

/**
 * Register an alias with its actual path
 * `{ alias: actualPath }`
 */
const idealPost = idealPostAbject(post, {
  id: 'post.id',
  title: 'post.title',
  url: 'post.url',
  category: 'post.category.name',
  tags: 'post.tags[].name'
});

const id = idealPost('id')
// const id: number
expect(id).toBe(1);

const category = idealPost('category');
// const category: string
expect(category).toBe('hoge');

const tags = idealPost('tags');
// const tags: [string, string]
expect(tags).toEqual(
  expect.arrayContaining(['foo', 'bar'])
);