Created
July 5, 2020 16:47
-
-
Save gondar00/7fd8368c54b4c1b2d9219794192dbca5 to your computer and use it in GitHub Desktop.
JS Rest client
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
| class RestClient { | |
| static endpoint = ''; | |
| constructor () { | |
| this.id = args.id; | |
| this.errors = Array.isArray(args.errors) ? args.errors : []; | |
| } | |
| static adapter; | |
| static toQueryString(params = {}, prefix = '') { | |
| const query = Object.keys(params).map((k) => { | |
| let key = k; | |
| const value = params[key]; | |
| if (params.constructor === Array) { | |
| key = encodeURIComponent(`${prefix}[]`); | |
| } else if (params.constructor === Object) { | |
| key = prefix ? `${prefix}[${key}]` : key; | |
| } | |
| if (typeof value === 'object') { | |
| return this.toQueryString(value, key); | |
| } | |
| return `${key}=${encodeURIComponent(value)}`; | |
| }); | |
| return [...query].join('&'); | |
| } | |
| static constructEndpoint(args = {}) { | |
| const urlParams = this.endpoint.match(/:\w+/g); | |
| if (!urlParams) { | |
| return this.endpoint; | |
| } | |
| let url = this.endpoint; | |
| urlParams.forEach((item) => { | |
| url = url.replace(item, args[item.substring(1)]); | |
| }); | |
| return url; | |
| } | |
| validate() {} | |
| get(args, query) { | |
| let requestURL = this.id ? `${this.constructEndpoint(args)}/${this.id}` : this.constructEndpoint(args); | |
| if (typeof query === 'object') { | |
| requestURL += `?${this.toQueryString(query)}`; | |
| } | |
| return this.adapter.get(requestURL) | |
| } | |
| save() { | |
| return this.id ? this._update() : this._create() | |
| } | |
| delete() { | |
| return this.constructor.adapter.patch(`${this.constructEndpoint()}/${this.id}`, this.getData()); | |
| } | |
| constructData() { | |
| } | |
| private _update() { | |
| return this.constructor.adapter.patch(`${this.constructEndpoint()}/${this.id}`, this.constructData()); | |
| } | |
| private _create() { | |
| return this.constructor.adapter.post(this.constructEndpoint(), this.constructData()); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment