简体   繁体   中英

How to handle PUT HTTP request in Vapor?

The only way I've found to update a record in Vapor is this:

drop.get("update") { request in

  guard var first = try Acronym.query().first(),
    let long = request.data["long"]?.string else {
    throw Abort.badRequest
  }
  first.long = long
  try first.save()
  return first

}

However it's not a very RESTful way of doing it since it's performing a GET request with a parameter instead of a PUT request.

How does one perform a PUT request in Vapor?

As it turns out, performing PUT, as well as other HTTP methods are as simple as changing .get() or .post() to .put() or any other HTTP methods.

As for my question, to create a PUT function in Vapor, just simply add a .put method that takes an Int (Or String, or any data type you'd like), and accept a JSON (Or whatever format you'd like), and simply update like it's a POST request.

drop.put("update") { request in
  guard var first = try Acronym.query().first(),
    let long = request.data["long"]?.string else {
    throw Abort.badRequest
  }

  first.long = long
  try first.save()

  return first
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM