feat: Begins breaking out database interfaces and api controllers into seperate items.
This commit is contained in:
36
Sources/App/DB/UserDB.swift
Normal file
36
Sources/App/DB/UserDB.swift
Normal file
@@ -0,0 +1,36 @@
|
||||
import Fluent
|
||||
import Vapor
|
||||
|
||||
struct UserDB {
|
||||
|
||||
func create(_ model: User.Create, on db: any Database) async throws -> User.DTO {
|
||||
guard model.password == model.confirmPassword else {
|
||||
throw Abort(.badRequest, reason: "Passwords did not match.")
|
||||
}
|
||||
let user = try User(
|
||||
username: model.username,
|
||||
email: model.email,
|
||||
passwordHash: Bcrypt.hash(model.password)
|
||||
)
|
||||
try await user.save(on: db)
|
||||
return user.toDTO()
|
||||
}
|
||||
|
||||
func login(user: User, on db: any Database) async throws -> UserToken {
|
||||
let token = try user.generateToken()
|
||||
try await token.save(on: db)
|
||||
return token
|
||||
}
|
||||
|
||||
func fetchAll(on db: any Database) async throws -> [User.DTO] {
|
||||
try await User.query(on: db).all().map { $0.toDTO() }
|
||||
}
|
||||
|
||||
func delete(id: User.IDValue, on db: any Database) async throws {
|
||||
guard let user = try await User.find(id, on: db) else {
|
||||
throw Abort(.notFound)
|
||||
}
|
||||
try await user.delete(on: db)
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user