Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add OrComposeDecodeHookFunc function #240

Merged

Conversation

julnicolas
Copy link
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
Owner

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants