Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

219 строки
8.0 KiB

  1. //
  2. // FuelEntryController.swift
  3. //
  4. //
  5. // Created by Bill Ryckman on 4/24/23.
  6. //
  7. import Vapor
  8. import FluentKit
  9. struct FuelEntryV2Controller: RouteCollection {
  10. func boot(routes: RoutesBuilder) throws {
  11. let fuelEntries = routes.grouped("fuel_entries")
  12. let tokenAuthMiddleware = Token.authenticator()
  13. let guardMiddleware = User.guardMiddleware()
  14. let tokenAuthGroup = fuelEntries.grouped(tokenAuthMiddleware, guardMiddleware)
  15. tokenAuthGroup.get(use: index)
  16. tokenAuthGroup.get("test", use: filtered)
  17. // fuelEntries.get("with-images", use: getAllEntriesWithImages)
  18. tokenAuthGroup.post(use: create)
  19. // fuelEntries.post("upload-image", use: uploadImage)
  20. tokenAuthGroup.group(":fuelEntryID") { fuelEntry in
  21. fuelEntry.delete(use: delete)
  22. }
  23. }
  24. func index(req: Request) async throws -> [FuelEntry] {
  25. return try await FuelEntry.query(on: req.db).all()
  26. }
  27. struct filteredreturn: Content{
  28. var fuelentries: [FuelEntry]
  29. var pages: Int
  30. }
  31. @Sendable
  32. func filtered(req: Request) async throws -> Response {
  33. var image: Bool
  34. var serial: String
  35. var tank: String
  36. let qstring = req.query
  37. if let qimage = try? qstring.get(Bool.self, at: "image"){
  38. image = qimage
  39. } else {
  40. image = false
  41. }
  42. if let qserial = try? qstring.get(String.self, at: "serial"){
  43. serial = qserial
  44. } else {
  45. serial = ""
  46. }
  47. if let qtank = try? qstring.get(String.self, at: "tank"){
  48. tank = qtank
  49. } else {
  50. tank = ""
  51. }
  52. var query = FuelEntry.query(on: req.db)
  53. if(image){
  54. query = query
  55. .field(\.$id)
  56. .field(\.$timestamp)
  57. .field(\.$userID)
  58. .field(\.$product)
  59. .field(\.$make)
  60. .field(\.$model)
  61. .field(\.$serialNumber)
  62. .field(\.$tankID)
  63. .field(\.$fuelAmount)
  64. .field(\.$fuelType)
  65. .field(\.$isOverride)
  66. .field(\.$latitude)
  67. .field(\.$longitude)
  68. .field(\.$image)
  69. .field(\.$downloaded)
  70. } else {
  71. query = query
  72. .field(\.$id)
  73. .field(\.$timestamp)
  74. .field(\.$userID)
  75. .field(\.$product)
  76. .field(\.$make)
  77. .field(\.$model)
  78. .field(\.$serialNumber)
  79. .field(\.$tankID)
  80. .field(\.$fuelAmount)
  81. .field(\.$fuelType)
  82. .field(\.$isOverride)
  83. .field(\.$latitude)
  84. .field(\.$longitude)
  85. .field(\.$downloaded)
  86. }
  87. if(serial.count > 0){
  88. query = query
  89. .filter(\.$serialNumber == serial)
  90. }
  91. if(tank.count > 0){
  92. query = query
  93. .filter(\.$tankID == tank)
  94. }
  95. if(image){
  96. let wimage = try await query.paginate(for: req).map{
  97. img in FuelEntry.wimage(id: img.id, timestamp: img.timestamp, userID: img.userID, latitude: img.latitude, longitutde: img.longitude, product: img.product, make: img.make, model: img.model, serialNumber: img.serialNumber, tankID: img.tankID, fuelAmount: img.fuelAmount, fuelType: img.fuelType, isOverride: img.isOverride, image: img.image!, downloaded: img.downloaded!)
  98. }
  99. return try await wimage.encodeResponse(for: req)
  100. } else {
  101. let woimage = try await query.paginate(for: req).map{
  102. img in FuelEntry.woimage(id: img.id, timestamp: img.timestamp, userID: img.userID, latitude: img.latitude, longitutde: img.longitude, product: img.product, make: img.make, model: img.model, serialNumber: img.serialNumber, tankID: img.tankID, fuelAmount: img.fuelAmount, fuelType: img.fuelType, isOverride: img.isOverride, downloaded: img.downloaded!)
  103. }
  104. return try await woimage.encodeResponse(for: req)
  105. }
  106. // let result = try await query.paginate(for: req)
  107. // return try await result.encodeResponse(for: req)
  108. }
  109. // func getAllEntriesWithImages(req: Request) async throws -> [FuelEntry] {
  110. // let fuelEntries = try await FuelEntry.query(on: req.db).all()
  111. //
  112. // for var fuelEntry in fuelEntries {
  113. // if let imagePath = fuelEntry.image {
  114. // let fileURL = URL(fileURLWithPath: imagePath)
  115. // if let imageData = try? Data(contentsOf: fileURL) {
  116. // fuelEntry.imageData = imageData
  117. // }
  118. // }
  119. // }
  120. // return fuelEntries
  121. // }
  122. func create(req: Request) async throws -> [FuelEntry] {
  123. let fuelEntry = try req.content.decode([FuelEntry].self)
  124. try await fuelEntry.create(on: req.db)
  125. return fuelEntry
  126. }
  127. //Create with image file written to server storage instead of database
  128. // func create(req: Request) async throws -> [FuelEntry] {
  129. // let fuelEntries = try await req.content.decode([FuelEntry].self)
  130. // let directory = DirectoryConfiguration.detect().workingDirectory + "Images/"
  131. //
  132. // var updatedFuelEntries: [FuelEntry] = []
  133. //
  134. // for fuelEntry in fuelEntries {
  135. // let updatedFuelEntry = try await { () async throws -> FuelEntry in
  136. // var updatedFuelEntry = fuelEntry
  137. //
  138. // if let imageData = updatedFuelEntry.imageData {
  139. // let imageFilename = "\(updatedFuelEntry.id!).png"
  140. // let tempImageURL = URL(fileURLWithPath: directory + imageFilename)
  141. // try await imageData.write(to: tempImageURL)
  142. // updatedFuelEntry.image = tempImageURL.absoluteString
  143. // }
  144. //
  145. // do {
  146. // _ = try await updatedFuelEntry.save(on: req.db)
  147. // return updatedFuelEntry
  148. // } catch {
  149. // throw Abort(.internalServerError, reason: "Error saving FuelEntry: \(error)")
  150. // }
  151. // }()
  152. //
  153. // updatedFuelEntries.append(updatedFuelEntry)
  154. // }
  155. //
  156. // return updatedFuelEntries
  157. // }
  158. func delete(req: Request) async throws -> HTTPStatus {
  159. guard let fuelEntry = try await FuelEntry.find(req.parameters.get("fuelEntryID"), on: req.db) else {
  160. throw Abort(.notFound)
  161. }
  162. try await fuelEntry.delete(on: req.db)
  163. return .noContent
  164. }
  165. // func uploadImage(req: Request) async throws -> FuelEntry {
  166. // let fuelEntryID: UUID = try req.parameters.require("id")
  167. //
  168. // let file = try await req.content.decode(File.self)
  169. // let filename = fuelEntryID.uuidString + ".png" // Generate a unique filename for the uploaded image
  170. // let directory = DirectoryConfiguration.detect().workingDirectory + "Images/"
  171. //
  172. // if let imageData = file.data.getData(at: 0, length: file.data.readableBytes) {
  173. // do {
  174. // try Data(imageData).write(to: URL(fileURLWithPath: directory + filename)) // Save the uploaded image to server
  175. // } catch {
  176. // throw Abort(.internalServerError, reason: "Failed to save image file")
  177. // }
  178. //
  179. // // Update FuelEntry model after saving the image
  180. // if let fuelEntry = try await FuelEntry.find(fuelEntryID, on: req.db) {
  181. // return fuelEntry
  182. // } else {
  183. // throw Abort(.notFound, reason: "FuelEntry not found")
  184. // }
  185. // } else {
  186. // throw Abort(.badRequest, reason: "Failed to extract image data")
  187. // }
  188. // }
  189. }
  190. struct PageRequest: Content {
  191. var page: Int
  192. var size: Int
  193. // Add any other properties needed for pagination
  194. init(page: Int, size: Int) {
  195. self.page = page
  196. self.size = size
  197. }
  198. }