Files
AuroraBot-discord/src/modules/user/user.service.ts

69 lines
2.5 KiB
TypeScript

import { users } from "@/db/schema";
import { eq, sql } from "drizzle-orm";
import { DrizzleClient } from "@/lib/DrizzleClient";
export const userService = {
getUserById: async (id: string) => {
const user = await DrizzleClient.query.users.findFirst({
where: eq(users.id, BigInt(id)),
with: { class: true }
});
return user;
},
getUserByUsername: async (username: string) => {
const user = await DrizzleClient.query.users.findFirst({ where: eq(users.username, username) });
return user;
},
getOrCreateUser: async (id: string, username: string, tx?: any) => {
const execute = async (txFn: any) => {
let user = await txFn.query.users.findFirst({
where: eq(users.id, BigInt(id)),
with: { class: true }
});
if (!user) {
const [newUser] = await txFn.insert(users).values({
id: BigInt(id),
username,
}).returning();
user = { ...newUser, class: null };
}
return user;
};
return tx ? await execute(tx) : await DrizzleClient.transaction(execute);
},
getUserClass: async (id: string) => {
const user = await DrizzleClient.query.users.findFirst({
where: eq(users.id, BigInt(id)),
with: { class: true }
});
return user?.class;
},
createUser: async (id: string | bigint, username: string, classId?: bigint, tx?: any) => {
const execute = async (txFn: any) => {
const [user] = await txFn.insert(users).values({
id: BigInt(id),
username,
classId,
}).returning();
return user;
};
return tx ? await execute(tx) : await DrizzleClient.transaction(execute);
},
updateUser: async (id: string, data: Partial<typeof users.$inferInsert>, tx?: any) => {
const execute = async (txFn: any) => {
const [user] = await txFn.update(users)
.set(data)
.where(eq(users.id, BigInt(id)))
.returning();
return user;
};
return tx ? await execute(tx) : await DrizzleClient.transaction(execute);
},
deleteUser: async (id: string, tx?: any) => {
const execute = async (txFn: any) => {
await txFn.delete(users).where(eq(users.id, BigInt(id)));
};
return tx ? await execute(tx) : await DrizzleClient.transaction(execute);
},
};