@pallad/builder
TypeScript icon, indicating that this package has built-in type declarations

2.0.2 • Public • Published

builder 💪

Builder building blocks to prevent breaking chaining


CircleCI npm version Coverage Status License: MIT

Installation

npm install @pallad/builder

Problem

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

Solution

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

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

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()
	.run(setupFilters)
	.run(setupSorting)
	.run(setupPagination)
	.run(setupTenancy)

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

Package Sidebar

Install

npm i @pallad/builder

Weekly Downloads

442

Version

2.0.2

License

MIT

Unpacked Size

33.9 kB

Total Files

8

Last publish

Collaborators

  • wookieb