Skip to content

Instantly share code, notes, and snippets.

@r3dm1ke
Last active January 21, 2022 12:58
Show Gist options
  • Select an option

  • Save r3dm1ke/8a20067238bf0900af65e5938591e1a7 to your computer and use it in GitHub Desktop.

Select an option

Save r3dm1ke/8a20067238bf0900af65e5938591e1a7 to your computer and use it in GitHub Desktop.
Builder pattern in JavaScript
function executeWithFetch(request) {
// EXERCISE FOR THE READER
}
function executeWithAxios(request) {
// EXERCISE FOR THE READER
}
function ClientBuilder() {
return {
forBaseUrl: function(baseUrl) {
this.baseUrl = baseUrl;
return this;
}
withHeaders: function(headers) {
this.headers = headers;
return this;
}
usingFetch: function() {
this.executor = executeWithFetch;
return this;
}
usingAxios: function() {
this.executor = executeWithAxios;
return this;
}
build: function() {
return new Client(this.baseUrl, this.headers, this.executor);
}
}
}
function Client(baseUrl, headers, executor) {
this.baseUrl = baseUrl;
this.headers = headers;
this.executor = executor;
this.post = function(endpoint, data) {
const url = `${this.baseUrl}${endpoint}`;
return this.executor({
url,
data,
method: 'POST',
headers: this.headers
});
}
this.get = function(endpoint, params) {
const url = `${this.baseUrl}${endpoint}`;
return this.executor({
url,
params,
method: 'GET',
headers: this.headers
});
}
}
@0xflotus
Copy link
Copy Markdown

In L43 and L53 you forgot to close the template string

@r3dm1ke
Copy link
Copy Markdown
Author

r3dm1ke commented Jan 30, 2020

In L43 and L53 you forgot to close the template string

Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment