Skip to content

Instantly share code, notes, and snippets.

@jacobdubail
Last active August 10, 2021 20:44
Show Gist options
  • Select an option

  • Save jacobdubail/0773cf4b6ab44055ee45fd51584277cc to your computer and use it in GitHub Desktop.

Select an option

Save jacobdubail/0773cf4b6ab44055ee45fd51584277cc to your computer and use it in GitHub Desktop.
OrderDesk API Client in JavaScript
class OrderDeskApiClient {
constructor(store_id = 0, api_key = "") {
this.store_id = store_id
this.api_key = api_key
this.base_url = "https://app.orderdesk.me/api/v2"
this.last_status_code = ""
}
get(url = '', post = null) {
return this.go('GET', url, post)
}
post(url, post = null) {
return this.go('POST', url, post)
}
put(url, post = null) {
return this.go('PUT', url, post)
}
delete(url, post = null) {
return this.go('DELETE', url, post)
}
async go(method, url, data) {
if (typeof data !== 'object') data = null
if (!url) throw 'Please enter a destination url'
url = `${this.base_url}/${url}`
const headers = this.getHeaders()
//GET Override
if (method == 'GET' && data !== null) {
url = url + (url.indexOf('?') === -1 ? '?' : '').this.buildQuery(data)
data = ''
}
return await this.fetch(url, method, headers, data)
.then(async (resp) => {
return await resp.json()
})
.catch((error) => {
this.last_status_code = error
return { status: 'error', message: `Receive Error: ${response}` }
})
}
async fetch(url, method, headers, data) {
return await fetch(url, {
method,
headers,
body: data ? JSON.stringify(data) : null,
redirect: 'follow', // manual, *follow, error
})
}
buildQuery(params) {
var searchParams = new URLSearchParams()
Object.keys(params).forEach(function (name) {
searchParams.append(name, params[name])
})
return searchParams.toString()
}
//Get auth headers for this call
getHeaders() {
return {
'ORDERDESK-STORE-ID': this.store_id,
'ORDERDESK-API-KEY': this.api_key,
'Content-Type': 'application/json',
}
}
get lastStatusCode() {
return this.last_status_code
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment