Eray
Eray

Reputation: 7128

NestJS - Creating Business Objects From Other Services

Nowadays I'm playing around with NestJS and trying to understand the best practices of NestJS world.

By following official documentations I have created service/dto/entity/controller for my business object called 'Cat'.

(also using SequelizeJS)

cat.entity.ts
@Table({
  freezeTableName: true,
})
export class Cat extends Model<Cat> {
    @AllowNull(false)
    @Column
    name: string;
    @Column
    breed: string;
}



create-cat.dto.ts
export class CreateCatDto {
    @IsString()
    readonly name: string;
    @IsString()
    readonly breed: string;
}


cat.service.ts
export class CatService {
    constructor(@Inject('CAT_REPOSITORY') private readonly CAT_REPOSITORY: typeof Cat) {}
    async create(createCatDto: CreateCatDto): Promise<Cat> {
        const cat = new Cat();
        cat.name = createCatDto.name;
        cat.breed = createCatDto.breed;

        return await cat.save();
    }
}

Now I can make POST requests to my controller and create Cat objects successfully. But I want to create a 'Cat' from other service and the create() method only takes CreateCatDto which I cannot/shouldn't initialize (it's read-only).

How can I call create(createCatDto: CreateCatDto) from other services? How you are handling this kind of requirements with NestJS? Should I create one more method like createFromEntity(cat: Cat) and use it?

Upvotes: 1

Views: 3946

Answers (1)

tano
tano

Reputation: 2817

try this:

const cat: CreateCatDto = { name: 'Miau', breed: 'some' };

Upvotes: 2

Related Questions