Skip to content
This repository was archived by the owner on Jul 22, 2024. It is now read-only.

add OrComposeDecodeHookFunc function#240

Merged
mitchellh merged 2 commits intomitchellh:masterfrom
julnicolas:feature/add_or_compose_decode_hook_func
Apr 20, 2022
Merged

add OrComposeDecodeHookFunc function#240
mitchellh merged 2 commits intomitchellh:masterfrom
julnicolas:feature/add_or_compose_decode_hook_func

Conversation

@julnicolas
Copy link
Copy Markdown
Contributor

The aim is to be able to compose existing or custom DecodeHookFuncs conditionally.

Currently it is possible to chain calls thanks to ComposeDecodeHookFunc but execution is aborted in case an error is found. Therefore, ComposeDecodeHookFunc can be seen as an AND logical operation.

OrComposeDecodeHookFunc on the other hand, executes until a function returns a nil error or all functions returned a non-nil-error. It can be seen as a complimentary OR logical operation.

One practical use case is to be able to parse dates with different supported layouts :

        data := FormData{}
	config := &mapstructure.DecoderConfig{
		DecodeHook: mapstructure.ComposeDecodeHookFunc(
			OrComposeDecodeHookFunc(
				// Converts input.type === "month"
				mapstructure.StringToTimeHookFunc("2006-01"),
				// Converts input.type === "date"
				mapstructure.StringToTimeHookFunc("2006-01-02"),
				// Converts input.type === "month" from other layout
				mapstructure.StringToTimeHookFunc("2006/01"),
				// Converts input.type === "date" from other layout
				mapstructure.StringToTimeHookFunc("2006/01/02"),
			),
                        // Other DecodeHookFuncs
		),
		WeaklyTypedInput: true,
		Result:           &data,
	}

@mitchellh mitchellh merged commit 3a684c7 into mitchellh:master Apr 20, 2022
@mitchellh
Copy link
Copy Markdown
Owner

Beautiful thanks. I think helping composition of hooks is a great thing to add.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants