From 9f56bb74a9aeea0655cd497f25b982b5018bf6d1 Mon Sep 17 00:00:00 2001 From: kientux Date: Thu, 30 Jun 2022 17:05:13 +0700 Subject: [PATCH] Update README, tests --- README.md | 36 ++++++++++++++++++- .../ParameterizeTests/ParameterizeTests.swift | 10 ++++++ 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 7c1cff1..bc08654 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ components.path = "some/api/path/" components.queryItems = params.map { URLQueryItem(name: $0.key, value: "\($0.value)")} ``` -- Auto infer name of param from simple field name +- Auto infer name of param from field name, with default/snake_case or custom naming strategy - Nil and empty array will be remove automatically - Auto handle array of elements that conform to `CustomStringConvertible` - Auto expand nested params @@ -83,3 +83,37 @@ print(serialized) // ["query": "search", "name": "tux"] ``` + +### Naming strategy + +```swift +struct ApiParam: ParamsContainer { + + @Params + var thisShouldBeSnakeCase: Int = 0 +} + +let params = ApiParam() +let config = ParamSerializer.Config(namingStrategy: SerializerNamingStrategy.convertToSnakeCase) +let serialized = ParamSerializer(config: config).serialize(object: params) +print(serialized) + +// ["this_should_be_snake_case": 0] +``` + +- Any custom naming strategy can be done by conforming to `NamingStrategy` + +```swift +class UppercaseNamingStrategy: NamingStrategy { + public func name(from fieldName: String) -> String { + return fieldName.uppercased() + } +} + +let params = ApiParam() +let config = ParamSerializer.Config(namingStrategy: UppercaseNamingStrategy()) +let serialized = ParamSerializer(config: config).serialize(object: params) +print(serialized) + +// ["THISSHOULDBESNAKECASE": 0] +``` \ No newline at end of file diff --git a/Tests/ParameterizeTests/ParameterizeTests.swift b/Tests/ParameterizeTests/ParameterizeTests.swift index 7ec9df0..5ba6027 100644 --- a/Tests/ParameterizeTests/ParameterizeTests.swift +++ b/Tests/ParameterizeTests/ParameterizeTests.swift @@ -64,6 +64,10 @@ final class ParameterizeTests: XCTestCase { XCTAssert(serialized.keys.contains("namingConvert")) XCTAssert(serialized.keys.contains("namingConvert1")) XCTAssert(serialized.keys.contains("NamingConvert2")) + + serialized = ParamSerializer(config: .init(namingStrategy: UppercaseNamingStrategy())) + .serialize(object: params) + XCTAssert(serialized.keys.contains("NAMINGCONVERT")) } } @@ -140,3 +144,9 @@ extension Date: ParamConvertible { ISO8601DateFormatter().string(from: self) } } + +class UppercaseNamingStrategy: NamingStrategy { + public func name(from fieldName: String) -> String { + return fieldName.uppercased() + } +}