switch to monorepo structure
This commit is contained in:
62
packages/server/src/user/user.ts
Normal file
62
packages/server/src/user/user.ts
Normal file
@@ -0,0 +1,62 @@
|
||||
import { type User, DEMO_USER } from "@markone/core/user"
|
||||
import { ulid } from "ulid"
|
||||
import { db } from "~/database.ts"
|
||||
|
||||
interface UserWithPassword extends User {
|
||||
password: string
|
||||
}
|
||||
|
||||
const findUserByIdQuery = db.query("SELECT id, username FROM users WHERE id = $userId")
|
||||
|
||||
const findUserByUsernameQuery = db.query("SELECT id, username FROM users WHERE username = $username")
|
||||
const findUserByUsernameWithPwQuery = db.query("SELECT id, username, password FROM users WHERE username = $username")
|
||||
|
||||
const createUserQuery = db.query("INSERT INTO users(id, username, password) VALUES ($id, $username, $password)")
|
||||
|
||||
function findUserByUsername(username: string, opts: { password: true }): UserWithPassword | null
|
||||
function findUserByUsername(username: string, { password }: { password?: boolean }): User | UserWithPassword | null {
|
||||
const row = (password ? findUserByUsernameWithPwQuery : findUserByUsernameQuery).get({ username })
|
||||
if (!row) {
|
||||
return null
|
||||
}
|
||||
return row as User
|
||||
}
|
||||
|
||||
function findUserById(userId: string): User | null {
|
||||
const row = findUserByIdQuery.get({ userId })
|
||||
if (!row) {
|
||||
return null
|
||||
}
|
||||
return row as User
|
||||
}
|
||||
|
||||
function createUser(username: string, password: string): User {
|
||||
const userId = ulid()
|
||||
createUserQuery.run({
|
||||
id: userId,
|
||||
username,
|
||||
password,
|
||||
})
|
||||
return {
|
||||
id: userId,
|
||||
username,
|
||||
}
|
||||
}
|
||||
|
||||
async function createDemoUser() {
|
||||
const row = findUserByUsernameQuery.get({ username: DEMO_USER.username })
|
||||
if (row) {
|
||||
return
|
||||
}
|
||||
|
||||
const hashedPassword = await Bun.password.hash(DEMO_USER.unhashedPassword, "argon2id")
|
||||
|
||||
createUserQuery.run({
|
||||
id: DEMO_USER.id,
|
||||
username: DEMO_USER.username,
|
||||
password: hashedPassword,
|
||||
})
|
||||
}
|
||||
|
||||
export type { User }
|
||||
export { DEMO_USER, createDemoUser, createUser, findUserByUsername, findUserById }
|
Reference in New Issue
Block a user