I'm looking for a way to call a method "implicitely" after a chain (fluent interface pattern).
I already have something like
class Foobar {
methodA() {
// update state
return this;
}
methodB() {
// update state
return this;
}
applyChanges() {
// persist the state at this point
}
}
And on the usage:
new Foobar().methodA().methodB().applyChanges();
The thing here, is that I don't know in advance if users of the class will use only one chain method or two (or even zero) and for "developer experience", I didn't want to expose the applyChanges method.
Is there a way to perform that? Or even another pattern I could implement. For example, I thought I could stack the method calls first, but I still won't know when to stop and execute the applyChanges method :(
If the applyChanges operation were async (and I'm guessing the "persisting" might need something asynchronous anyway), it would be easy: you could have a then method like this:
async applyChanges () { /*...*/ }
then (success, failure) {
return this.applyChanges().then(success, failure)
}
Then awaiting your object would implicitly apply changes and wait for them to be done (await new Foobar().methodA().methodB()), because async/await uses promises under the hood, so await x will cause x.then to be called if existing. This is how Mongoose query objects behave for example.
Ok so I actually got away with it thanks to Polly. Because it lazily evaluates the http handler i'm building, it gets the "right version" of it when the HTTP requests happen :)