user.repositories.ts76 lines, 2.0 KB
| 1 | import { Op, type WhereOptions } from 'sequelize'; |
| 2 | |
| 3 | import type { CreateUserInput, User } from '@/types/user'; |
| 4 | import type { AuthUserRegisteredPayload } from '@chatapp/common'; |
| 5 | |
| 6 | import { UserModel } from '@/db'; |
| 7 | |
| 8 | const toDomainUser = (model: UserModel): User => ({ |
| 9 | id: model.id, |
| 10 | email: model.email, |
| 11 | displayName: model.displayName, |
| 12 | createdAt: model.createdAt, |
| 13 | updatedAt: model.updatedAt, |
| 14 | }); |
| 15 | |
| 16 | export class UserRepository { |
| 17 | async findById(id: string): Promise<User | null> { |
| 18 | const user = await UserModel.findByPk(id); |
| 19 | return user ? toDomainUser(user) : null; |
| 20 | } |
| 21 | |
| 22 | async findAll(): Promise<User[]> { |
| 23 | const users = await UserModel.findAll({ |
| 24 | order: [['displayName', 'ASC']], |
| 25 | }); |
| 26 | return users.map(toDomainUser); |
| 27 | } |
| 28 | |
| 29 | async create(data: CreateUserInput): Promise<User> { |
| 30 | const user = await UserModel.create(data); |
| 31 | return toDomainUser(user); |
| 32 | } |
| 33 | |
| 34 | async searchByQuery( |
| 35 | query: string, |
| 36 | options: { limit?: number; excludeIds?: string[] } = {}, |
| 37 | ): Promise<User[]> { |
| 38 | const where: WhereOptions = { |
| 39 | [Op.or]: [ |
| 40 | { displayName: { [Op.iLike]: `%${query}%` } }, |
| 41 | { email: { [Op.iLike]: `%${query}%` } }, |
| 42 | ], |
| 43 | }; |
| 44 | |
| 45 | if (options.excludeIds && options.excludeIds.length > 0) { |
| 46 | Object.assign(where, { |
| 47 | [Op.and]: [{ id: { [Op.notIn]: options.excludeIds } }], |
| 48 | }); |
| 49 | } |
| 50 | |
| 51 | const users = await UserModel.findAll({ |
| 52 | where, |
| 53 | order: [['displayName', 'ASC']], |
| 54 | limit: options.limit ?? 10, |
| 55 | }); |
| 56 | |
| 57 | return users.map(toDomainUser); |
| 58 | } |
| 59 | |
| 60 | async upsertFromAuthEvent(payload: AuthUserRegisteredPayload): Promise<User> { |
| 61 | const [user] = await UserModel.upsert( |
| 62 | { |
| 63 | id: payload.id, |
| 64 | email: payload.email, |
| 65 | displayName: payload.displayName, |
| 66 | createdAt: new Date(payload.createdAt), |
| 67 | updatedAt: new Date(payload.createdAt), |
| 68 | }, |
| 69 | { returning: true }, |
| 70 | ); |
| 71 | |
| 72 | return toDomainUser(user); |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | export const userRepository = new UserRepository(); |