You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

79 lines
2.8 KiB

  1. //
  2. // cntrlFluid.swift
  3. //
  4. //
  5. // Created by Michiel Carman on 4/5/2024.
  6. //
  7. import Fluent
  8. import Vapor
  9. import Crypto
  10. struct cntrlFluid: RouteCollection {
  11. func boot(routes: RoutesBuilder) throws {
  12. let rts = routes.grouped("fluids")
  13. rts.get(use: index)
  14. rts.get(":x", use: read)
  15. rts.post(use: create)
  16. rts.delete(":x", use: delete)
  17. //Additional routs added here
  18. }
  19. func index(req: Request) async throws -> Response {
  20. guard let obj = try? await mdlFluid.ObjQuery(req: req).all() else {
  21. throw Abort(.badGateway, reason: "Something went wrong with this api.")
  22. }
  23. guard let response = try? await obj.encodeResponse(status: .ok, for: req) else{
  24. throw Abort(.noContent, reason: "Something went wrong decoding data. Array could not be shown.")
  25. }
  26. return response
  27. }
  28. func read(req:Request) async throws -> Response{
  29. guard let obj = try? await mdlFluid.ObjQuery(req: req).first() else{
  30. throw Abort(.notFound, reason: "Fluid was not found.")
  31. }
  32. guard let response = try? await obj.encodeResponse(status: .ok, for: req) else {
  33. throw Abort(.noContent, reason: "Something went wrong decoding object.")
  34. }
  35. return response
  36. }
  37. func create(req: Request) async throws -> Response {
  38. guard let obj = try? req.content.decode(mdlFluid.self) else {
  39. throw Abort(.notAcceptable, reason: "Fluid json not formatted correctly or is missing parents.")
  40. }
  41. var exists = false
  42. if(obj.id != nil){
  43. obj._$idExists = true
  44. exists = true
  45. }
  46. guard let _ = try? await obj.save(on: req.db) else{
  47. throw Abort(.conflict, reason: "Something conflicts in the database. Fluid cannot be saved.")
  48. }
  49. guard let response = try? await obj.encodeResponse(status: exists ? .accepted : .created, for: req) else{
  50. throw Abort(.noContent, reason: "Something went wrong decoding data. Fluid has been saved.")
  51. }
  52. return response
  53. }
  54. func delete(req: Request) async throws -> Response {
  55. guard let obj = try? await mdlFluid.ObjQuery(req: req).first() else {
  56. throw Abort(.notFound, reason: "Fluid's ID was not supplied. Fluid will not be deleted")
  57. }
  58. guard let _ = try? await obj.delete(on: req.db) else{
  59. throw Abort(.conflict, reason: "There was a conflict deleting Fluid. Make sure it has not children.")
  60. }
  61. guard let response = try? await obj.encodeResponse(status: .ok, for: req) else{
  62. throw Abort(.noContent, reason: "Something went wrong decoding data. Fluid has been deleted.")
  63. }
  64. return response
  65. }
  66. }