-
Notifications
You must be signed in to change notification settings - Fork 46
/
request.ts
27 lines (27 loc) · 996 Bytes
/
request.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import * as fetch from 'node-fetch'
export async function request(
apiUrl: string,
fetchContext: fetch.RequestInit | undefined
): Promise<fetch.Response> {
const response = await fetch.default(apiUrl, fetchContext)
const responseBody = await response.clone().json()
if (response.status === 401) {
throw new Error(
`Bad credentials data. Run hydra-cli login or check your account`
)
} else if (response.status === 400 && responseBody.errors.length === 0) {
throw new Error(responseBody.message)
} else if (response.status === 400 && responseBody.errors.length !== 0) {
let validationErrorString = 'some validation problems\n'
for (const error of responseBody.errors) {
for (const constraint of Object.values(error.constraints)) {
validationErrorString += `${constraint}\n`
}
}
throw new Error(validationErrorString)
} else if (response.status === 200) {
return response
} else {
throw new Error(`Server error`)
}
}