What is the best way to perform a dependent insertion of another entry into the database using Typeorm?

Asked

Viewed 41 times

0

The entities involved are the following (cardinality Onetoone)

User

import {
    Entity, 
    PrimaryGeneratedColumn, 
    Column, 
    OneToOne, 
    JoinColumn
} from "typeorm";
import Profile from "./Profile";

@Entity()
export default class User {
    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    nome: string;

    @Column()
    age: number;

    @OneToOne(() => Profile)
    @JoinColumn()
    profile: number;
}

Profile

import {
    Entity, 
    PrimaryGeneratedColumn, 
    Column,
    CreateDateColumn,
    BeforeInsert,
    BeforeUpdate
} from "typeorm";
import * as bcrypt from "bcryptjs"

@Entity()
export default class Profile {
    @PrimaryGeneratedColumn()
    id: number;
    
    @Column()
    email: string;

    @Column()
    password: string;

    @CreateDateColumn({ name: "created_at" })
    created_at: Date;
    
    @CreateDateColumn({ name: "updated_at" })
    updated_at: Date;

    @BeforeInsert()
    @BeforeUpdate()
    hashPassword(){
        this.password = bcrypt.hashSync(this.password, 12)
    }
}

What I have to do here is persist different data of the same user in different tables of my database, in the user table the data to be stored are name and age and in the profile table are email and password, but in the user table I have a foreign key referencing that user’s profile within the profile table, that is, in order to get the id of this user’s profile I need to first register the profile , take the generated profile id and then register the user’s age and name in the user table, all this is happening in the user controller’s store function, follow it below:

import { Request, Response } from "express"
import User  from "../entity/User"
import Profile from "../entity/Profile"
import { getRepository } from "typeorm"

class UserController{
    async store(request: Request, response: Response){
        const user_repository = getRepository(User)
        const profile_repository = getRepository(Profile)
        
        const { nome, age, email, password } = request.body
    
        const emailExists = await profile_repository.findOne({ email })
        if(emailExists){
            return response.json({ message: "Email inválido." })
        }else{
            const new_profile = profile_repository.create({ email, password })
            await profile_repository.save(new_profile)

            const new_user = user_repository.create({ nome, age, profile: new_profile.id })
            await user_repository.save(new_user)

            return response.json({
                user_data: new_user,
                profile_data: new_profile
            })
        }
    }
}

export default new UserController()

However I wanted to know if there is any way gave to ensure that whenever the profile is registered the user data will also be persisted in the user table and in case one of the wrong entries none of them should happen, I was able to do this using the query Builder knex with the transaction engine, but when I went to study and try to implement this mechanism using Typeorm, I was not very successful.

I’m thinking of creating procedures in the database so that persist the data in the profile table I call the procedure to register the data in the user table, but this is still an idea, I can get this procedure called by a Trigger attached to the profile table, but all of this is still an idea.

Already I appreciate too much the help of those who know how I can guarantee the persistence of data in the two tables and if any wrong cancel both tbm so do not generate profile unlinked to any user.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.