eletrotupi / tcc/ api/src/services/user.service.ts13a51f682d4b5fcaa5c7daa8c766d0d8738d29da
1.5 KB | 70 lines Raw
1
import { prisma } from '@app/lib/prisma';
2
import { User } from '@prisma/client';
3
import bcrypt from 'bcryptjs';
4

5
import {
6
  CreateUserInput,
7
  UpdateUserInput
8
} from "@app/schemas";
9

10
export const createUser = async(input: CreateUserInput): Promise<User> => {
11
  const { password, ...data } = input;
12
  const encryptedPassword = bcrypt.hashSync(password, 10);
13

14
  return await prisma.user.create({
15
    data: {
16
      ...data, encryptedPassword
17
    }
18
  })
19
};
20

21
export const findUserById = async(id: number): Promise<User | null> => {
22
  return await prisma.user.findUnique({
23
    where: {
24
      id
25
    }
26
  });
27
};
28

29
export const findUserByEmail = async(email: string): Promise<User | null> => {
30
  return await prisma.user.findUnique({
31
    where: {
32
      email
33
    }
34
  });
35
};
36

37
export const findUserByActivationCode = async(code: string): Promise<User | null> => {
38
  return await prisma.user.findUnique({
39
    where: {
40
      activationCode: code,
41
      activationCodeExpiresAt: { gt: new Date() }
42
    }
43
  });
44
}
45

46
export const updateUser = async (input: UpdateUserInput): Promise<User> => {
47
  const { password, ...data } = input;
48

49
  const updateData = {
50
    ...data,
51
    ...(password && { encryptedPassword: bcrypt.hashSync(password, 10) })
52
  };
53

54
  return await prisma.user.update({
55
    where: {
56
      id: input.id
57
    },
58
    data: updateData
59
  })
60
}
61

62
export const findUsersElligibleForPush = async (): Promise<User[]> => {
63
  return await prisma.user.findMany({
64
    where: {
65
      pushToken: {
66
        not: null
67
      }
68
    }
69
  });
70
}