Moya: Is there a way to avoid creating a Decoder for every task?

Created on 9 Oct 2018  路  3Comments  路  Source: Moya/Moya

I have Codable models, and I'd like do encode the using .convertToSnakeCase strategy, is there a way to avoid the following for every enum:


...

    var task: Task {

        var parameters: [String: Any] = [:]

        let encoder = JSONEncoder()
        encoder.keyEncodingStrategy = .convertToSnakeCase

        switch self {
        case let .update(user):

            return .requestCustomJSONEncodable(user, encoder: encoder)

        ...
        }

        return .requestParameters(parameters: parameters, encoding: URLEncoding.default)

    }

...

question stale

Most helpful comment

try declaring encoder as private top-level constant

private let snakeEncoder: JSONEncoder = {
    let encoder = JSONEncoder()
    encoder.keyEncodingStrategy = .convertToSnakeCase
    return encoder
}()

enum MyTarget: Moya.TargetType {
    ...

    var task: Task {
        switch self {
        case .update(user):
            return .requestCustomJSONEncodable(user, encoder: snakeEncoder) // encoder declared on the top level
        ...
        }
    }

    ...
}

All 3 comments

try declaring encoder as private top-level constant

private let snakeEncoder: JSONEncoder = {
    let encoder = JSONEncoder()
    encoder.keyEncodingStrategy = .convertToSnakeCase
    return encoder
}()

enum MyTarget: Moya.TargetType {
    ...

    var task: Task {
        switch self {
        case .update(user):
            return .requestCustomJSONEncodable(user, encoder: snakeEncoder) // encoder declared on the top level
        ...
        }
    }

    ...
}

This issue has been marked as stale because it has not had recent activity. It will be closed if no further activity occurs.

I'll close this one as it seems resolved.

@felixsolorzano if you still have questions, feel free to re-open this issue or create another one!

Was this page helpful?
0 / 5 - 0 ratings