|
| 1 | +import getConfig from "next/config"; |
| 2 | +import { DuplicateUserError } from "../../models/errors"; |
| 3 | +import { User } from "../../models/user"; |
| 4 | +import { InsertOneResult, MongoClient, MongoServerError, WithId } from "mongodb"; |
| 5 | + |
| 6 | +const { serverRuntimeConfig } = getConfig(); |
| 7 | + |
| 8 | +if (!serverRuntimeConfig.mongoConfig.connectionStr) { |
| 9 | + throw new Error("mongo connection string is missing, please check MONGO_CONN_STR in your env file"); |
| 10 | +} |
| 11 | + |
| 12 | +if (!serverRuntimeConfig.mongoConfig.db) { |
| 13 | + throw new Error("mongo db name is missing, please check MONGO_DB_NAME in your env file"); |
| 14 | +} |
| 15 | + |
| 16 | +const client = new MongoClient(serverRuntimeConfig.mongoConfig.connectionStr); |
| 17 | +const usersCollection = client.db(serverRuntimeConfig.mongoConfig.db).collection<User>("User"); |
| 18 | + |
| 19 | +//function to connect to mongoDB and save a user to the database |
| 20 | +export async function saveUser(user: User): Promise<InsertOneResult<User>> { |
| 21 | + try { |
| 22 | + return await usersCollection.insertOne(user); |
| 23 | + } catch (err) { |
| 24 | + if (err instanceof MongoServerError && err.code === 11000) { |
| 25 | + throw new DuplicateUserError(); |
| 26 | + } |
| 27 | + throw err; |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +//function to connect to mongoDB and get a user from the database |
| 32 | +export async function getUserByAddress(address: string): Promise<WithId<User> | null> { |
| 33 | + return await usersCollection.findOne({ address: address }); |
| 34 | +} |
| 35 | + |
| 36 | +//function to get user by _id |
| 37 | +export async function getUserById(id: string): Promise<WithId<User> | null> { |
| 38 | + return await usersCollection.findOne({ id: id }); |
| 39 | +} |
| 40 | + |
| 41 | +//function to list all users |
| 42 | +export async function getAllUsers(): Promise<WithId<User>[]> { |
| 43 | + const usersCursor = usersCollection.find(); |
| 44 | + return await usersCursor.toArray(); |
| 45 | +} |
0 commit comments