ExeRhythm
ExeRhythm

Reputation: 480

Swift - Return a string in a POST request with Vapor 3

I have a problem where the user needs to post a new order via POST request. The server needs to return an ID of an order, so the front-end code can check if the order was accepted. How can I do so?

This is my code:

router.post("postNewOrder") { req -> Future<HTTPStatus> in
    print(req)
    return try req.content.decode(OrderRequest.self).map(to: HTTPStatus.self) { orderRequest in
        print("latitude: \(orderRequest.latitude), longitude:\(orderRequest.longitude)")

        let newOrder = Order()
        newOrder.latitude = orderRequest.latitude
        newOrder.longitude = orderRequest.longitude

        orders.append(newOrder)

        return "1234abcd"
    }
}

Thanks in advance :)

Upvotes: 2

Views: 366

Answers (1)

imike
imike

Reputation: 5656

First of all change return type to Future<String>

Then if you don't use any databases but just some orders array

router.post("postNewOrder") { req -> Future<String> in
    return try req.content.decode(OrderRequest.self).map { orderRequest in
        let newOrder = Order()
        newOrder.latitude = orderRequest.latitude
        newOrder.longitude = orderRequest.longitude
        orders.append(newOrder)
        return "\(newOrder.id)"
        // if id is String then simply
        // return newOrder.id
        // if id is UUID then this way
        // return newOrder.id.uuidString
    }
}

Or if you use Fluent then you have to save a new order into database

router.post("postNewOrder") { req -> Future<String> in
    return try req.content.decode(OrderRequest.self).flatMap { orderRequest in
        let newOrder = Order()
        newOrder.latitude = orderRequest.latitude
        newOrder.longitude = orderRequest.longitude
        return newOrder.create(on: req).map { newOrder in
            return "\(newOrder.requireID())"
            // if id is String then simply
            // return newOrder.id
            // if id is UUID then this way
            // return newOrder.requireID().uuidString
        }
    }
}

You also can change return type to Int or UUID depending on which type you use for \Order.id

Also you can return some struct like this

struct NewOrderResponse: Content {
    let id: UUID // or String, Int, etc.
}

Upvotes: 3

Related Questions