public static LinkConsumerMessageHandlerBuilder Create( LinkConsumerMessageHandlerDelegate <object> onMessage ) => new LinkConsumerMessageHandlerBuilder( (serializer, mapping) => msg => { object body; var props = msg.Properties.Clone(); var typeName = props.Type; if (string.IsNullOrWhiteSpace(typeName)) { return(Task.FromException <LinkConsumerAckStrategy>(new LinkCosumerTypeNameMappingException())); } typeName = typeName.Trim(); var bodyType = mapping.Map(typeName); if (bodyType == null) { return(Task.FromException <LinkConsumerAckStrategy>( new LinkCosumerTypeNameMappingException(typeName))); } try { body = serializer.Deserialize(bodyType, msg.Body, props); } catch (Exception ex) { var sException = new LinkDeserializationException(msg, bodyType, ex); return(Task.FromException <LinkConsumerAckStrategy>(sException)); } var concreteMsg = LinkMessageFactory .ConstructConsumedMessage(bodyType, body, props, msg.RecieveProperties, msg.Cancellation); return(onMessage(concreteMsg)); }, true, true );
public async Task <ILinkPulledMessage <TBody> > GetMessageAsync <TBody>(CancellationToken?cancellation = null) where TBody : class { if (typeof(TBody) != typeof(byte[]) && _serializer == null) { throw new InvalidOperationException("Serializer not set"); } if (typeof(TBody) == typeof(object) && _typeNameMapping.IsEmpty) { throw new InvalidOperationException("Type name mapping is empty"); } while (true) { var msg = await GetRawMessageAsync(cancellation) .ConfigureAwait(false); if (typeof(TBody) == typeof(byte[])) { return((ILinkPulledMessage <TBody>)msg); } try { Type bodyType; if (typeof(TBody) == typeof(object)) { var typeName = msg.Properties.Type; if (string.IsNullOrWhiteSpace(typeName)) { throw new LinkPullConsumerTypeNameMappingException(msg); } bodyType = _typeNameMapping.Map(typeName !.Trim()); if (bodyType == null) { throw new LinkPullConsumerTypeNameMappingException(msg, typeName !); } } else { bodyType = typeof(TBody); } TBody body; var props = msg.Properties.Clone(); try { body = (TBody)_serializer.Deserialize(bodyType, msg.Body, props); } catch (Exception ex) { throw new LinkPullConsumerDeserializationException(msg, bodyType, ex); } var concreteMsg = LinkMessageFactory .ConstructPulledMessage(bodyType, msg, body, props); return((ILinkPulledMessage <TBody>)concreteMsg); } catch (Exception ex) { msg.Exception(ex); } } }