Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Server-Side Swift as a Live Example

Server-Side Swift as a Live Example

My lightning talk at the try! Swift Tokyo 2017.

Codes: https://github.com/search?q=user%3Atnantoka+topic%3Asssaale&type=Repositories

Tatsuya Tobioka

March 03, 2017
Tweet

Other Decks in Technology

Transcript

  1. #if os(Linux) error: use of unresolved identifier 'NSRegularExpression' error: value

    of type 'NSURL' has no member 'isFileReferenceURL' error: cannot convert value of type 'NSMutableString' to expected argument type 'CFMutableString!' (›°□°)›ớᵲᴸᵲ
  2. AppLogic/Droplet+Setup.swift // GET / -> Views/welcome.leaf drop.get { req in

    return try drop.view.make("welcome", [ "title": title ]) } // /example -> Controllers/ExampleController.swift drop.resource("example", ExampleController())
  3. Models/Example.swift final class Example: Model { // Input -> Output

    var input: String var output: String { return input.uppercased() } // JSON -> Model init(node: Node, in context: Context) throws { input = try node.extract("input") } // Model -> JSON func makeNode(context: Context) throws -> Node { return try Node(node: [ "output": output, ]) } }
  4. Controllers/ExampleController.swift final class ExampleController: ResourceRepresentable { // Model -> JSON

    func create(request: Request) throws -> ResponseRepresentable { let example = try request.example() return example } // POST /example -> create func makeResource() -> Resource<Example> { return Resource( store: create ) } }
  5. AppLogicTests/AppLogicTests.swift func testExample() { let drop = try! makeTestDroplet() let

    json = try! JSON(node: .object([ "input" : "hello" ])) let req = try! Request( method: .post, uri: "/example", headers: [ HeaderKey.contentType : "application/json" ], body: json.makeBody() ) let res = try! drop.respond(to: req) let body = res.body.bytes!.string XCTAssertTrue(body.contains("HELLO")) // hello -> HELLO }
  6. scripts/app.js - <input type="text + <textarea - { example.output }

    + <div + dangerouslySetInnerHTML={ + { __html: example.output } + } + />
  7. AppLogicTests/AppLogicTests.swift - try! JSON(node: .object([ "input" : "hello" ])) +

    try! JSON(node: .object([ "input" : "# hello" ])) - XCTAssertTrue(body.contains("HELLO")) + XCTAssertTrue(body.contains("<h1>hello</h1>"))
  8. Test & Run $ docker pull swiftdocker/swift $ docker run

    -it -v `pwd`:/app -w /app -p 8080:8080 swiftdocker/swift $ swift test $ .build/Debug/App