When using a Kitura server, a common requirement is to save and return data. The simplest solution is to store everything on the server, however if the server restarts, the data will be lost. To solve this, we would like to add data persistence by connecting to an SQL database using Swift code. We will use Swift Kuery to make this connection and query process simple.
Introduction to Swift Kuery
Swift Kuery is a pluggable SQL database abstraction layer. Specifically, its aim is to unify the APIs to the various SQL database implementations, providing a Swifty yet SQL-like API. It works alongside a specific database library, such as Swift-Kuery-PostgreSQL or Swift-Kuery-MySQL, to allow a user to query a SQL database in Swift.
Tutorial: Adding a Database
This tutorial provides a step by step guide on how to create, connect and query a PostgreSQL database. For example, storing and retrieving data using Swift SQL INSERT and SELECT queries. The starting point is a completed food tracker application, but don’t worry, if you haven’t previously completed the FoodTrackerBackend tutorial you can simply clone the CompletedFoodTracker branch to get started straight away!
Example code: Adding Persistence to your Server-Side Kitura Application
We have modified our ToDoList Kitura application example (called iOSSampleKituraKit), to store its ToDo list data in a MySQL database. This is achieved by performing a corresponding SQL query for each REST request the server receives. As a result, you can see the power of using the Swift Kuery abstraction layer, by changing a single line of code you can swap the SQL database which the server connects to (for example, changing MySQL for PostgreSQL)!
Any questions or comments? Please join the vibrant Kitura community on Slack!
||Join the discussion on Slack||Learn more at kitura.io||Star Kitura on GitHub|