import { branch } from "https://deno.land/x/domain_functions@v3.0.0/src/index.ts";
Use it to add conditional logic to your domain functions' compositions.
It receives a domain function and a predicate function that should return the next domain function to be executed based on the previous domain function's output, like pipe
. If the predicate returns null
the result of the previous domain function will be returned and it won't be piped.
Examples
import { mdf, branch } from 'domain-functions'
import { mdf, branch } from 'domain-functions'
const getIdOrEmail = mdf(z.object({ id: z.number().optional(), email: z.string().optional() }))((data) => data.id ?? data.email) const findUserById = mdf(z.number())((id) => db.users.find({ id })) const findUserByEmail = mdf(z.string().email())((email) => db.users.find({ email })) const findUserByIdOrEmail = branch( getIdOrEmail, (output) => (typeof output === "number" ? findUserById : findUserByEmail) ) // ^? DomainFunction
const getStock = mdf(z.any(), z.object({ id: z.number() }))(, ({ id }) => db.stocks.find({ id })) const getExtraStock = mdf(z.any(), z.object({ id: z.number() }))(, ({ id }) => db.stockes.find({ id, extra: true }))
const getStockOrExtraStock = branch( getStock, ({ items }) => (items.length >= 0 ? null : getExtraStock) ) // ^? DomainFunction<{ items: Item[] }>