rahimizad / Resource

RESTful resources for Zewo's Router

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Resource

Zewo 0.4 Swift 3 Platform Linux License MIT Slack Status

Resource provides RESTful resources for Zewo's Router.

Usage

Todo.swift

public struct Todo {
    public let id: String?
    public let title: String
    public let done: Bool

    public init(id: String?, title: String, done: Bool) {
        self.id = id
        self.title = title
        self.done = done
    }
}

TodoContent.swift

extension Todo: ContentMappable {
    public init(content: Content) throws {
        self.id = try? content.get("id")
        self.title = try content.get("title")
        self.done = try content.get("done")
    }
}

extension Todo: ContentRepresentable {
    public var content: Content {
        return [
            "id": Content.from(id),
            "title": Content.from(title),
            "done": Content.from(done)
        ]
    }
}

Router.swift

let router = Router { route in
    route.resources("/todos", resources: todoResources)
}

TodoResources.swift

let todoResources = Resource(mediaTypes: [JSONMediaType()]) { todo in
    // GET /todos
    todo.index { request in
        let todos = try app.getAllTodos()
        return Response(content: ["todos": todos.content])
    }

	// POST /todos
    todo.create(content: Todo.self) { request, todo in
        let newTodo = try app.createTodo(title: todo.title, done: todo.done)
        return Response(content: newTodo)
    }

	// GET /todos/:id
    todo.show { request, id in
        let todo = try app.getTodo(id: id)
        return Response(content: todo)
    }

	// PUT /todos/:id
    todo.update(content: Todo.self) { request, id, todo in
        let newTodo = try app.updateTodo(id: id, title: todo.title, done: todo.done)
        return Response(content: newTodo)
    }

	// DELETE /todos/:id
    todo.destroy { request, id in
        try app.removeTodo(id: id)
        return Response(status: .noContent)
    }
}

Installation

  • Add Resource to your Package.swift
import PackageDescription

let package = Package(
	dependencies: [
		.Package(url: "https://github.com/paulofaria/Resource.git", majorVersion: 0, minor: 4),
	]
)

Community

Slack

Join us on Slack.

License

Resource is released under the MIT license. See LICENSE for details.

About

RESTful resources for Zewo's Router

License:MIT License


Languages

Language:Swift 100.0%