feat: Begins breaking out database interfaces and api controllers into seperate items.
This commit is contained in:
52
Sources/App/Controllers/Api/VendorApiController.swift
Normal file
52
Sources/App/Controllers/Api/VendorApiController.swift
Normal file
@@ -0,0 +1,52 @@
|
||||
import Fluent
|
||||
import Vapor
|
||||
|
||||
struct VendorApiController: RouteCollection {
|
||||
private let vendors = VendorDB()
|
||||
|
||||
func boot(routes: any RoutesBuilder) throws {
|
||||
let protected = routes.apiProtected(route: "vendors")
|
||||
protected.get(use: index(req:))
|
||||
protected.post(use: create(req:))
|
||||
protected.group(":id") {
|
||||
$0.put(use: update(req:))
|
||||
$0.delete(use: delete(req:))
|
||||
}
|
||||
}
|
||||
|
||||
@Sendable
|
||||
func index(req: Request) async throws -> [Vendor.DTO] {
|
||||
let params = try req.query.decode(VendorsIndexQuery.self)
|
||||
return try await vendors.fetchAll(withBranches: params.branches, on: req.db)
|
||||
}
|
||||
|
||||
@Sendable
|
||||
func create(req: Request) async throws -> Vendor.DTO {
|
||||
try Vendor.Create.validate(content: req)
|
||||
let model = try req.content.decode(Vendor.Create.self)
|
||||
return try await vendors.create(model, on: req.db)
|
||||
}
|
||||
|
||||
@Sendable
|
||||
func update(req: Request) async throws -> Vendor.DTO {
|
||||
guard let id = req.parameters.get("id", as: Vendor.IDValue.self) else {
|
||||
throw Abort(.badRequest, reason: "Vendor id not provided.")
|
||||
}
|
||||
try Vendor.Update.validate(content: req)
|
||||
let updates = try req.content.decode(Vendor.Update.self)
|
||||
return try await vendors.update(id: id, with: updates, on: req.db)
|
||||
}
|
||||
|
||||
@Sendable
|
||||
func delete(req: Request) async throws -> HTTPStatus {
|
||||
guard let id = req.parameters.get("id", as: Vendor.IDValue.self) else {
|
||||
throw Abort(.badRequest, reason: "Vendor id not provided.")
|
||||
}
|
||||
try await vendors.delete(id: id, on: req.db)
|
||||
return .ok
|
||||
}
|
||||
}
|
||||
|
||||
struct VendorsIndexQuery: Content {
|
||||
let branches: Bool?
|
||||
}
|
||||
Reference in New Issue
Block a user