Skip to content

v4.1.0

Compare
Choose a tag to compare
@MrHus MrHus released this 18 Oct 12:45
· 55 commits to master since this release

feat: It is now possible to have a custom mapper.

Resource now accepts an configuration object, which can contain a
custom mapper. With the custom mapper it is possible to dynamically
add properties and to convert them.

For example:

class Pokeball extends makeResource<Pokeball>({
  baseUrl: '/api/pokeball',
  mapper: pokeballMapper,
}) {
  public id?: number;

  /*
    In the actual JSON response pokemon is simply an object.
    But our custom mapper makes sure it will also get mapped.
  */
  public pokemon!: Pokemon;

  /*
    Does not really exist on the back-end but is filled by the
    custom mapper.
  */
  public retrievedAt!: Date;
}

function pokeballMapper(json: any, Class: { new (): Pokeball }): Pokeball {
  const pokeball = makeInstance(Class, json);
  /* Add a completely new field */
  pokeball.retrievedAt = new Date();

  /* Make the fetched pokemon an actual instance of Pokemon */
  pokeball.pokemon = makeInstance(Pokemon, pokeball.pokemon);

  return pokeball;
}