Skip to content

Instantly share code, notes, and snippets.

@carina-akaia
Last active September 2, 2022 16:55
Show Gist options
  • Save carina-akaia/1c3313bd93dc9b0954a150c268471126 to your computer and use it in GitHub Desktop.
Save carina-akaia/1c3313bd93dc9b0954a150c268471126 to your computer and use it in GitHub Desktop.
effector-forms FP-way validation example
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