قالب وردپرس درنا توس
Home / IOS Development / Use of liquid and renewable models in steam

Use of liquid and renewable models in steam



Floating is Damps ORM or object-related mapping tools. It's an abstraction layer between the Damp application and the database, and it's designed to make it easier to work with databases. Using an ORM as Liquid has a number of benefits.

The biggest advantage is that you don't have to use the database directly! When you interact directly with a database, write database queries as strict. These are not type-safe and can be painful to use from Swift.

Liquid distributes you by allowing you to use some of a number of database engines, even in the same app. Finally, you do not need to know how to write questions since you can interact with models on a "dizzy" "way.

Models are the fast representation of your data and are widely used. Models are the objects, such as user profiles, you store and access the database. Floating returns and uses type-safe models when interacting with the database, giving you compilation time security.

In this tutorial, you learn how to use Fluent to store data in steam applications.

Getting Started

] Start by creating a new project using the Vapor Toolbox. In Terminal, enter the following commands:

  cd ~ / damp
steam new TILApp

The first command takes you into a directory called steam in your home directory, and assumes that you have completed the steps in "Time Guide with server-side Swift using Vapor".

The second command creates a new Steam 3 project called TILApp using the default template.

 New TILApp project

The template gives examples of files for models and controllers. You want to build your own, then delete the examples. In Terminal, enter:

  cd TILApp
rm -rf Sources / App / Models / *
rm -rf Sources / App / Controllers / *

Since Xcode projects can be discarded using Damp – they are completely optional – it is best practice to create project files outside of Xcode. This allows Swift Package Manager used by the Vapor Toolbox to make sure they connect to the right targets. Create a file to hold Acronym model:

  touch Sources / App / Models / Akronym.swift

This command creates a Swift file in the App module Models directory called Acronym.swift . Now generate your Xcode project:

  steam xcode -y

This will open the project in Xcode.

open configure.swift in the folder App find the group Configure migrations and the following line:

  migrations.add (model: Todo.self, database: .sqlite)

Next, open routes. Swift and the following lines:

  // Example of configuring a controller
la todoController = TodoController ()
router.get ("todos", use: todoController.index)
router.post ("todos", use: todoController.create)
router.delete ("todos", Todo.parameter, use: todoController.delete)

This removes the remaining references to the model's model and controls.

Create the model

Open Akronym.swift and add the following to create the basic model of the acronym:

 ] import steam
import FluentSQLite

Last Class Acronym: Codable {
was id: Int?
was short: String
was long: strict

init (short: string, long: string) {
self.short = short
self.long = long
}
}

The model contains two String properties to hold acronym and its definition. It also contains an optional id property that stores the model ID, if one is set.

All floating models must comply with Codable . It is also good practice to mark classes finally where possible, as it provides a benefit advantage. The ID is set by the database when the acronym is stored.

Next Mark Acronym corresponds to Fluent's Model . At the end of the file, add the following:

  Extension Acronym: Model {
// 1
typealias Database = SQLiteDatabase
// 2
type alias ID = Int
// 3
public static was idKey: IDKey = Acronym.id
}

Here's what this does:

  1. Tells fluently which database to use for this model. The template is already configured to use SQLite.
  2. Tells Floating what type of ID is.
  3. Tells floating key path to the model's ID property.

But this code can be further improved with SQLiteModel . Replace:

  extension Acronym: Model {
typealias Database = SQLiteDatabase
type alias ID = Int
public static was idKey: IDKey = Acronym.id
}

with the following:

  extension Acronym: SQLiteModel {}

Floating packages provide Model help protocols for each database vendor, so you do not need to specify the database or ID types, or key. SQLiteModel protocol must have an ID of the type Int? called id but there is SQLiteUUIDModel and SQLiteStringModel protocols for models with IDs of type UUID or String . To customize the ID property name, you must comply with the standard model protocol.

Creating a table for the model

To save the model in the database, you must create a table for it. Liquid does this with a migration . Transfers make it possible to make reliable, testable, reproducible changes to the database. They are usually used to create a database schema or table description for your models. They are also used to seed data in your database or make changes to your models after they have been stored.

Add the following at the end of Acronym.swift to make the model conform to Migration :

  extension Acronym: Migration {}

That's all you need to do! Liquid gives the form to your model thanks to Codable . For basic models, you can use standard implementations for Migration . If you need to change the model later or do more complex things, such as marking a property as unique, you may need to implement your own migrations.

Now that Acronym complies with Migration you can tell Fluent to create the table when the program starts. Open configure.swift and find the part labeled // Configure migrations . Add the following before services.register (migrations) :

  migrations.add (model: Akronym.self, database: .sqlite)

Floating supports mix multiple databases in a single application, so you specify which database holds each model. Migrations only run once ; Once they have run in a database, they are never driven again. It is important to remember this, as Fluent will not attempt to restore a table if you change the model.

Insert the active form Run with My Mac as the destination. Build and run. Check the console and see that the transfers have run. You should see something similar to the console output below:

 Transmission Complete

Save Models

When the app's user enters a new acronym, you need a way to save it. In Swift 4 and Vapor 3, Codable this becomes trivial. Steam gives Contents a cover around Codable that allows you to convert models and other data between different formats. Acronym.swift and add the following at the end of the file to make Acronym in accordance with Content : [19659020] extension Acronym: Content {}

Acronym is already in accordance with Codable you do not need to add anything else. To create an acronym, the user's browser sends a POST request containing a JSON payload similar to the following:

  {
"short": "OMG",
"long": "Oh my God"
}

You need a route to handle this POST request and save the new acronym. Open routes.swift and add the following to the end of routes (_ :) :

  // 1
router.post ("api", "acronyms") {req -> Future  i
// 2
return try req.content.decode (Acronym.self) .flatMap (to: Akronym.self) {acronym in
// 3
return acronym.save (on: req)
}
}

Here's what you do here:

  1. Register a new route on / api / acronyms that accepts a POST request and returns Future . It returns the acronym when stored.
  1. Decode the request JSON in a Acronym model using Codable . This returns a Future so that it uses a flat folder (to :) to extract the acronym when decoding is completed. In this route manager, call code (_ :) on Request yourself. You then avoid the result as decoder (_ :) returns a Future .
  2. Save the model using Fluent. This returns Future as it returns the model when it is stored.

Fluent and Damps integrated use of Codable makes this easy. Since Acronym matches Content it is easily converted between JSON and Model . This allows Vapor to return the model as JSON in the answer without any effort on your part.

Build and run the program to try it. A good tool to test this is RESTed available as a free download from the Mac App Store. Other tools like Paw and Postman also fit.

In RESTed, you configure the request as follows:

  • URL : http: // localhost: 8080 / api / acronyms
  • method : POST
  • Parameter coding : JSON coded

Add two parameters with names and values:

  • cards : OMG
  • lang : Oh My God

Setting the parameter encoding to The JSON encoded ensures that the data is sent as JSON. It is important to note that this also sets Content-Type header to application / json which tells Vapor that the request contains JSON. If you use another client to send the request, you may need to manually enter this request.

Click Send Request and you will see the acronym stated in the answer. The field id will have a value as it is now stored in the database:

 RESTED response to POST

Where are you going?

You can download the final project for this tutorial with Download Materials button found at the top and bottom of this page.

This tutorial has introduced you to Fluent and how to create models in Steam and save them to a database. If you liked this tutorial, why not check out our full Vapor development book: Server Side Swift with Steam?

If you are a beginner for web development but have been working with Swift for a while, you will find it easy to create robust, full-featured web applications and web APIs with Vapor 3.

Whether you're looking to make a backend for your iOS app, or want to create full-fledged web apps, Vapor is the perfect platform for you.

Questions or comments on this tutorial? Add them in the comments below!


Source link