mubashir
mubashir

Reputation: 811

TypeORM Multi-Schema Insert Without Losing TypeScript Support in NestJS

I am using a multi-schema approach to manage my SaaS app in NestJS and TypeORM. I followed a Stack Overflow answer and discovered that the only way to change the schema at the query level or runtime is by using createQueryBuilder. However, the issue I'm facing is that insert operations return raw results without TypeScript support, which defeats the purpose of using TypeORM. Is there another, perhaps better, way to achieve this?

async createUser (registerTenant: RegisterTenantDto, queryRunner: QueryRunner, schemaName: string) {
        // Generate Password Hash
        const hash = await bcrypt.hash(registerTenant.password, SALT_OR_ROUNDS);
        
        const user = new User()
        user.country = registerTenant.country
        user.email= registerTenant.email
        user.phoneNumber = registerTenant.phoneNumber
        user.phoneNumberCode = registerTenant.phoneNumberCode
        user.password = hash

        const result = await queryRunner.manager.createQueryBuilder()
            .insert()
            .into(`${schemaName}.user`)
            .values([user])
            .returning('*')
            .execute()

        if (result.raw.length > 0) {
            return result.raw[0] as User
        }

        return null
}

Upvotes: 0

Views: 44

Answers (0)

Related Questions