Skip to content

Commit

Permalink
Added json serialization.
Browse files Browse the repository at this point in the history
  • Loading branch information
OrkhanAlikhanov committed Jul 30, 2017
1 parent e870f1a commit 4ccba30
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 0 deletions.
4 changes: 4 additions & 0 deletions Sources/Request.swift
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,10 @@ extension String {
static var contentLength: String {
return "Content-Length"
}

static var contentType: String {
return "Content-Type"
}
}


11 changes: 11 additions & 0 deletions Sources/Response.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
// Created by Orkhan Alikhanov on 7/4/17.
// Copyright © 2017 BiAtoms. All rights reserved.
//
import Foundation

public typealias Byte = UInt8
open class Response {
open var status: Status
Expand Down Expand Up @@ -52,4 +54,13 @@ extension Response {
class func ok(_ body: String, headers: HeaderDictionary = [:]) -> Self {
return self.init(.ok, body: body.bytes, headers: headers)
}

class func json(_ object: Any, status: Response.Status = .ok, options: JSONSerialization.WritingOptions = .prettyPrinted) -> Response {
var response = Response.ok("Could not serialize into json")
if JSONSerialization.isValidJSONObject(object) {
let data = try! JSONSerialization.data(withJSONObject: object, options: options)
response = Response(status, body: Array(data), headers: [.contentType: "application/json"])
}
return response
}
}
17 changes: 17 additions & 0 deletions Tests/HttpSwiftTests/HttpSwiftTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,22 @@ class HttpSwiftTests: XCTestCase {
waitForExpectations()
}

func testJson() {
server.get("testJson") { _ in
return .json(["hi": ["I": ["am": ["json": ["array": [1,2,3,4]]]]]], status: .ok, options: [])
}

let ex = expectation(description: "testJson")
client.request("/testJson").responseString { r in
XCTAssertEqual(r.response?.statusCode, 200)
XCTAssertEqual(r.response?.headers["Content-Type"], "application/json")
XCTAssertEqual(r.value, "{\"hi\":{\"I\":{\"am\":{\"json\":{\"array\":[1,2,3,4]}}}}}")
ex.fulfill()
}

waitForExpectations()
}

static var allTests = [
("testRoute", testRoute),
("testRequestAndResponse", testRequestAndResponse),
Expand All @@ -245,6 +261,7 @@ class HttpSwiftTests: XCTestCase {
("testMiddleware", testMiddleware),
("testRouteMiddleware", testRouteMiddleware),
("testRouteGrouping", testRouteGrouping),
("testJson", testJson),
]

}
Expand Down

0 comments on commit 4ccba30

Please sign in to comment.