Skip to content

Commit

Permalink
Merge pull request #17 from bensyverson/fix/jwt-locale
Browse files Browse the repository at this point in the history
Fixes Codable support for LocaleClaim
  • Loading branch information
tanner0101 authored Feb 26, 2020
2 parents 77553e6 + d85df02 commit 57c49ff
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
12 changes: 12 additions & 0 deletions Sources/JWTKit/Claims/LocaleClaim.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,16 @@ public struct LocaleClaim: JWTClaim, Equatable, ExpressibleByStringLiteral {
public init(stringLiteral value: String) {
self.value = Locale(identifier: value)
}

/// See `Decodable`.
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
try self.init(value: Locale(identifier: container.decode(String.self)))
}

/// See `Encodable`.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(value.identifier)
}
}
31 changes: 31 additions & 0 deletions Tests/JWTKitTests/JWTKitTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,37 @@ class JWTKitTests: XCTestCase {
data = #"{"bad":"Not boolean"}"#.data(using: .utf8)!
XCTAssertThrowsError(try JSONDecoder().decode(BoolPayload.self, from: data))
}

func testLocaleClaim() throws {
let ptBR = #"{"locale":"pt-BR"}"#

let plainEnglish = try LocalePayload.from(#"{"locale":"en"}"#)
let brazillianPortugese = try LocalePayload.from(ptBR)
let nadizaDialectSlovenia = try LocalePayload.from(#"{"locale":"sl-nedis"}"#)
let germanSwissPost1996 = try LocalePayload.from(#"{"locale":"de-CH-1996"}"#)
let chineseTraditionalTwoPrivate = try LocalePayload.from(#"{"locale":"zh-Hant-CN-x-private1-private2"}"#)

XCTAssertEqual(plainEnglish.locale.value.identifier, "en")
XCTAssertEqual(brazillianPortugese.locale.value.identifier, "pt-BR")
XCTAssertEqual(nadizaDialectSlovenia.locale.value.identifier, "sl-nedis")
XCTAssertEqual(germanSwissPost1996.locale.value.identifier, "de-CH-1996")
XCTAssertEqual(chineseTraditionalTwoPrivate.locale.value.identifier, "zh-Hant-CN-x-private1-private2")

let encoded = try JSONEncoder().encode(brazillianPortugese)
let string = String(bytes: encoded, encoding: .utf8)!
XCTAssertEqual(string, ptBR)
}
}

struct LocalePayload: Codable {
var locale: LocaleClaim
}

extension LocalePayload {
static func from(_ string: String) throws -> LocalePayload {
let data = string.data(using: .utf8)!
return try JSONDecoder().decode(LocalePayload.self, from: data)
}
}

struct BoolPayload: Decodable {
Expand Down

0 comments on commit 57c49ff

Please sign in to comment.