Skip to content

Using both URLEncoding and JSONEncoding #1059

Closed
@amaurydavid

Description

@amaurydavid
Contributor

I have to use an API that asks me to make a POST and put one parameter in the URL, others as JSON in the body.
If I had to only send the URL parameter, I would use URLEncoding.queryString
If I had to only send the body parameters, I would use JSONEncoding.default
But how can I send both with Moya? As far as I know, Moya only allow 1 parameter encoding.

As a workaround, in my implementation of TargetType I left the body params in parameters and 'parameterEncoding` to JSONEncoding.default, and tried to put the query parameter directly in the path, but doing so the '?' is encoded as '%3F' while it shouldn't and the API returns an error.

Using Moya 8.0.3

Activity

amaurydavid

amaurydavid commented on Apr 20, 2017

@amaurydavid
ContributorAuthor

Nvm, I found some inspiration from #909 and created a custom encoding.

struct MultipleEncoding : ParameterEncoding {

	var urlParameters: [String]?
	
	init(urlParameters:[String]) {
		self.urlParameters = urlParameters
	}
	
	func encode(_ urlRequest: Alamofire.URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
		guard let parameters = parameters else { return urlRequest as! URLRequest }
		
		//Encode URL Params
		var filteredParams: [String: Any] = [:]
		
		parameters.filter({ (key,value) in
			return urlParameters?.contains(key) ?? false
		}).forEach {
			filteredParams[$0.0] = $0.1
		}
		
		let partiallyEncodedRequest = try URLEncoding.queryString.encode(urlRequest, with: filteredParams)
		
		//Encode JSON
		filteredParams = parameters.minus(dict: filteredParams)
		return try JSONEncoding.default.encode(partiallyEncodedRequest, with: filteredParams)
	}
}

That's not very generic but I someone has the same issue, here is something to start with :)

hardikamal

hardikamal commented on Sep 3, 2018

@hardikamal

@amaurydavid parameter.minus is not working. And can you help out on how to use this?

amaurydavid

amaurydavid commented on Sep 4, 2018

@amaurydavid
ContributorAuthor

I no longer have access to that code but by the look of it, the minus function was just building a new dictionary with only entries that should be json encoded. Kinda the opposite of the filter above.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @BasThomas@hardikamal@amaurydavid

        Issue actions

          Using both URLEncoding and JSONEncoding · Issue #1059 · Moya/Moya