Fluent API JavaScript/TypeScript Implementation
interface IMyService {
prop1: ISomeType1;
prop2: ISomeType2;
}
class MyService implements IMyService {
//
}Scenario:
- You want make sure
prop1andprop2assigned some valid value before clients using instance ofMyServiceclass. prop1andprop2are some complex values to construct.- Sometime you may have too many properties hard to pass in constructor.
Wouldn’t it be nice if we can create those properties step by step and assign to the object? and validate those properties before the client is using it?
Get Musema Hassen’s stories in your inbox
Join Medium for free to get updates from this writer.
Solution:
- Create a builder class, and make the actual object
privateso consumers not accidentally using it before it’s ready to use. - The builder exposes
publicmethods to set each properties in any order. The key point here is those methods need to return the instance of builder(this) so that the consumer can call other public methods of the builder step by step. - Expose the actual object with a method which you can validate it’s state before returning it.
export class MyServiceBuilder {
private myService: IMyService;
public withProp1(): MyServiceBuilder {
// the logic of creating prop1 here
const someValue = ...;
this.myService.prop1 = someValue;
// now return the builder itself, so client calls it's other methods
return this;
}
public withProp2(): MyServiceBuilder {
// the logic of creating prop2 here
const someOtherValue = ...;
this.myService.prop2 = someValue;
// now return the builder itself, so client calls it's other methods
return this;
}
public build(): IMyService {
// here when build is called you can validate if prop1 and prop2 are assigned and valid
// otherwise throw Error
// this way making sure the build is only returning valid of myService object
// now return the actual myService object
return this.myService;
}
}Usage
function myClientFunction() {
const myService: IMyService = new MyServiceBuilder()
.withProp1()
.withProp2()
.build();
}or
function myClientFunction() {
let myServiceBuilder= new MyServiceBuilder();
myServiceBuilder = myServiceBuilder.withProp1(); // prop1 of myService is set
myServiceBuilder = myServiceBuilder.withProp2(); // prop2 of myService is set
// now builder sets all props of myService instance.
//so we can get the constructed myService instance
const myService: IMyService = myServiceBuilder.build(); // myService is READY
}Conclusion
This core idea in this patten is returning builder instance in setter methods, and returning the actual object from build method. Note: How you name the methods does’t really matter except for readability purpose.





