Skip to content
This repository has been archived by the owner on Apr 26, 2022. It is now read-only.

Commit

Permalink
fix: throw error when fetch is not ok (#81)
Browse files Browse the repository at this point in the history
* fix: throw error when fetch is not ok

* fix: return statusCode with error res
  • Loading branch information
notrab committed Dec 21, 2018
1 parent 0e80fd0 commit 84293bf
Showing 1 changed file with 37 additions and 41 deletions.
78 changes: 37 additions & 41 deletions src/index.ts
Expand Up @@ -27,56 +27,52 @@ export class createClient {
data: object = undefined,
requestHeaders: Headers = {}
) {
try {
const {
application,
currency,
customer_token,
host,
version,
headers: classHeaders
} = this.options

const uri: string = `https://${host}/${version}/${removeLeadingSlash(
path
)}`

const customHeaders = {
...classHeaders,
...requestHeaders
}
const {
application,
currency,
customer_token,
host,
version,
headers: classHeaders
} = this.options

const uri: string = `https://${host}/${version}/${removeLeadingSlash(path)}`

const customHeaders = {
...classHeaders,
...requestHeaders
}

const headers: Headers = {
'Content-Type': 'application/json',
'X-MOLTIN-SDK-LANGUAGE': 'JS-REQUEST',
Authorization: `Bearer ${await this.authenticate()}`,
...(application && { 'X-MOLTIN-APPLICATION': application }),
...(currency && { 'X-MOLTIN-CURRENCY': currency }),
...(customer_token && { 'X-MOLTIN-CUSTOMER-TOKEN': customer_token }),
...customHeaders
}
const headers: Headers = {
'Content-Type': 'application/json',
'X-MOLTIN-SDK-LANGUAGE': 'JS-REQUEST',
Authorization: `Bearer ${await this.authenticate()}`,
...(application && { 'X-MOLTIN-APPLICATION': application }),
...(currency && { 'X-MOLTIN-CURRENCY': currency }),
...(customer_token && { 'X-MOLTIN-CUSTOMER-TOKEN': customer_token }),
...customHeaders
}

const body = customHeaders['Content-Type']
? data
: { body: JSON.stringify({ data }) }
const body = customHeaders['Content-Type']
? data
: { body: JSON.stringify({ data }) }

const response = await fetch(uri, {
method,
headers,
...(data && body)
})
const response = await fetch(uri, {
method,
headers,
...(data && body)
})

const json = await response.json()
const json = await response.json()

return {
if (!response.ok) {
throw {
statusCode: response.status,
...json
}
} catch (errors) {
return {
errors
}
}

return json
}

async authenticate() {
Expand Down

0 comments on commit 84293bf

Please sign in to comment.