// otp.repository.ts import { Injectable } from "@nestjs/common"; import { InjectRepository } from "@nestjs/typeorm"; import { Repository } from "typeorm"; import { OtpVerification } from "./otp.entity"; @Injectable() export class OtpRepository { constructor( @InjectRepository( OtpVerification ) private readonly repository: Repository ) {} // --------------------------------------------------------------------------- // Find By Phone // --------------------------------------------------------------------------- async findByPhone( phone: string ) { return this.repository.findOne({ where: { phone, }, }); } // --------------------------------------------------------------------------- // Find By Email // --------------------------------------------------------------------------- async findByEmail( email: string ) { return this.repository.findOne({ where: { email, }, }); } // --------------------------------------------------------------------------- // Find By Target (either channel) // --------------------------------------------------------------------------- async findByTarget( target: { phone?: string; email?: string } ) { return target.email ? this.findByEmail(target.email) : this.findByPhone(target.phone!); } // --------------------------------------------------------------------------- // Create OTP // --------------------------------------------------------------------------- async createOtp( target: { phone?: string; email?: string }, otp: string ) { const entity = this.repository.create({ phone: target.phone, email: target.email, otp, verified: false, }); return this.repository.save( entity ); } // --------------------------------------------------------------------------- // Update OTP // --------------------------------------------------------------------------- async updateOtp( otpVerification: OtpVerification, otp: string ) { otpVerification.otp = otp; otpVerification.verified = false; return this.repository.save( otpVerification ); } // --------------------------------------------------------------------------- // Mark Verified // --------------------------------------------------------------------------- async markVerified( otpVerification: OtpVerification ) { otpVerification.verified = true; return this.repository.save( otpVerification ); } // --------------------------------------------------------------------------- // Delete OTP (single-use consume) // --------------------------------------------------------------------------- // Hard delete so the unique `phone` row is freed and a fresh code can be // requested for the same number on the next action. async deleteOtp( otpVerification: OtpVerification ) { return this.repository.remove( otpVerification ); } }