Skip to content

Proposal: Adding RequestBehaviours to Malibu #88

@codeOfRobin

Description

@codeOfRobin

Hey!

I've been reading about RequestBehaviour recently and I think it'd be a great addition to Malibu, especially for things like Logging, NetworkActivityIndicators, authentication, caching etc.

Here's what the protocol looks like

protocol RequestBehavior {

	func beforeSend()

	func afterSuccess(result: Any)

	func afterFailure(error: Error)

	func adapt(_ request: URLRequest) -> URLRequest

}

// default implementations
extension RequestBehavior {
	func beforeSend() {

	}

	func afterSuccess(result: Any) {

	}

	func afterFailure(error: Error) {

	}

	func adapt(_ request: URLRequest) -> URLRequest {
		return request
	}
}

And Auth can be implemented as follows:

struct TokenAuthBehaviour: RequestBehavior {
	let token: String

	func adapt(_ request: URLRequest) -> URLRequest {
		var copy = request
		var headers = copy.allHTTPHeaderFields ?? [:]
		headers["Authorization"] = "Bearer \(token)"
		copy.allHTTPHeaderFields = headers
		return copy
	}
}

struct CustomAuthBehaviour: RequestBehavior {

	let key: String
	let value: String

	func adapt(_ request: URLRequest) -> URLRequest {
		var copy = request
		var headers = copy.allHTTPHeaderFields ?? [:]
		headers[key] = value
		copy.allHTTPHeaderFields = headers
		return copy
	}
}

struct CustomAuthBehaviour: RequestBehavior {

	let key: String
	let value: String

	func adapt(_ request: URLRequest) -> URLRequest {
		var copy = request
		var headers = copy.allHTTPHeaderFields ?? [:]
		headers[key] = value
		copy.allHTTPHeaderFields = headers
		return copy
	}
}

There's other examples in the blog post, but this would be an excellent starting point (Logging could be in both before and after function calls, for example)

PS: Discussed this with @vadymmarkov on Twitter recently: https://twitter.com/vadymmarkov/status/956075029736894465

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions