Thiago Dias
Thiago Dias

Reputation: 33

NestJs create relation given the id

I have 2 entities: User and Article. One article is created by one user, but one user may create many articles. Their respective entities are defined like this:

export class Article {
    id?: string; // Optional to allow db to generate id
    // ...
    user?: User;
}

export class User {
    id?: string;
    username: string;
    password: string;
}

I have separated the entities from their schemas following the NestJs Documentation. The Article should have a column userId that is related to the User. This is defined in the relations part of the schema. I do not specify an userId column, only in the relations.

export const ArticleSchema = new EntitySchema<Article>({
    name: 'Article',
    target: Article,
    tableName: 'Article',
    columns: {
        id: {
            type: String,
            primary: true,
            generated: 'uuid',
        },
        // ...
    },
    relations: {
        user: {
            type: 'many-to-one',
            target: 'User',
            nullable: false,
            joinColumn: {
                name: 'userId',
            },
        },
    },
});

In my controller, I receive a CreateArticleDto:

export class CreateArticleDto {
    // ...
    @IsUUID()
    userId: string;
}

I know that TypeORM, by default, creates a column relatedEntityId when we specify a relation and pass the entity, in my case, user: User. However, in my controller, I only have access to the userId. I want to create an Article without having to search for the User entity.

Currently, I have to create an empty user (with only the id) to pass it to the service, then search for the user with that id and save it in the Article in order to save an Article to the database:

Controller

const article: Article = {
    ...createArticleDto,
    user: {
        id: createArticleDto.userId,
        username: '',
        password: '',
    },
};
const result = await this.articleService.create(article);

Service

async create(article: Article) {
    const user = await this.userService.getById(article.user.id);
    article.user = user;
    const result = await this.articleRepository.create(article);
    return result;
}

Is there a better way of doing this? Ideally, using only the userId to create a new Article.

Upvotes: 0

Views: 947

Answers (1)

Thiago Dias
Thiago Dias

Reputation: 33

After more research I was able to find this obscure documentation. Although it seems like a workaround, I do not think there is another way of doing this.

There is a discussion that started on 2017 in the typeorm repo about this feature. Repeating the relationEntityId in the schema and entity feels wrong and kind of weird, but it is better than doing more database lookups than necessary.

Upvotes: 0

Related Questions