Last active
November 12, 2020 20:13
-
-
Save clintonmedbery/671b18d484edfa995d6417f8f76d8e47 to your computer and use it in GitHub Desktop.
build a query string
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
import _ from 'lodash' | |
export const buildQueryString = (url, params) => { | |
let queryStrings = Object.keys(params) | |
.map((key) => { | |
if (!_.isNil(params[key])) { | |
if (Array.isArray(params[key])) { | |
if (params[key].length === 0) { | |
return | |
} | |
let arrayParams = params[key].map((item) => { | |
return encodeURIComponent(key) + '[]=' + encodeURIComponent(item) | |
}) | |
return arrayParams.join('&') | |
} else { | |
return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]) | |
} | |
} | |
}) | |
.filter((value) => typeof value !== 'undefined') | |
if (queryStrings.length === 0) { | |
return url | |
} | |
url = `${url}?` | |
let queryString = queryStrings.join('&') | |
return `${url}${queryString}` | |
} |
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
import axios from 'axios' | |
import {BASE_URL} from "../config"; | |
export const apiFetch = async (method = "GET", url, data, responseType = 'json', contentType = 'application/json') => { | |
url = `${BASE_URL}${url}` | |
try { | |
return ( | |
await axios({ | |
method, | |
headers: { | |
'Content-Type': contentType, | |
}, | |
url, | |
data, | |
responseType | |
}) | |
).data | |
} catch (e) { | |
console.log('e', e) | |
throw e | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment