Skip to content

Async response validation #106

@xperiandri

Description

@xperiandri

If we need to read a content on validation like this

let validateResponse (content:HttpContent) = task {
    let! result =  content.ReadAsStringAsync()
    let! stream = content.ReadAsStreamAsync()
    stream.Seek(0L, SeekOrigin.Begin) |>ignore
    return not <| result.StartsWith("<!DOCTYPE html>")
}

then validator must be asynchronous like this

let validateAsync<'TContext, 'TSource>
    (predicate: 'TSource -> Task<bool>)
    (source: Pipeline<'TContext, 'TSource>)
    : Pipeline<'TContext, 'TSource> =
    fun next ->
        { new IAsyncNext<'TContext, 'TSource> with
            member _.OnSuccessAsync(ctx, value) =
                  task{
                      let! isValid = predicate value
                      if isValid then return! next.OnSuccessAsync(ctx, value)
                      else return! next.OnErrorAsync(ctx, SkipException "Validation failed")
                }

            member _.OnErrorAsync(ctx, exn) = next.OnErrorAsync(ctx, exn)
            member _.OnCancelAsync(ctx) = next.OnCancelAsync(ctx) }
        |> source

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions