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

79 строки
2.7 KiB

  1. //
  2. // cntrlGate.swift
  3. //
  4. //
  5. // Created by Michiel Carman on 4/5/2024.
  6. //
  7. import Fluent
  8. import Vapor
  9. import Crypto
  10. struct cntrlGate: RouteCollection {
  11. func boot(routes: RoutesBuilder) throws {
  12. let rts = routes.grouped("gates")
  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 mdlGate.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 mdlGate.ObjQuery(req: req).first() else{
  30. throw Abort(.notFound, reason: "Gate 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(mdlGate.self) else {
  39. throw Abort(.notAcceptable, reason: "Gate 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. Gate 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. Gate has been saved.")
  51. }
  52. return response
  53. }
  54. func delete(req: Request) async throws -> Response {
  55. guard let obj = try? await mdlGate.ObjQuery(req: req).first() else {
  56. throw Abort(.notFound, reason: "Gate's ID was not supplied. Gate 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 Gate. 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. Gate has been deleted.")
  63. }
  64. return response
  65. }
  66. }