70 lines
2 KiB
TypeScript
70 lines
2 KiB
TypeScript
import { eq } from 'drizzle-orm'
|
|
import bcrypt from 'bcryptjs'
|
|
|
|
import { db } from './db-instance'
|
|
import { staff } from './schema/staff'
|
|
|
|
export type Staff = {
|
|
id: number
|
|
name: string
|
|
username: string
|
|
email: string | null
|
|
mobile: string | null
|
|
added_on: string
|
|
password: string
|
|
is_password_reset_needed: boolean
|
|
}
|
|
|
|
export type StaffRepo = {
|
|
getStaffById: (id: number) => Promise<Staff | null>
|
|
getStaffByUsername: (username: string) => Promise<Staff | null>
|
|
createStaff: (input: { name: string; username: string; email?: string | null; mobile?: string | null; added_on: string; password: string; is_password_reset_needed?: boolean }) => Promise<Staff>
|
|
verifyPassword: (staff: Staff, password: string) => Promise<boolean>
|
|
}
|
|
|
|
function toStaff(row: typeof staff.$inferSelect): Staff {
|
|
return {
|
|
id: row.id,
|
|
name: row.name,
|
|
username: row.username,
|
|
email: row.email,
|
|
mobile: row.mobile,
|
|
added_on: row.addedOn,
|
|
password: row.password,
|
|
is_password_reset_needed: row.isPasswordResetNeeded,
|
|
}
|
|
}
|
|
|
|
export function createStaffRepo(): { repo: StaffRepo } {
|
|
const repo: StaffRepo = {
|
|
getStaffById(id) {
|
|
const row = db.select().from(staff).where(eq(staff.id, id)).get()
|
|
return Promise.resolve(row ? toStaff(row) : null)
|
|
},
|
|
|
|
getStaffByUsername(username) {
|
|
const row = db.select().from(staff).where(eq(staff.username, username)).get()
|
|
return Promise.resolve(row ? toStaff(row) : null)
|
|
},
|
|
|
|
createStaff(input) {
|
|
const hashed = bcrypt.hashSync(input.password, 10)
|
|
const created = db.insert(staff).values({
|
|
name: input.name,
|
|
username: input.username,
|
|
email: input.email ?? null,
|
|
mobile: input.mobile ?? null,
|
|
addedOn: input.added_on,
|
|
password: hashed,
|
|
isPasswordResetNeeded: input.is_password_reset_needed ?? true,
|
|
}).returning().get()
|
|
return Promise.resolve(toStaff(created))
|
|
},
|
|
|
|
async verifyPassword(s, password) {
|
|
return bcrypt.compare(password, s.password)
|
|
},
|
|
}
|
|
|
|
return { repo }
|
|
}
|