File size: 1,490 Bytes
545f89a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import { ConflictException, Injectable } from '@nestjs/common';
import bcrypt from 'bcrypt';
import { v4 as uuidv4 } from 'uuid';
import { PrismaService } from '../database/prisma.service';
import { CreateAdminDto } from './dto/create-admin.dto';

@Injectable()
export class AdminService {
  constructor(private readonly prisma: PrismaService) {}

  async create(dto: CreateAdminDto) {
    // Is the email already registered
    const existingAdmin = await this.prisma.users.findUnique({
      where: { email: dto.email },
    });
    if (existingAdmin) {
      throw new ConflictException('Admin with this email already exists');
    }

    const hashedPassword = await bcrypt.hash(dto.password, 10);

    // Create new admin
    const newAdmin = await this.prisma.users.create({
      data: {
        id: uuidv4(),
        name: dto.name,
        email: dto.email,
        phoneNumber: dto.phoneNumber,
        role: dto.role,
        image: `https://ui-avatars.com/api/?background=1565D8&color=fff&rounded=true&size=128&length=2&bold=true&font-size=0.33&name=${dto.name}`,
        emailVerified: true,
        accounts: {
          create: [
            {
              id: uuidv4(),
              accountId: uuidv4(),
              providerId: 'credential',
              password: hashedPassword,
            },
          ],
        },
      },
      select: {
        id: true,
        email: true,
        role: true,
        name: true,
      },
    });

    return newAdmin;
  }
}