UNPKG

1.53 kBPlain TextView Raw
1import type { GraphQLFormattedError } from 'graphql'
2import { type ExecutionResult, GraphQLError } from 'graphql'
3import { isPlainObject } from './prelude.js'
4
5export const parseExecutionResult = (result: unknown): ExecutionResult => {
6 if (typeof result !== `object` || result === null) {
7 throw new Error(`Invalid execution result: result is not object`)
8 }
9
10 let errors = undefined
11 let data = undefined
12 let extensions = undefined
13
14 if (`errors` in result) {
15 if (
16 !Array.isArray(result.errors)
17 || result.errors.some(
18 error => !(isPlainObject(error) && `message` in error && typeof error[`message`] === `string`),
19 )
20 ) {
21 throw new Error(`Invalid execution result: errors is not array of formatted errors`) // prettier-ignore
22 }
23 errors = result.errors.map((error: GraphQLFormattedError) =>
24 error instanceof GraphQLError ? error : new GraphQLError(error.message, error)
25 )
26 }
27
28 // todo add test coverage for case of null. @see https://github.com/jasonkuhrt/graphql-request/issues/739
29 if (`data` in result) {
30 if (!isPlainObject(result.data) && result.data !== null) {
31 throw new Error(`Invalid execution result: data is not plain object`) // prettier-ignore
32 }
33 data = result.data
34 }
35
36 if (`extensions` in result) {
37 if (!isPlainObject(result.extensions)) throw new Error(`Invalid execution result: extensions is not plain object`) // prettier-ignore
38 extensions = result.extensions
39 }
40
41 return {
42 data,
43 errors,
44 extensions,
45 }
46}