import { Injectable } from ‘@nestjs/frequent’;
import DatabaseService from ‘../database/database.service’;
import UserModel from ‘./person.mannequin’;
import { CreateUserDto } from ‘./dto/createUser.dto’;
import isRecord from ‘../utils/isRecord’;
import PostgresErrorCode from ‘../database/postgresErrorCode.enum’;
import UserAlreadyExistsException from ‘./exceptions/userAlreadyExists.exception’;
@Injectable()
class UsersRepository {
constructor(non-public readonly databaseService: DatabaseService) {}
non-public async createUserWithAddress(userData: CreateUserDto) {
attempt {
const databaseResponse = await this.databaseService.runQuery(
`
WITH created_address AS (
INSERT INTO addresses (
avenue,
metropolis,
nation
) VALUES (
$1,
$2,
$3
) RETURNING *
),
created_user AS (
INSERT INTO customers (
electronic mail,
identify,
password,
tackle_id
) VALUES (
$4,
$5,
$6,
(SELECT id FROM created_address)
) RETURNING *
)
SELECT created_user.id AS id, created_user.electronic mail AS electronic mail, created_user.identify AS identify, created_user.password AS password,
created_address.id AS address_id, avenue AS address_street, metropolis AS address_city, nation AS address_country
FROM created_user, created_tackle
`,
[
userData.address.street,
userData.address.city,
userData.address.country,
userData.email,
userData.name,
userData.password,
],
);
return new UserModel(databaseResponse.rows[0]);
} catch (error) {
if (isRecord(error) && error.code === PostgresErrorCode.UniqueViolation) {
throw new UserAlreadyExistsException(userData.electronic mail);
}
throw error;
}
}
// …
}
export default UsersRepository;