Skip to content

Instantly share code, notes, and snippets.

@clintonmedbery
Last active November 12, 2020 20:13
Show Gist options
  • Save clintonmedbery/671b18d484edfa995d6417f8f76d8e47 to your computer and use it in GitHub Desktop.
Save clintonmedbery/671b18d484edfa995d6417f8f76d8e47 to your computer and use it in GitHub Desktop.
build a query string
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}`
}
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