Posting a new Todo item

The first step will be to develop a post method to create a Todo item as follows:

/// Post a todo item 
drop.post("postTodo") { request in
guard let id = request.headers["id"]?.int,
let name = request.headers["name"],
let description = request.headers["description"],
let notes = request.headers["notes"],
let completed = request.headers["completed"],
let synced = request.headers["synced"]
else {
return try JSON(node: ["message": "Please include mandatory
parameters"])
}

let todoItem = Todo(todoId: id,
name: name,
description: description,
notes: notes,
completed: completed.toBool()!,
synced: synced.toBool()!)

let todos = TodoStore.sharedInstance
todos.addOrUpdateItem(item: todoItem)

let json: [Todo] = todos.listItems()
return try JSON(node: json)
}

The preceding example is going to create a Todo item. First, we check if the API user is provided with all the necessary HTTP headers with a guard expression and then we use our addOrUpdateItem() method in the TodoStore class to add / update that specific item. In the preceding code example, we needed to convert completed from Bool to String, so we extended the String function as follows and we called toBool() on completed:

extension String { 
func toBool() -> Bool? {
switch self {
case "True", "true", "yes", "1":
return true
case "False", "false", "no", "0":
return false
default:
return nil
}
}
}

We will need to build and run our backend app with the vapor build and vapor run directives in the terminal application. At this point, we should get the following prompt:

If we point to localhost:8080 in a web browser, we should see Vapor up-and-running. Also, we can use the curl tool to test our POST method in the terminal by copying and pasting the following command:

curl -X "POST" "http://localhost:8080/postTodo/" 
-H "Cookie: test=123"
-H "id: 3"
-H "notes: do not forget to buy potato chips"
-H "Content-Type: application/json"
-H "description: Our first todo item"
-H "completed: false"
-H "name: todo 1"
-d "{}"

The result will resemble the following screenshot:

As we can see from the screenshot, we received a JSON response that includes our added Todo item.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset