|
- //
- // cntrlModel.swift
- //
- //
- // Created by Michiel Carman on 4/5/2024.
- //
-
- import Fluent
- import Vapor
- import Crypto
-
-
-
- struct cntrlModel: RouteCollection {
- func boot(routes: RoutesBuilder) throws {
- let rts = routes.grouped("models")
- 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 mdlModel.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 mdlModel.ObjQuery(req: req).first() else{
- throw Abort(.notFound, reason: "Model 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(mdlModel.self) else {
- throw Abort(.notAcceptable, reason: "Model 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. Model 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. Model has been saved.")
- }
- return response
- }
-
-
- func delete(req: Request) async throws -> Response {
- guard let obj = try? await mdlModel.ObjQuery(req: req).first() else {
- throw Abort(.notFound, reason: "Model's ID was not supplied. Model will not be deleted")
- }
- guard let _ = try? await obj.delete(on: req.db) else{
- throw Abort(.conflict, reason: "There was a conflict deleting Model. 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. Model has been deleted.")
- }
- return response
- }
- }
|