3
0

Allow simple interaction with record encoder

Mainly used for record importer; might rework/remove at a later
point.
This commit is contained in:
Tomaž Jerman 2020-11-27 18:15:25 +01:00
parent 851a9a7e11
commit eb2d98cbf0
2 changed files with 29 additions and 10 deletions

View File

@ -129,6 +129,24 @@ func (n *composeRecordState) Encode(ctx context.Context, s store.Storer, state *
im := n.res.IDMap
return n.res.Walker(func(r *resource.ComposeRecordRaw) error {
// Simple wrapper to do some post-processing steps
dfr := func(err error) error {
if n.cfg.Defer != nil {
n.cfg.Defer()
}
if err != nil {
if n.cfg.DeferNok != nil {
return n.cfg.DeferNok(err)
}
return err
} else if n.cfg.DeferOk != nil {
n.cfg.DeferOk()
}
return nil
}
rec := &types.Record{
ID: im[r.ID],
NamespaceID: nsID,
@ -170,24 +188,17 @@ func (n *composeRecordState) Encode(ctx context.Context, s store.Storer, state *
rec.Values = rvSanitizer.Run(mod, rvs)
rve := rvValidator.Run(ctx, s, mod, rec)
if !rve.IsValid() {
return rve
return dfr(rve)
}
// Create a new record
if !exists {
err = store.CreateComposeRecord(ctx, s, mod, rec)
if err != nil {
return err
}
return nil
return dfr(err)
}
// Update existing
err = store.UpdateComposeRecord(ctx, s, mod, rec)
if err != nil {
return err
}
return nil
return dfr(err)
})
}

View File

@ -38,6 +38,14 @@ type (
// EncoderConfig allows us to configure the resource encoding process
EncoderConfig struct {
OnExisting mergeAlg
// Defer is called after the resource is encoded, regardles of the result
Defer func()
// DeferOk is called after the resource is encoded, only when successful
DeferOk func()
// DeferNok is called after the resource is encoded, only when failed
// If you return an error, the encoding will terminate.
// If you return nil (ignore the error), the encoding will continue.
DeferNok func(error) error
}
// resourceState allows each conforming struct to be initialized and encoded