Last active
January 21, 2022 12:58
-
-
Save r3dm1ke/8a20067238bf0900af65e5938591e1a7 to your computer and use it in GitHub Desktop.
Builder pattern in JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | |
| }); | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you!