feat: Begins integrating database client into vapor app.

This commit is contained in:
2025-01-14 11:50:06 -05:00
parent c8bcffa0b5
commit ccf80f05a7
42 changed files with 2378 additions and 2540 deletions

View File

@@ -1,11 +1,13 @@
import DatabaseClient
import Dependencies
import Fluent
import SharedModels
import Vapor
// TODO: Add update and get by id.
struct UserApiController: RouteCollection {
@Dependency(\.users) var users
@Dependency(\.database.users) var users
func boot(routes: any RoutesBuilder) throws {
let unProtected = routes.apiUnprotected(route: "users")
@@ -20,26 +22,28 @@ struct UserApiController: RouteCollection {
}
@Sendable
func index(req: Request) async throws -> [User.DTO] {
func index(req: Request) async throws -> [User] {
try await users.fetchAll()
}
@Sendable
func create(req: Request) async throws -> User.DTO {
func create(req: Request) async throws -> User {
// Allow the first user to be created without authentication.
let count = try await User.query(on: req.db).count()
// let count = try await User.query(on: req.db).count()
let count = try await users.count()
if count > 0 {
guard req.auth.get(User.self) != nil else {
throw Abort(.unauthorized)
}
}
return try await users.create(req.ensureValidContent(User.Create.self))
return try await users.create(req.content.decode(User.Create.self))
}
@Sendable
func login(req: Request) async throws -> UserToken {
func login(req: Request) async throws -> User {
let user = try req.auth.require(User.self)
return try await users.login(user)
return user
// return try await users.login(user)
}
// @Sendable
@@ -50,9 +54,10 @@ struct UserApiController: RouteCollection {
@Sendable
func delete(req: Request) async throws -> HTTPStatus {
guard let id = req.parameters.get("id", as: User.IDValue.self) else {
throw Abort(.badRequest, reason: "User id not provided")
}
// guard let id = req.parameters.get("id", as: User.IDValue.self) else {
// throw Abort(.badRequest, reason: "User id not provided")
// }
let id = try req.ensureIDPathComponent()
try await users.delete(id)
return .ok
}