@lcdev/api-fields
TypeScript icon, indicating that this package has built-in type declarations

0.1.5 • Public • Published

API Fields

Licensed under MPL 2.0 Build Status npm BundlePhobia

A small utility package that enables an easy way to guarantee that your API doesn't return fields that you didn't want it to.

yarn add @lcdev/api-fields@0.1

You might want to reduce the duplication when extracting return values. Most of the time, you want to return the same fields for the same entities, records, etc.

API Fields is a decorator for classes that gives you the ability to tie in to @lcdev/mapper, specifically its extract function.

import { ApiField } from '@lcdev/api-fields';

class User extends BaseEntity {
  @ApiField()
  id: number;

  // we never want to give this back in API responses
  // maybe it's private, or maybe we don't want consumers to depend on it
  privateField: number;

  @ApiField()
  firstName: string;

  // here, we only want the API Fields of Permission in the nested field
  @ApiField(() => Permission)
  permission: Permission;

  ...
}

To reveal the 'Extraction' object that can be used by @lcdev/mapper:

import { getApiFields } from '@lcdev/api-fields';
import { extract } from '@lcdev/mapper';

// getApiFields can be called anywhere to retrieve the `Extraction` object
const extraction = getApiFields(User);

// use the mapper package to take back only the fields you're interested in
const trimmedFields = extract(fullFields, extraction);

Decorator possibilities:

  • @ApiField() property means take all of property
  • @ApiField(() => PropertyType) property means take ApiFields of property
  • @ApiField(() => [PropertyType]) property[] means take ApiFields of all propertys
  • @ApiField({ ... }) property means take { ... } from property

You might want to create middleware in your router to do this type of extraction for you. Internally at Launchcode we do just that, and would like to open-source that effort as well.

Alternatives

Readme

Keywords

none

Package Sidebar

Install

npm i @lcdev/api-fields

Weekly Downloads

10

Version

0.1.5

License

MPL-2.0

Unpacked Size

32.8 kB

Total Files

6

Last publish

Collaborators

  • jbrandtlc
  • joelgallant-me
  • servalldev
  • gregnr