Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add option to disableEventMessageParsing and receive messages as Strings #1331

Open
wants to merge 3 commits into
base: development
Choose a base branch
from

Conversation

lavenj
Copy link

@lavenj lavenj commented Feb 23, 2021

Hi @nuclearace! Not sure where I should direct this, but I had a need to parse my own messages on a version two(?) websocket that doesn't support binary data, and added a new config option:

/// If passed `true`, event message data will not be parsed, and all message events will be received with
/// `event` value of `"rawMessage"`; listen with `socketClient.on("rawMessage") { ... }`
case disableEventMessageParsing(Bool)

If enabled, event messages are received like so:

socketClient.on("rawMessage") { data, ack in //data is [String] ... }

And emit() calls don't do any further parsing of their data argument, and are expected to look something like:

let message:String = """[echo, {"text": "someValue"}]""" // looks like: [<messageName>, <payload>]"
socketClient.emit("rawMessage", message) //first parameter is ignored

I'm sure there's a more beautiful way of implementing this, but I wanted to keep changes minimal.

Upside for me is easy parsing from/to strongly typed objects using Codable

Any interest in merging?

Example usage:

//receiving the rawMessage
socketClient.on("rawMessage") { data, ack in
	guard let s = data.first as? String, let data = s.data(using: .utf16) else { return }
	let decoder = JSONDecoder()
	let message = try! decoder.decode(Message.self, from: data)
	//do whatever!
}

Parsing/Decoding:

enum Message: Decodable {
	case yellowAlert(YellowAlert)
	case redAlert(RedAlert)

	enum MessageType: String, Decodable {
		case yellowAlert
		case redAlert
	}

	init(from decoder: Decoder) throws {
		var values = try decoder.unkeyedContainer()
		let type = try values.decode(MessageType.self)
		switch type {
		case .yellowAlert:
			let payload = try values.decode(YellowAlert.self)
			self = .yellowAlert(payload)
		case .redAlert:
			let payload = try values.decode(RedAlert.self)
			self = .redAlert(payload)
		}
	}
	
	//Empty data types for demo purposes. You'd probably have some properties in real data.
	struct YellowAlert: Decodable { }
	struct RedAlert: Decodable { }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

1 participant