gqty
Version:
The No-GraphQL Client for TypeScript
64 lines (59 loc) • 2.13 kB
JavaScript
;
Object.defineProperty(exports, '__esModule', { value: true });
const graphql = require('graphql');
const index = require('../Error/index.js');
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 index.GQtyError(
`Received HTTP ${response.status} from GraphQL endpoint${text ? `, body: ${text.length > 50 ? text.slice(0, 50) + "..." : text}` : ""}.`
);
}
if (!text) {
throw new index.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 graphql.GraphQLError(error.message, error)
);
}
return result;
} catch {
throw new index.GQtyError(
`Received malformed JSON response from GraphQL endpoint: ${text.length > 50 ? text.slice(0, 50) + "..." : text}`
);
}
};
function assertExecutionResult(input) {
if (!isExecutionResult(input)) {
throw new index.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 graphql.GraphQLError);
};
const handleResponseErrors = (result) => {
var _a;
if ((_a = result.errors) == null ? void 0 : _a.length) {
throw index.GQtyError.fromGraphQLErrors(result.errors);
}
};
exports.assertExecutionResult = assertExecutionResult;
exports.defaultResponseHandler = defaultResponseHandler;
exports.handleResponseErrors = handleResponseErrors;
exports.isExecutionResult = isExecutionResult;
exports.parseResponse = parseResponse;