API Fields
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 ofproperty
-
@ApiField(() => PropertyType) property
means take ApiFields ofproperty
-
@ApiField(() => [PropertyType]) property[]
means take ApiFields of allproperty
s -
@ApiField({ ... }) property
means take{ ... }
fromproperty
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.