@jojoxd/tsed-entity-mapper
TypeScript icon, indicating that this package has built-in type declarations

1.0.0 • Public • Published

@jojoxd/tsed-entity-mapper

status coverage Latest Release

See on NPM

Map Ts.ED request parameters to any object!

Installation

You can get the latest release and the type definitions using npm:

$ npm install @jojoxd/tsed-entity-mapper reflect-metadata
// Server.ts
import "reflect-metadata";
import "@jojoxd/tsed-entity-mapper";

// <snip>

@Configuration({
    // No configuration required
})
export class Server {}

⚠️ Important: Don't skip the reflect-metadata package. It is required to extract the types from your controller methods.
You also need "emitDecoratorMetadata": true in your tsconfig.

Examples

Creating a Mapper

The Entity Mapper is the core of translating parameters to an object.

import { Inject } from "@tsed/di";
import { EntityMapper } from "@jojoxd/tsed-entity-mapper";
import { MyEntity } from "../entity/my-entity";
import { MyEntityRepository } from "../entity/repository/my-entity-repository";

@EntityMapper(MyEntity)
export class MyEntityMapper implements EntityMapperMethods<MyEntity>
{
    // EntityMapper is an injectable, so Inject works here

    @Inject()
    protected entityRepository: MyEntityRepository;

    async map(value: unknown, ctx: EntityMapperMapContext<MyEntity>): Promise<MyEntity>
    {
        return this.entityRepository.find({ id: value });
    }
}

Using an Entity Mapper in a controller

Entity mappers are used when you specify a parameter decorator:

// Using the above defined Entity Mapper

import { Get, Post } from "@tsed/schema";
import { Controller } from "@tsed/common";
import { BodyParamEntity, QueryParamEntity, PathParamEntity } from "@jojoxd/tsed-entity-mapper";
import { MyEntity } from "../entity/my-entity";

@Controller('/')
export class MyController
{
    @Get('/test')
    getMyEntity(@QueryParamEntity('id') entity: MyEntity)
    {
        // entity will be resolved as a MyEntity
    }

    @Post('/test')
    async postMyEntity(@BodyParamEntity() entity: MyEntity)
    {
        // entity will be resolved as a MyEntity
    }
    
    @Get('/by-id/:id')
    async getById(@PathParamEntity('id') entity: MyEntity)
    {
        // entity will be resolved as a MyEntity
    }
}

Using the Entity Mapper itself:

It currently is not possible to use the Entity Mapper by itself.

Roadmap

  • [ ] Better Exception Handling
  • [ ] Extract mapping functionality from EntityMapperPipe into a usable service

Versions

Current Tags

  • Version
    Downloads (Last 7 Days)
    • Tag
  • 1.0.0
    1
    • latest

Version History

  • Version
    Downloads (Last 7 Days)
    • Published
  • 1.0.0
    1

Package Sidebar

Install

npm i @jojoxd/tsed-entity-mapper

Weekly Downloads

1

Version

1.0.0

License

MIT

Unpacked Size

34.5 kB

Total Files

7

Last publish

Collaborators

  • bakaxd