[Swift] Web Framework - Vapor

Inwoo Hwang·2021년 8월 26일
0

Swift

목록 보기
6/8
post-thumbnail

Vapor란?

Vapor is a web framework for Swift. It provides a beautifully expressive and easy to use foundation for your next website, API, or cloud project

스위프트를 활용하여 서버를 구성할 필요한 프레임워크입니다.

Routes

Route == API Endpoint

Route가 뭔지 너무 헷갈렸는데요 설명을 읽어보니 이제 드디어 이해가 됐어요!

짧게 말하자면 Route는 리소스를 접근할 수 있게 해주는 URL입니다

영화리스트를 접근할 수 있는 Movie API는 아래와 같은 URL을 가질 수 있죠!

https://www.mydomain.com/movies

HTTP GET:

Get all Movies(GET) https://mydomain.com/**movies**

HTTP POST:

Create a Movie(POST) https://mydomain.com/**movies**

HTTP GET:

Get all Movie by ID(GET) https://mydomain.com/**movies/123**

HTTP DELETE:

Delete a Movie(DELETE) https://mydomain.com/**movies/123**

Object Relational Mapper(ORM)


SQL = Structure Query language

It is a domain-specific language used in programming and designed for managing data held in a relational database management system.

what if we want to use the power of swift language or any of the language to use some helper functions to get all the data in the way we want?

Ex: Movie.all() → fetch all data

What is a Relational DataBase?

A relational database is a collection of data items with pre-defined relationships between them. These items are organized as a set of tables with a columns and rows.

What is an ORM?

  • Mapping between Objects and Relational Database

Fluent Driver

We can use the fluent driver to connect the model in swift and the database table together. Meaning we can create the models and classes in swift code that can actually talk to the database. : Performing creation, deletion and etc..

Real benefit: you are not dealing with writing SQL with your hands. you are only dealing with the objects in the classes, whether you are using JavaScript or Java, or Swift

Migration[Fluent]

데이터베이스는 모두 SQL로 동작함 .Fluent가 SQL문을 변환해서 데이터베이스로 날려줌. SQL 없이 데이터베이스는 동작하지 않는다. 이걸 텍스트로 만들어서 날리기에는 너무 장황함. ORM이 매핑 해줌. 마이그레이션의 의미. 없으면 생성하고 있으면 사용. fluent library의 기능적인 것.

to connect vapor app and make sure vapor app is going to create tables in our data base , we need to use Migration

how to connect to database

먼저 Migration을 통해 매핑 해 줄 Swift class를 구현해야합니다.

import Foundation
import Fluent
import FluentPostgresDriver

struct CreateMovie: Migration {
    // upmigration: whatever you will run, whatever you are trying to do, like creating a table, you will do it in a prepare function. Any kind of changes including create, read, update, and delete to the structure of table, it has to be a migration when using fluent.
    // sql문을 날리는 것. prepare가 데이터베이스의 상태 값을 받아올 수 있는지 직의하는 용어로 쓰임
    func prepare(on database: Database) -> EventLoopFuture<Void> {
        // building table and naming the table
        database.schema("movies") // table name
            .id()
            .field("title", .string) //column name
            .create()
    }
    
    // undo migration: if you don't want database, this method may undo the action
    func revert(on database: Database) -> EventLoopFuture<Void> {
        database.schema("movies").delete() // drop the table
    }
    
    
}

Migration을 채택한 뒤 prepare 메서드 에서 테이블을 만들어줘야합니다.

해당 테이블에 포함할 id, column등을 만든 뒤 .create() 메서드를 통해 테이블을 만들어줄 준비를 합니다.

import Vapor
import Fluent
import FluentPostgresDriver

// configures your application
// 해당 데이터베이스에 접속하기 위해 설정하는 메서드
public func configure(_ app: Application) throws {
    // uncomment to serve files from /Public folder
    // app.middleware.use(FileMiddleware(publicDirectory: app.directory.publicDirectory))
    
    app.databases.use(.postgres(hostname: "localhost", username: "사용자이름", password: "", database: "moviesdb"), as: .psql)
    
    // migration will run only once. if it runs, it will create table in our database.
    app.migrations.add(CreateMovie())
    
    // register routes
    try routes(app)
}

그 후 database에 접속하기 위해 설정하는 configure() 메서드안에서 어떠한 database와 연결할 것인지 이름을 명시한 뒤

app.migrations.add() 메서드를 통해 CreateMovie에서 구현하고자 하는 테이블을 database에서 만들어주면 됩니다.

위 작업이 끝난 뒤 terminal로 들어가서 아래와 같은 프로세스를 진행하면 됩니다.

~/사용하고있는vapor위치 vapor run migrate

위 작업을 한 뒤 Postico를 통해 moviedb에 테이블이 잘 생성되었는지 확인할 수 있습니다.

how do we insert data to the created table?

import Foundation
import Fluent
import Vapor


final class Movie: Model {
    
    // identifying the scema. It is declaring that any operation associated with movie table, we will use the particular class Movie
    static var schema: String = "movies"
    
    @ID(key: .id)
    var id: UUID?
    
    // identifying what kind of column does this variable representing
    @Field(key: "title")
    var title: String
    
    init() {}
    
    init(id: UUID = nil, title: String) {
        self.id = id
        self.title = title
    }
}

next we have to make the class conform to Content protocol

import Foundation
import Fluent
import Vapor

// the reason of conforming to Content protocol is that eventually we have to send back a list of movies or a particular movie so that it would be much nicer if we can simply send an instance of this class. that is why we are making this class JSONDecodable, decodable in general by conforming to Content protocol 
final class Movie: Model, Content {
    
    // identifying the scema. It is declaring that any operation associated with movie table, we will use the particular class Movie
    static var schema: String = "movies"
    
    @ID(key: .id)
    var id: UUID?
    
    // identifying what kind of column does this variable representing
    @Field(key: "title")
    var title: String
    
    init() {}
    
    init(id: UUID = nil?, title: String) {
        self.id = id
        self.title = title
    }
}

이제 위 모델을 활용하여 특정한 모델을 테이블로 insert 하거나 table로 부터 데이터를 가져올 수 있습니다.

profile
james, the enthusiastic developer

0개의 댓글