| 1 | import type { UserCreatedPayload } from '@chatapp/common'; |
| 2 | import type { Collection } from 'mongodb'; |
| 3 | |
| 4 | import { getMongoClient } from '@/clients/mongo.client'; |
| 5 | |
| 6 | const COLLECTION_NAME = 'users'; |
| 7 | |
| 8 | const getCollection = async (): Promise<Collection<UserDocument>> => { |
| 9 | const client = await getMongoClient(); |
| 10 | return client.db().collection<UserDocument>(COLLECTION_NAME); |
| 11 | }; |
| 12 | |
| 13 | interface UserDocument { |
| 14 | _id: string; |
| 15 | email: string; |
| 16 | displayName: string; |
| 17 | createdAt: string; |
| 18 | updatedAt: string; |
| 19 | } |
| 20 | |
| 21 | export const userRepository = { |
| 22 | async upsertUser(payload: UserCreatedPayload) { |
| 23 | const collection = await getCollection(); |
| 24 | await collection.updateOne( |
| 25 | { _id: payload.id }, |
| 26 | { |
| 27 | $set: { |
| 28 | _id: payload.id, |
| 29 | email: payload.email, |
| 30 | displayName: payload.displayName, |
| 31 | createdAt: payload.createdAt, |
| 32 | updatedAt: payload.updatedAt, |
| 33 | }, |
| 34 | }, |
| 35 | { upsert: true }, |
| 36 | ); |
| 37 | }, |
| 38 | |
| 39 | async findUserById(id: string): Promise<UserDocument | null> { |
| 40 | const collection = await getCollection(); |
| 41 | return collection.findOne({ _id: id }); |
| 42 | }, |
| 43 | }; |