// // cntrlOilSample.swift // // // Created by Michiel Carman on 4/5/2024. // import Fluent import Vapor import Crypto struct cntrlOilSample: RouteCollection { func boot(routes: RoutesBuilder) throws { let rts = routes.grouped("oilsamples") rts.get(use: index) rts.get(":x", use: read) rts.post(use: create) rts.delete(":x", use: delete) //Additional routs added here } func index(req: Request) async throws -> Response { guard let obj = try? await mdlOilSample.ObjQuery(req: req).all() else { throw Abort(.badGateway, reason: "Something went wrong with this api.") } guard let response = try? await obj.encodeResponse(status: .ok, for: req) else{ throw Abort(.noContent, reason: "Something went wrong decoding data. Array could not be shown.") } return response } func read(req:Request) async throws -> Response{ guard let obj = try? await mdlOilSample.ObjQuery(req: req).first() else{ throw Abort(.notFound, reason: "OilSample was not found.") } guard let response = try? await obj.encodeResponse(status: .ok, for: req) else { throw Abort(.noContent, reason: "Something went wrong decoding object.") } return response } func create(req: Request) async throws -> Response { guard let obj = try? req.content.decode(mdlOilSample.self) else { throw Abort(.notAcceptable, reason: "OilSample json not formatted correctly or is missing parents.") } var exists = false if(obj.id != nil){ obj._$idExists = true exists = true } guard let _ = try? await obj.save(on: req.db) else{ throw Abort(.conflict, reason: "Something conflicts in the database. OilSample cannot be saved.") } guard let response = try? await obj.encodeResponse(status: exists ? .accepted : .created, for: req) else{ throw Abort(.noContent, reason: "Something went wrong decoding data. OilSample has been saved.") } return response } func delete(req: Request) async throws -> Response { guard let obj = try? await mdlOilSample.ObjQuery(req: req).first() else { throw Abort(.notFound, reason: "OilSample's ID was not supplied. OilSample will not be deleted") } guard let _ = try? await obj.delete(on: req.db) else{ throw Abort(.conflict, reason: "There was a conflict deleting OilSample. Make sure it has not children.") } guard let response = try? await obj.encodeResponse(status: .ok, for: req) else{ throw Abort(.noContent, reason: "Something went wrong decoding data. OilSample has been deleted.") } return response } }