eletrotupi / tcc/ api/src/services/user.service.tsd056c177d3c92fbe121ee526d7bab29f7ba377eb
1.7 KB | 75 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
import { CURRENT_TERMS_VERSION } from '@app/lib/constants';
11

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

16
  return await prisma.user.create({
17
    data: {
18
      ...data,
19
      encryptedPassword,
20
      termsAcceptedAt: acceptedTerms ? new Date() : undefined,
21
      termsVersion: acceptedTerms ? CURRENT_TERMS_VERSION : undefined,
22
    }
23
  })
24
};
25

26
export const findUserById = async(id: number): Promise<User | null> => {
27
  return await prisma.user.findUnique({
28
    where: {
29
      id
30
    }
31
  });
32
};
33

34
export const findUserByEmail = async(email: string): Promise<User | null> => {
35
  return await prisma.user.findUnique({
36
    where: {
37
      email
38
    }
39
  });
40
};
41

42
export const findUserByActivationCode = async(code: string): Promise<User | null> => {
43
  return await prisma.user.findUnique({
44
    where: {
45
      activationCode: code,
46
      activationCodeExpiresAt: { gt: new Date() }
47
    }
48
  });
49
}
50

51
export const updateUser = async (input: UpdateUserInput): Promise<User> => {
52
  const { password, ...data } = input;
53

54
  const updateData = {
55
    ...data,
56
    ...(password && { encryptedPassword: bcrypt.hashSync(password, 10) })
57
  };
58

59
  return await prisma.user.update({
60
    where: {
61
      id: input.id
62
    },
63
    data: updateData
64
  })
65
}
66

67
export const findUsersElligibleForPush = async (): Promise<User[]> => {
68
  return await prisma.user.findMany({
69
    where: {
70
      pushToken: {
71
        not: null
72
      }
73
    }
74
  });
75
}