Our mobile apps are exploding! Our software and devices add more functionality, components, and sensors with every new revision, which also increases up the size and complexity of our software.
This complexity drives larger the amounts of data we must persist and store in our mobile apps. Therefore our databases are becoming more complicated and our data models are getting bigger.
OrientDB is an enterprise multi-model database solution with many advantages over traditional relational databases.
OrientDB is a solid platform that was launched in 2010 and is a leading database option in terms of innovative features & performance.
Plus, it has an HTTP REST API available out-of-the-box that our iOS apps can immediately begin communicating with.
1. 8/26/2017 Write Your Mobile App With a Graph Database backend
https://medium.com/mobile-growth/mobile-app-graph-db-a11638897a15 1/23
ApplausefromLucaGarulliand3others
AnthonyBlatner
Ilovetech,austin&tacos|#Marketing#Media#Growth#Online#Startups#Fitness#Traveling|Di…
Aug15 · 11minread
WriteYourMobileAppWithaGraph
Database backend
Out-of-the-box Database HTTP REST API and E-Commerce
App
Mobile apps are growing, literally. Our apps and devices add more
functionality, components, and sensors with each generation, which
also drives up the size and complexity of our applications.
This complexity influences the amount of data we must persist and
store in our apps.That means our databases are getting bigger and our
data models are getting more complicated.
For storage on iOS, simple key-value plists don’t cut it for most
applications. CoreData is known to be finnicky and resorting to SQLite
is usually necessary.
And then what about server side? There are many options out there
and solutions are constantly evolving. Parse was a go-to platform for
2. 8/26/2017 Write Your Mobile App With a Graph Database backend
https://medium.com/mobile-growth/mobile-app-graph-db-a11638897a15 2/23
a while until Facebook discontinued and open-sourced it, while
Google acquired Firebase.
If you’re working on an enterprise mobile application, this volatile
database environment remains questionable. How will you plan to
support your app in a year or two from now? Often, this is why it it
can be risky to choose a new technology to use in your stack.
. . .
OrientDB
I’m continuing to implement and test OrientDB in my applications,
and I have been happy with its performance. OrientDB is an
established platform that has been around since 2010, yet is a leading
database solution in terms of modern features and performance.
OrientDB is an enterprise multi-model database solution with many
advantages over traditional relational databases.
Plus, it has an HTTP REST API available out-of-the-box that our
mobile apps can immediately start interacting with.
If you want to learn more about OrientDB and it’s REST API before we
dive into iOS implementation, visit my earlier tutorial on here.
Intro tutorial here:
OrientDBIntro&HTTPRESTAPI
AnE‑CommerceCaseStudy
medium.com
. . .
ComputerStoreMobile App
3. 8/26/2017 Write Your Mobile App With a Graph Database backend
https://medium.com/mobile-growth/mobile-app-graph-db-a11638897a15 3/23
Here, we’ll simulate developing an e-commerce mobile app for our
“ComputerStore”, continued from our first tutorial. If you haven’t
already, I suggest reviewing the use cases and data model in that
tutorial. We’ll be writing this in Swift using XCode 8 on iOS 10.
As a quick refresher, our store will be selling six different products:
Apple MacBook Pro
Samsung Galaxy Phone
Dell Inspiron Desktop
8 GB Memory
16 GB Memory
Accelerometer
These Products have relationships of their Components and other
Products that they are CompatibleWith, using graph Edges.
In the last tutorial, we analyzed each request and response pair that
our ComputerStore would need to interact with our database via the
HTTP REST API. Our mobile app will leverage the same HTTP REST
API from the first tutorial, and we will walk through implementing
that API on iOS.
1.
2.
3.
4.
5.
6.
4. 8/26/2017 Write Your Mobile App With a Graph Database backend
https://medium.com/mobile-growth/mobile-app-graph-db-a11638897a15 4/23
We outlined a series of user stories that any e-commerce store would
need to implement to create a successful user journey. If a customer
downloads our app, we want to allow them to sign-in, see our
products, make a purchase, and view their orders.
Those user stories are:
A user opens our store app and wants to sign-in. (Connect)
A user views our catalogue of products. (Products)
A user drills down to view the components of a product.
(Components)
A user decides to make a purchase. (CreateOrder)
A user wants to see their orders. (Orders)
Visually, the user journey would look like this:
Translating that user journey into a storyboard for our app. We’ll need
the following view controllers.
Storyboard&ViewControllers
A user opens our store app and wants to sign-in:
LoginViewController
A user enters the store and views options: MainViewController
A user views our catalogue of products.
ProductsTableViewController
•
•
•
•
•
1.
2.
3.
5. 8/26/2017 Write Your Mobile App With a Graph Database backend
https://medium.com/mobile-growth/mobile-app-graph-db-a11638897a15 5/23
A user drills down to view the components of a product:
ProductDetailViewController
A user decides to make a purchase:
ProductDetailViewController
A user wants to see their orders: OrdersTableViewController
We’ll also create Swift classes to represent the objects in our Products
and Orders tables:
Product
Order
Finally, our views and view controllers will share information stored
in Globals.swift, which we’ll use for simplicity. If we were building an
enterprise application, we would like want to implement a more
robust StoreManager class.
Users
We won’t implement a registration process here, so to start, create a
couple customer users in your OrientDB database with full
permissions. In a production application, you’d want to limit the
access control to only what is necessary.
We’ll use these users to login and associate with their orders.
4.
5.
6.
•
•
6. 8/26/2017 Write Your Mobile App With a Graph Database backend
https://medium.com/mobile-growth/mobile-app-graph-db-a11638897a15 6/23
ProjectSetup
Now, let’s head over to XCode to start building our app. Create a new
project. We can start with a Single View Application. Set the language
to Swift and we’ll set our device to iPhone.
If you’re new to iOS development, it may be useful to follow along
with the code in our GitHub repository, here:
https://github.com/ablatner88/OrientDBTutorial-Swift
*When downloading the project, you will likely need to
use Cocoapods or download the associated libraries
as well*
ComputerStore‑GitHub
iOSE‑CommerceAppwithaGraphDatabase
Backend
github.com
OrientDB Studio
7. 8/26/2017 Write Your Mobile App With a Graph Database backend
https://medium.com/mobile-growth/mobile-app-graph-db-a11638897a15 7/23
There’s a few iOS libraries that we’ll be using to help us interact with
the API. These are common in iOS. Either download via CocoaPods or
manually install these into your project.
https://github.com/Alamofire/Alamofire—“Elegant HTTP
Networking in Swift” that helps with networking.
https://github.com/Alamofire/AlamofireImage—Component
library of Alamofire with handy image networking functions.
•
•
8. 8/26/2017 Write Your Mobile App With a Graph Database backend
https://medium.com/mobile-growth/mobile-app-graph-db-a11638897a15 8/23
https://github.com/SwiftyJSON/SwiftyJSON—Simplifies our
parsing of JSON
We’ll start by laying out the Storyboard that we’ll use for our app.
XCode’s Interface Builder is a great drag and drop UI tool. We’ll have
an initial login screen LoginViewController. Upon login, we’ll
navigate to the Welcome screen, MainViewController. From the
Welcome screen, the user can view the product catalogue,
ProductsTableViewController and drill down and see more
information about a product, ProductDetailViewController. Also
from the Welcome screen, the user can navigate to viewing their
orders, OrdersTableViewController.
Additionally, we’ll embed our app in a UINavigationController which
will help slide our view controllers in and out.
Globals.swift
As we navigate around our app, there’s some information our views
will need to share. That info is the location URL of our API, the
username, password, and userRid of our customer, and finally our
catalog of products.
Note that we will maintain our list of products in memory as a
Dictionary<String,Product>. This will allow us to look up each
product by its RID.
•
Storyboard of the nal app
10. 8/26/2017 Write Your Mobile App With a Graph Database backend
https://medium.com/mobile-growth/mobile-app-graph-db-a11638897a15 10/23
Make sure to import Alamofire and import SwiftyJSON at the top of
the login class to use these functions.
12. 8/26/2017 Write Your Mobile App With a Graph Database backend
https://medium.com/mobile-growth/mobile-app-graph-db-a11638897a15 12/23
In our Globals.swift, we set the baseURL to the location of our API.
Therefore we can use baseURL() + “<endpoint>” for our requests.
The connect call is to first make sure we can connect to our database
and to verify the login credentials.
On successful login, we also need to lookup the RID of our customer.
This RID will be later used when we’re making a purchase and
looking up our user’s orders.
We’ll store this information about our visitor’s username, password,
and userRid in the Globals.swift variables for later use.
Finally, if we perform a successful login, we will then navigate to the
MainViewController. We use the storyboard constructor and
navigation pushViewController methods to do so.
Note that in your storyboard, you must also define the Storyboard ID
for these view controllers.
42
43
44
45
46
47
48
49
50
51
52
53
let getUserString = baseURL() + "/query/ComputerStore/sql/SELECT from OU
let escapedUserString = getUserString.addingPercentEncoding
Alamofire.request(escapedUserString!).validate
switch response.result {
case .success (let value):
print("‐‐‐Response Received‐‐‐"
print("Request: (String(describing
print("Result: (response.result
if let json = response.result.value
print("JSON: (json)")
}
13. 8/26/2017 Write Your Mobile App With a Graph Database backend
https://medium.com/mobile-growth/mobile-app-graph-db-a11638897a15 13/23
2.MainViewController:Auserentersthe
storeandviews options
Next is the Welcome screen of our app, where we’ll present options to
the user to view our catalog or view their orders.
ViewProducts
//GET http://{{server}}:
{{port}}/query/{{database}}/{{language}}/SELECT from
PRODUCTS
let requestString = baseURL() +
“/query/ComputerStore/sql/SELECT from PRODUCTS”
let escapedString =
requestString.addingPercentEncoding(withAllowedCharacters:
.urlQueryAllowed)
Alamofire.request(escapedString!).validate().responseJSON {
response in …}
Construct the API endpoint using baseURL() again. Here we must be
sure to use the convenience function
MainViewController
14. 8/26/2017 Write Your Mobile App With a Graph Database backend
https://medium.com/mobile-growth/mobile-app-graph-db-a11638897a15 14/23
requestString.addingPercentEncoding(…) since our request string
has spaces in “SELECT from PRODUCTS”.
Again we will validate() our response and parse the JSON.
Now that we are receiving Product records from the database, we will
want to implement our Product class on client side. This is a simple
data storage class with the same fields as the database. It is important
to understand the convenience init(productJSON: JSON){…} that
is written to accept the JSON response from the server and unpack it
into a new object.
Keep in mind that a Product has relationships for Components and
CompatibleWith. These are edges, and edges have their own RIDs.
Therefore, the RIDs that the REST API returns to us are for the edges
which point to those Products, not the RIDs of the Products
themselves.
Additionally, we convert those Components and CompatibleWith
fields from Swift JSON type to Swift Array<String> type using the
following syntax:
productJSON[“out_Components”].arrayValue.map({$0.stringValue})
Back in our MainViewController, we then store the product, by it’s
RID, in our global product dictionary using products[rid] =
productObject
Once all of the products have been unpacked and stored, we then
instantiate and push our ProductsTableViewController to display
those products.
ViewOrders
Alternatively in this view, the user can select to view their orders.
To do this, we query and traverse the HasOrder edges which point to
our User RID, which we retrieve using the expand(out(…)) modifier
to receive the Order records.
//GET http://localhost:2480/query/ComputerStore/sql/SELECT
expand(out(“HasOrder”)) from 5:0
15. 8/26/2017 Write Your Mobile App With a Graph Database backend
https://medium.com/mobile-growth/mobile-app-graph-db-a11638897a15 15/23
let userRidTrim = userRid?.trimmingCharacters(in: [“#”])
let requestString = baseURL() +
“/query/ComputerStore/sql/SELECT expand(out(”HasOrder”))
from “ + userRidTrim!
let escapedString =
requestString.addingPercentEncoding(withAllowedCharacters:
.urlQueryAllowed)
Alamofire.request(escapedString!).validate().responseJSON {
response in … }
Note that we receive RIDs in the format of “#5:0”, although if we
include those hash signs in a URL request string it will causes
problems with the HTTP protocol, where pound signs (#) are
interpreted as page anchors. Therefore, we must trim off the “#” and
include only the “5:0”, which OrientDB accepts. Whew.
3.ProductsTableViewController:Auser
viewsourcatalogueofproducts.
We will display our list of products in a UITableViewController. Each
row will display a product’s name and price. In the storyboard, set the
prototype cell Identifier to ProductCell, which allows us to reference
it in programmatically, and set Style to Subtitle, which enables a
detail text label for us to use.
When the customer selects a row from our list of products, we’ll
lookup that product by the row selected and pass it onto the
UITableViewController con guration
16. 8/26/2017 Write Your Mobile App With a Graph Database backend
https://medium.com/mobile-growth/mobile-app-graph-db-a11638897a15 16/23
ProductDetailViewController using its product input to display
more information.
4.ProductDetailViewController:Auser
drillsdowntoviewthecomponentsof
a product.
The product detail view displays all of the product information using
several user interface elements, including a UIImageView, UITextView,
UILabel, and an embedded UITableView.
XCode’s Interface Builder has a handy Assistant Editor view and
ability to drag and connect UI elements to code snippets. Make sure
your UI elements are correctly referenced in their associated Swift
files, and that the Buy button invokes a buy function.
In our viewDidLoad() method, we’ll set all of our UI elements to
display our product’s information. Most of these are text labels.
We must also load the image for the productImageURL that we have.
This is where we will use AlamofireImage’s handy asynchronous
af_setImage(withURL: URL) method.
To display the components, we embed a UITableView inside of our
UIViewController (which is not a UITableViewController), we
XCode Assistant Editor
17. 8/26/2017 Write Your Mobile App With a Graph Database backend
https://medium.com/mobile-growth/mobile-app-graph-db-a11638897a15 17/23
therefore also need to adopt the UITableViewDelegate and
UITableViewDatasource protocols on the top class definition line.
That’s how we define what the table should display and what should
happen when our visitor selects a row.
Remember that our Product object has a componentEdgeRids field,
which holds the RIDs of the edge that points to our components, but
does not have the RIDs of the components themselves. Therefore we
will need to make another request to the OrientDB API to traverse this
edge.
We do that with the following request:
// GET http://{{server}}:
{{port}}/query/{{database}}/{{language}}/SELECT
expand(out(‘Components’)) from <<@rid>>
let requestString =
“http://admin:admin@localhost:2480/query/ComputerStore/sql/s
elect expand(out(‘Components’)) from “ + productRidTrim!
let escapedString =
requestString.addingPercentEncoding(withAllowedCharacters:
.urlQueryAllowed)
Alamofire.request(escapedString!).validate().responseJSON {
response in … }
The response we receive contains the full component products. Since
we already have our Globals.swift dictionary of products, all we
really need is the RIDs of those components.
When a visitor selects a component from the table, we take the RID of
the component that we retrieved and drill down into another
ProductDetailViewController, now passing in this component
product to display its information.
18. 8/26/2017 Write Your Mobile App With a Graph Database backend
https://medium.com/mobile-growth/mobile-app-graph-db-a11638897a15 18/23
5.ProductDetailViewController:Auser
decidestomakeapurchase.
Alternatively in this view, a customer may decide to purchase a
product by pressing the Buy button.
ProductDetailViewController
19. 8/26/2017 Write Your Mobile App With a Graph Database backend
https://medium.com/mobile-growth/mobile-app-graph-db-a11638897a15 19/23
This button invokes our clickBuy() function and prompts the user to
confirm their purchase with an UIAlertController. This alert view has
two actions, where Cancel simply dismisses the popup, and Confirm
invokes our createOrder() function.
The createOrder() function makes a request to our ComputerStore
custom function, CreateOrder, and passes in the RIDs of the product
and the customer. Our first tutorial explains the creation of this
custom function.
let productRidTrim = product?.rid?.trimmingCharacters(in:
[“#”])
let userRidTrim = userRid?.trimmingCharacters(in: [“#”])
// POST http://{{server}}:
{{port}}/function/{{database}}/{{name}}/{{argument1}}/{{argu
ment2}}
// POST
http://localhost:2480/function/ComputerStore/CreateOrder/23:
1/5:0
let requestString =
“http://admin:admin@localhost:2480/function/ComputerStore/Cr
eateOrder/" + productRidTrim! + “/” + userRidTrim!
let escapedString =
requestString.addingPercentEncoding(withAllowedCharacters:
.urlQueryAllowed)
Alamofire.request(escapedString!, method:
.post).validate().responseJSON { response in … }
20. 8/26/2017 Write Your Mobile App With a Graph Database backend
https://medium.com/mobile-growth/mobile-app-graph-db-a11638897a15 20/23
Note that this is a POST request to the API, executed by adding
method: .post to our Alamofire request, since our CreateOrder
function is not idempotent. That means our function makes changes
to the database, and cannot be invoked with a GET request, which are
typically limited to reading data.
If the purchase is successful, we display another popup to the user
which simply says “Thank you for your order”.
6.OrdersTableViewController:Auser
wantstoseetheir orders.
Back to the MainViewController, when a customer selects View
Orders we query the database for any HasOrder edges which point to
our current user.
Here we need to also create our Order class in Order.swift, which is
very similar to our Product class. This Order class also has a
convenience init(orderJSON: JSON) method to unpack a JSON
object into an Order object.
We append each order to an orders array and then push our
OrdersTableViewController, passing in this list.
This table view simply displays a table view of our order RID and
order totalPrice.
21. 8/26/2017 Write Your Mobile App With a Graph Database backend
https://medium.com/mobile-growth/mobile-app-graph-db-a11638897a15 21/23
. . .
And there you have it! We’ve built a (very simple) e-commerce mobile
app using an OrientDB database and it’s out of the box HTTP REST
API.
OrdersTableViewController
22. 8/26/2017 Write Your Mobile App With a Graph Database backend
https://medium.com/mobile-growth/mobile-app-graph-db-a11638897a15 22/23
Hope you found this useful. Feel free to dig through the iOS code on
GitHub leave us your comments and any questions that arise.
. . .
Here are some resources for additional reading:
Intro & HTTP API REST Tutorial:
https://medium.com/@anthonyblatner/orientdb-http-rest-api-
904947dcf14d
OrientDB’s website: http://orientdb.com/
Official Documentation: http://orientdb.com/docs/3.0.x/
GitHub: https://github.com/orientechnologies/orientdb
Alamofire iOS Networking:
https://github.com/Alamofire/Alamofire
Udemy, Getting Started with OrientDB:
https://www.udemy.com/orientdb-getting-started/
•
•
•
•
•
•
23. 8/26/2017 Write Your Mobile App With a Graph Database backend
https://medium.com/mobile-growth/mobile-app-graph-db-a11638897a15 23/23