Getting Started with Server-Side Swift Using the Vapor Web Framework

Continued from page 3. 

You could of course filter by specific attributes, and as a homework assignment, go ahead and try manipulating the queries, like as follows:

Store.query().filter("name", "Apple Store Union Square")

Setting up the Model

In the previous example, you referred to the object Store, which is in fact the model you haven't created yet. Go ahead and rename the existing model Post.swift to Store.swift, replacing the contents of the file with the following:

import Vapor
import Fluent
import Foundation

final class Store: Model {
    var id: Node?       // (1)
    var address: String
    var name: String

    init(node: Node, in context: Context) throws {      //(2)
        id = try node.extract("id")
        name = try node.extract("name")
        address = try node.extract("address")
    }

    func makeNode(context: Context) throws -> Node {    //(3)
        return try Node(node: [
            "id": id,
            "name": name,
            "address": address
        ])
    }
}

extension Store: Preparation {                       // (4)
    static func prepare(_ database: Database) throws {
        //
    }

    static func revert(_ database: Database) throws {   //(5)
        //
    }
}

Let's go through and explain what is happening in the above code:

  1. Start off by adding the Store attributes you want in the table, which in your case is quite simple, address and name
  2. Your initialization method has a fixed parameter signature, passing in a node, which you use to extract the individual properties of the table, with the possibility that any of the extractions could fail. You set the results to your current instance, and ultimately create your model from the persisted data
  3. Another method you'll need is the makeNode() method, which returns all the attributes you have. This method also tells the app how to save the data back to your database
  4. Prepare() and
  5. Revert() are optional methods and are mostly used for SQL-based databases, as a way to create and revert the database schemas. In your case since you are using MongoDB, you don't have to worry about it

Building and Testing the App Locally

Before you push this out to your Heroku site, you'll first build the app to make sure its working without any errors:

vapor build

If everything compiles correctly, you'll proceed to running your app, by typing in terminal the following:

vapor run

It should produce an output similar to:

No preparations.
Server 'default' starting at 0.0.0.0:8080

Testing the API

On your browser, go to 0.0.0.0:8080/stores, or via curl:

curl -X "GET" "http://0.0.0.0:8080/stores" \
     -H "Content: application/json"

If everything worked as planned, you should get the following response:

HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Date: Sun, 22 Jan 2017 18:23:19 GMT
Content-Length: 355

[{"address":"1301 Burlingame Ave, Burlingame, CA 94010","id":"5884f64fe35f462259939c53","name":"Apple Store Burlingame"},{"address":"300 Post St, San Francisco, CA 94108","id":"5884f64fe35f462259939c54","name":"Apple Store Union Square"},{"address":"340 University Ave, Palo Alto, CA 94301","id":"5884f64fe35f462259939c55","name":"Apple Store Palo Alto"}]

This is all fine and well, but you want to deploy your code somewhere others can see it, beyond your personal development environment. There are dozens of options for you to host your app, such as on AWS or other servers, but in this tutorial, you are going to demonstrate how easy it is through Heroku to generate a server to host your Vapor-app.

Deploying to Heroku

You now have a working API on your local environment, and your final step is to deploy your application to Heroku, which you designated as your server to host. In the command line, type:

$ vapor heroku init

Follow the prompts and it will create a heroku instance for you to work with, and if you answered yes to push to Heroku now, it will push your code to the Heroku server. Be sure to note your Heroku server instance. Once it finishes pushing to Heroku, you can test the endpoints by doing a curl to the following:

curl -X "GET" "https://sheltered-island-95773.herokuapp.com/stores" \
     -H "Content: application/json"

Replace https://sheltered-island-95773.herokuapp.com with your heroku server instance.

Final Thoughts

As you can see, Vapor and other Swift server-side frameworks provide a powerful platform for iOS developers to use their existing skill sets to deploy a Swift-developed server to interact with their apps, without the need for an additional web developer.

By choosing Vapor over Node.js, or a mobile SaaS platform like Firebase, which may or may not be around in the near future, development firms can use their existing dev resources own their back-end code, while maintaining complete control of the entire technology stack and environment. Granted, server-side Swift is still maturing with the level of industry-level interest pushed by not only the wider development community, but by the technology giants Apple and IBM (with Kitura), and with the current velocity of evolution, we should see 2017 as the year of server-side Swift. It will move from being a fringe-solution toward a more mainstream solution for development shops.

In this tutorial, you went through the concepts of one such platform, Vapor, and saw how easy working with the framework is, connecting it to a database, and hosting it on a server, such as Heroku. For any Swift-developer this tutorial should serve as a really simple example of how one can use her or his existing iOS client-side skills to become a full-stack developer.

You can download the entire source code for this tutorial, by going to the following Github repo page.

Some Helpful Resources

Doron Katz A keen passion for emerging technologies, practices and methodologies, Doron embraces the vision of lean development with continuous customer development. Consultant for various startups, as a Project and Product Manager, with a mobile engineering background in iOS, and over 10 years of professional web development experience.
 

Comments

Comments(2)

phani2

Hi , am able to successfully create the user but am not able to acces the console for stores db with the following command  >mongo -u myTester -p xyz123. I get this error  E QUERY    [main] SyntaxError: missing ; before statement @(shell):1:9

Am new to mongodb, any help appreciated. Thanks