Skip to content


Repository files navigation

builder 💪

Builder building blocks to prevent breaking chaining

CircleCI npm version Coverage Status License: MIT


npm install @pallad/builder


Whenever you use a builder pattern, sometimes certain methods needs be called conditionally. For those cases you need to break the chaining.

const queryBuilder = createQueryBuilder();
if (hasFilter) {
	queryBuilder.where() // do filters
return queryBuilder.where() // work on builder again


That is very annoying and many times unnecessary complicates the code. @pallad/builder provides Builder class that has runIf and run helper methods. The most useful is defeinitely runIf.

return createQueryBuilder()
	.runIf(hasFilter, () => {
		queryBuilder.where() // do filters 
	.where() // keep working on builder

Much cleaner.

Usage and how it works

In order to use Builder in your builder patterns you need to either extend it.

import {Builder} from '@pallad/builder';

class YourCustomBuilder extends Builder {


Or apply on existing object

import {Builder} from '@pallad/builder';

const existingBuilder = Builder.extend(someBuilderInstance);


runIf executes provided function only if condition is truthy. If it is not, then returns current instance.

new CustomBuilder()
	.runIf(hasEnabledSorting, (builder) => {
		builder.setupSorting(); // ran if `hasEnabledSorting` is truthy


run just always executes provided function. Very handy when you need to setup huge builder but want to split it into several other functions.

new CustomBuilder()

Returned result

Both run and runIf might return some result. If that result is not undefined or null then that result is being returned back.

const builder = new CustomBuilder();
const result = builder.runIf(true, () => {
	return new CustomBuilder(); // return new instance
result === builder // false

Otherwise current instance gets returned

const builder = new CustomBuilder();
const result = builder.runIf(false, () => {
	// do nothing
result === builder // true