25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 

70 satır
2.3 KiB

  1. //
  2. // FuelEntryController.swift
  3. //
  4. //
  5. // Created by Bill Ryckman on 4/24/23.
  6. //
  7. import Vapor
  8. struct FuelEntryV2Controller: RouteCollection {
  9. func boot(routes: RoutesBuilder) throws {
  10. let fuelEntries = routes.grouped("fuel_entries")
  11. fuelEntries.get(use: index)
  12. fuelEntries.post(use: create)
  13. fuelEntries.post("upload-image", use: uploadImage)
  14. fuelEntries.group(":fuelEntryID") { fuelEntry in
  15. fuelEntry.delete(use: delete)
  16. }
  17. }
  18. func index(req: Request) async throws -> [FuelEntry] {
  19. try await FuelEntry.query(on: req.db).all()
  20. }
  21. //Need to create image file path at time of FuelEntry creation. UploadImage to store file appropriately
  22. func create(req: Request) async throws -> [FuelEntry] {
  23. let fuelEntry = try req.content.decode([FuelEntry].self)
  24. try await fuelEntry.create(on: req.db)
  25. return fuelEntry
  26. }
  27. func delete(req: Request) async throws -> HTTPStatus {
  28. guard let fuelEntry = try await FuelEntry.find(req.parameters.get("fuelEntryID"), on: req.db) else {
  29. throw Abort(.notFound)
  30. }
  31. try await fuelEntry.delete(on: req.db)
  32. return .noContent
  33. }
  34. func uploadImage(req: Request) async throws -> FuelEntry {
  35. let fuelEntryID: UUID = try req.parameters.require("id")
  36. let file = try await req.content.decode(File.self)
  37. let filename = fuelEntryID.uuidString + ".png" // Generate a unique filename for the uploaded image
  38. let directory = DirectoryConfiguration.detect().workingDirectory + "Images/"
  39. if let imageData = file.data.getData(at: 0, length: file.data.readableBytes) {
  40. do {
  41. try Data(imageData).write(to: URL(fileURLWithPath: directory + filename)) // Save the uploaded image to server
  42. } catch {
  43. throw Abort(.internalServerError, reason: "Failed to save image file")
  44. }
  45. // Update FuelEntry model after saving the image
  46. if let fuelEntry = try await FuelEntry.find(fuelEntryID, on: req.db) {
  47. return fuelEntry
  48. } else {
  49. throw Abort(.notFound, reason: "FuelEntry not found")
  50. }
  51. } else {
  52. throw Abort(.badRequest, reason: "Failed to extract image data")
  53. }
  54. }
  55. }