UNPKG

graphql-hooks

Version:
80 lines (75 loc) 2.58 kB
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var sha256Browser = require('@aws-crypto/sha256-browser'); var buffer = require('buffer'); var __defProp = Object.defineProperty; var __defProps = Object.defineProperties; var __getOwnPropDescs = Object.getOwnPropertyDescriptors; var __getOwnPropSymbols = Object.getOwnPropertySymbols; var __hasOwnProp = Object.prototype.hasOwnProperty; var __propIsEnum = Object.prototype.propertyIsEnumerable; var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __spreadValues = (a, b) => { for (var prop in b || (b = {})) if (__hasOwnProp.call(b, prop)) __defNormalProp(a, prop, b[prop]); if (__getOwnPropSymbols) for (var prop of __getOwnPropSymbols(b)) { if (__propIsEnum.call(b, prop)) __defNormalProp(a, prop, b[prop]); } return a; }; var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b)); async function sha256(query) { const hash = new sha256Browser.Sha256(); hash.update(query, "utf8"); const hashUint8Array = await hash.digest(); const hashBuffer = buffer.Buffer.from(hashUint8Array); return hashBuffer.toString("hex"); } function isPersistedQueryNotFound(error) { var _a, _b, _c; if (((_a = error == null ? void 0 : error.fetchError) == null ? void 0 : _a.type) === "PERSISTED_QUERY_NOT_FOUND") { return true; } let errors = (_b = error == null ? void 0 : error.graphQLErrors) != null ? _b : []; if (error.httpError) { try { const body = JSON.parse(error.httpError.body); errors = errors.concat((_c = body.errors) != null ? _c : []); } catch (e) { return false; } } return errors.some((e) => e.message === "PersistedQueryNotFound"); } const APQMiddleware = async ({ operation, client, resolve, reject }, next) => { try { operation.extensions = __spreadProps(__spreadValues({}, operation.extensions), { persistedQuery: { version: 1, sha256Hash: await sha256(operation.query) } }); const res = await client.requestViaHttp( __spreadProps(__spreadValues({}, operation), { query: null }), { fetchOptionsOverrides: { method: "GET" } } ); if (!res.error) { return resolve(res); } const { error } = res; if (isPersistedQueryNotFound(error)) { next(); } else { throw error; } } catch (err) { reject(err); } }; exports.APQMiddleware = APQMiddleware; exports.sha256 = sha256;