Skip to main content
Module

x/domain_functions/src/domain-functions.ts>branch

Decouple your business logic from your framework. With first-class type inference from end to end.
Go to Latest
function branch
import { branch } from "https://deno.land/x/domain_functions@v2.6.0/src/domain-functions.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'

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[] }>

Parameters

resolver: (o: T) => Promise<R> | R