Last active
September 2, 2022 16:55
-
-
Save akaia-shadowfox/1c3313bd93dc9b0954a150c268471126 to your computer and use it in GitHub Desktop.
effector-forms FP-way validation example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { createForm } from "effector-forms" | |
import { __, assoc, pipe, prop } from "ramda" | |
import { toString } from "some-library" | |
import { toGas, toSomeAlienStructure } from "some-other-library-or-something" | |
import { isOk, isJustFine } from "some-validation-library" | |
/* Shared library code */ | |
const logged = (value) => { | |
console.log(value) | |
return value | |
} | |
const fromInput = assoc("value", __, { valid: true }) | |
const checked = (predicate) => ({ valid, value }) => ({ valid: valid ? predicate(value) : valid, value }) | |
const ifValid = (converter) => ({ valid, value }) => ({ valid, value: valid ? converter(value) : value }) | |
const toOutput = prop("valid") | |
/* Business logic */ | |
const form = createForm({ | |
someValue: { | |
init: "", | |
rules: [ | |
{ | |
name: "someValue", | |
validator: pipe( | |
fromInput, | |
ifValid(toString), | |
checked(isOk), | |
ifValid(toSomeAlienStructure), | |
logged, | |
checked(isJustFine), | |
logged, | |
ifValid(toGas), | |
checked((value) => value > 2 && value < 10), | |
toOutput, | |
) | |
}, | |
], | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment