Code Monkey home page Code Monkey logo

codableproxies's Introduction

CodableProxies

CodableProxies provides powerful encoding and decoding strategies for Swift's Codable types. By wrapping your encoders and decoders in DecoderProxy and EncoderProxy, you can easily apply these strategies for a more flexible and versatile encoding/decoding experience.

Features

  • ๐Ÿš€ Flexible Encoding/Decoding strategies.
  • ๐Ÿ”„ Symmetric Encoding and Decoding support through union types.
  • ๐Ÿ Convert from/to SnakeCase, CamelCase keys.
  • ๐Ÿ”ข Custom strategies for numbers, dates, URLs, etc.
  • ๐Ÿ“ฆ Easily extensible.

Usage

Example

struct User: Codable {
    let isActive: Bool
    let birthDate: Date
    ...
}

let userJSON = """
{
    "isActive": "yes",
    "birthDate": "1990-01-01T00:00:00Z",
    ...
}
"""

let decoder = DecoderProxy(JSONDecoder(), strategy: [.default, .Bool.string, .Date.iso8601])
let user = try decoder.decode(User.self, from: userJSON.data(using: .utf8)!)

Initialization

Wrap your encoders and decoders:

let encoder = EncoderProxy(JSONEncoder(), strategy: [.Bool.string, .Date.iso8601])
let decoder = DecoderProxy(JSONDecoder(), strategy: [.Bool.string, .Date.iso8601])

Available strategies

  • .Bool: decodeFromString, string.
  • .Data: base64.
  • .Date: date, iso8601, formatted(formatter:), timestamp.
  • .Decimal: string, number.
  • .Keys: useDefaultKeys, snakeCase, camelCase, custom(...).
  • .Numeric: string.
  • .Optional: encodeNull.
  • .URL: uri.

Union Types

The library offers CodingProxy and CodingStrategy that bring together both encoding and decoding for symmetrical operations.

๐Ÿ“ Combining Encoding and Decoding Strategies

When setting multiple strategies, the behavior varies between encoding and decoding:

Encoding:

If you combine multiple encoding strategies for the same type, only the last strategy specified will be applied. Strategies specified earlier will be overridden.

Example: Using [.Date.iso8601, .Date.timestamp] for encoding will result in the date being encoded as a timestamp, as .Date.timestamp is the last strategy listed.

Decoding:

For decoding, if multiple strategies are specified for the same type, all of them will be attempted in the order they are provided. Decoding will succeed if any of the strategies succeeds. If all custom strategies fail, the original strategy of the decoder will be used as a fallback.

Example: With [.Date.iso8601, .Date.timestamp] for decoding, the proxy will first attempt to decode the date in the ISO8601 format. If that fails, it will then try to decode it as a timestamp. If both strategies fail, the date will be decoded using the decoder's original strategy.

โš ๏ธ Important Note on Custom Type Encoding/Decoding

When utilizing CodableProxies, it's crucial to understand that the library will override and ignore any custom encoding and decoding strategies set on the original encoders/decoders. This behavior particularly impacts the following types when used with JSONEncoder, JSONDecoder, PropertyListEncoder, and PropertyListDecoder:

  • Decimal
  • URL
  • Data
  • Date

To maintain consistency and avoid unexpected outcomes, always include strategies for these types in your proxy encoder/decoder. Conveniently, all these strategies are bundled within EncoderStrategy.default and DecoderStrategy.default.

Upcoming Enhancements:

  • Diagnostic Tools: Introduce strategies and utilities to aid in testing encoders and decoders, such as EncodingStrategy.print.
  • Collection Handling: Implement strategies like .Collection.nilIfEmpty and .Collection.emptyIfNil to better manage collection states.
  • Structural Strategies: Develop strategies that work with deep keys, allowing for nuanced modifications in object structures.
  • Enhanced Flexibility: Further refine and expand the range of available strategies for broader use cases and adaptability.

Installation

  1. Swift Package Manager

Create a Package.swift file.

// swift-tools-version:5.7
import PackageDescription

let package = Package(
  name: "SomeProject",
  dependencies: [
    .package(url: "https://github.com/dankinsoid/CodableProxies.git", from: "1.1.3")
  ],
  targets: [
    .target(name: "SomeProject", dependencies: ["CodableProxies"])
  ]
)
$ swift build

Author

dankinsoid, [email protected]

License

CodableProxies is available under the MIT license. See the LICENSE file for more info.

Contribution

Contributions are always welcome! Please refer to our contribution guidelines.

codableproxies's People

Contributors

dankinsoid avatar

Stargazers

 avatar  avatar  avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.