From 073f26337febc0cb4cb402e51ee125fd49b33331 Mon Sep 17 00:00:00 2001 From: Drew DeVault Date: Fri, 27 Aug 2021 09:45:41 +0200 Subject: [PATCH] valid: add generic optional interface --- valid/valid.go | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/valid/valid.go b/valid/valid.go index 991cd77fd90ff7d72cc1174e91eb7cc8af51fe8d..90e35f9d28c10c769a0e0d0fa6accd512746f368 100644 --- a/valid/valid.go +++ b/valid/valid.go @@ -36,6 +36,19 @@ func (valid *Validation) Ok() bool { return len(graphql.GetErrors(valid.ctx)) == 0 } +// Fetches an item from the validation context, which must have an input +// registered. If the field is not present, the callback is not run. Otherwise, +// the function is called with the value for the user to conduct further +// validation with. +func (valid *Validation) Optional(name string, fn func(i interface{})) { + if valid.input == nil { + panic("Attempted to validate fields without input") + } + if o, ok := valid.input[name]; ok { + fn(o) + } +} + // Fetches a string from the validation context, which must have an input // registered. If the field is not present, the callback is not run. If // present, but not a string, an error is recorded. Otherwise, the function is