Hands-On Server-Side Web Development with Swift
上QQ阅读APP看书,第一时间看更新

Using controller for logical operations

For simplicity, your myJournal application persists data in memory. You'll use database operations for permanent data storage later on.

Even though you are not using a database operation, you'll implement the typical Create, Read, Update, and Delete (CRUD) operations for your data. Create the JournalController.swift file in the /Sources/App/Controllers directory:

// Journal controller
import Vapor

final class JournalController {

var entries : Array<Entry> = Array() // [1]

//: Get total number of entries
func total() -> Int { // [2]
return entries.count
}
//: Create a new journal entry
func create(_ entry: Entry) -> Entry? { // [3]
entries.append(entry)
return entries.last
}
//: Read a journal entry
func read(index: Int) -> Entry? { // [5]
if let entry = entries.get(index: index) {
return entry
}
return nil
}
//: Update the journal entry
func update(index: Int, entry: Entry) -> Entry? { // [6]
if let entry = entries.get(index: index) {
entries[index] = entry
return entry
}
return nil
}
//: Delete a journal entry
func delete(index: Int) -> Entry? { // [7]
if let _ = entries.get(index: index) {
return entries.remove(at: index)
}
return nil
}
}

extension Array {
func get(index: Int) -> Element? { // [4]
if index >= 0 && index < count {
return self[index]
}
return nil
}
}

The journalController class performs the following operations:

  • Declares an array to hold all the instances of Entry in memory
  • Returns the number of entries in the array
  • Appends a new Entry item to the array
  • Adds a safe get(index:) function to the Array extension that checks for bounds
  • Retrieves an Entry item identified by a zero-based index from the array
  • Replaces a current item in the array with the supplied Entry item
  • Deletes an item from the array

An array in [1] will be used as in memory persistence and holds the references for all Entry instances. The total() method in [2] gives out the total number of entries in the array. In [4], a safe get(index:) function is implemented as an extension to Array. It checks for the given index against the bounds of entries array. The functions in [3], [5],[6] and [7] implement the CRUD operations on the array.