|
1 | | -import { ClientError, Options, Variables } from './types' |
| 1 | +import { |
| 2 | + Options, |
| 3 | + Variables, |
| 4 | +} from './types' |
2 | 5 | import 'cross-fetch/polyfill' |
3 | 6 | import * as DataLoader from 'dataloader' |
4 | | - |
5 | | -export { ClientError } from './types' |
| 7 | +import { ClientError } from './ClientError' |
6 | 8 |
|
7 | 9 | export class BatchedGraphQLClient { |
8 | 10 | public uri: string |
@@ -42,32 +44,33 @@ export class BatchedGraphQLClient { |
42 | 44 | body, |
43 | 45 | }) |
44 | 46 |
|
45 | | - const results = await getResults(response)! |
| 47 | + const results = await getResults(response) |
46 | 48 |
|
47 | | - const allResultsHaveData = |
48 | | - results.filter(r => r.data).length === results.length |
| 49 | + if (Array.isArray(results)) { |
| 50 | + const allResultsHaveData = |
| 51 | + results.filter(r => r.data).length === results.length |
49 | 52 |
|
50 | | - if (response.ok && !results.find(r => r.errors) && allResultsHaveData) { |
51 | | - return results.map(r => r.data) |
| 53 | + if (response.ok && !results.find(r => r.errors) && allResultsHaveData) { |
| 54 | + return results.map(r => r.data) |
| 55 | + } else { |
| 56 | + const errorIndex = results.findIndex(r => r.errors) |
| 57 | + const result = results[errorIndex] |
| 58 | + const errorResult = |
| 59 | + typeof result === 'string' ? { error: result } : result |
| 60 | + throw new ClientError({ ...errorResult, status: response.status }) |
| 61 | + } |
52 | 62 | } else { |
53 | | - const errorIndex = results.findIndex(r => r.errors) |
54 | | - const result = results[errorIndex] |
55 | | - const { query, variables } = requests[errorIndex] |
56 | | - const errorResult = |
57 | | - typeof result === 'string' ? { error: result } : result |
58 | | - throw new ClientError( |
59 | | - { ...errorResult, status: response.status }, |
60 | | - { query, variables }, |
61 | | - ) |
| 63 | + // if it is not an array, there must be an error |
| 64 | + throw new ClientError({ ...results, status: response.status }) |
62 | 65 | } |
63 | 66 | } |
64 | 67 | } |
65 | 68 |
|
66 | | -async function getResults(response: Response): Promise<any> { |
| 69 | +function getResults(response: Response): Promise<any> { |
67 | 70 | const contentType = response.headers.get('Content-Type') |
68 | 71 | if (contentType && contentType.startsWith('application/json')) { |
69 | | - return await response.json() |
| 72 | + return response.json() |
70 | 73 | } else { |
71 | | - return await response.text() |
| 74 | + return response.text() |
72 | 75 | } |
73 | 76 | } |
0 commit comments