UNPKG

gqty

Version:

The No-GraphQL Client for TypeScript

56 lines (53 loc) 1.87 kB
import { GraphQLError } from 'graphql'; import { GQtyError } from '../Error/index.mjs'; const defaultResponseHandler = async (response) => { const result = await parseResponse(response); assertExecutionResult(result); handleResponseErrors(result); return result; }; const parseResponse = async (response) => { const text = await response.text().then((text2) => text2.trim() || null); if (response.status >= 400) { throw new GQtyError( `Received HTTP ${response.status} from GraphQL endpoint${text ? `, body: ${text.length > 50 ? text.slice(0, 50) + "..." : text}` : ""}.` ); } if (!text) { throw new GQtyError("Received an empty response from GraphQL endpoint."); } try { const result = JSON.parse(text); if (Array.isArray(result == null ? void 0 : result.errors)) { result.errors = result.errors.map( (error) => new GraphQLError(error.message, error) ); } return result; } catch { throw new GQtyError( `Received malformed JSON response from GraphQL endpoint: ${text.length > 50 ? text.slice(0, 50) + "..." : text}` ); } }; function assertExecutionResult(input) { if (!isExecutionResult(input)) { throw new GQtyError( `Expected response to be an ExecutionResult, received: ${JSON.stringify( input )}` ); } } const isExecutionResult = (input) => { if (typeof input !== "object" || input === null) return false; const value = input; return "data" in value || Array.isArray(value.errors) && value.errors.every((error) => error instanceof GraphQLError); }; const handleResponseErrors = (result) => { var _a; if ((_a = result.errors) == null ? void 0 : _a.length) { throw GQtyError.fromGraphQLErrors(result.errors); } }; export { assertExecutionResult, defaultResponseHandler, handleResponseErrors, isExecutionResult, parseResponse };