UNPKG

@sparklink-pro/apant

Version:

Apollo & Antd tools

74 lines 2.93 kB
import { __awaiter } from "tslib"; import { gql, useMutation } from '@apollo/client'; import { Kind } from 'graphql'; import { isArray, isPlainObject, isString } from 'lodash-es'; /** * Extract fragments definition from a GraphQL query */ export const getFragments = (query) => query.definitions.filter((def) => def.kind === Kind.FRAGMENT_DEFINITION); /** * Replace one or more fragments from the specified GraphQL query * * @param query The query object to update * @param fragments {string|array|object} The fragments to replace *'TypedDocumentNode<any, OperationVariables>': kind, definitions * @return {object} The updated query object */ export const replaceFragments = (query, fragments) => { const newFragments = isString(fragments) ? [fragments] : fragments; if (!isPlainObject(newFragments) && !isArray(newFragments)) { console.error('Invalid fragments specified. Fragments argument must be an object with the name of the fragments as key and a gql fragment or a fields set as value'); console.error('Example: {myFragmentToReplace: gql`xxx`} or {myFragmentToReplace: "id name'); return query; } const queryFragments = getFragments(query).map((fragment, idx) => { const name = fragment.name.value; const config = Array.isArray(newFragments) ? newFragments[Number(idx)] : newFragments[name]; if (!config) { return fragment; } if (isString(config)) { const type = fragment.typeCondition.name.value; const gqlString = ` fragment ${name} on ${type} ${config[0] !== '{' ? '{' : ''} ${config} ${config[config.length - 1] !== '}' ? '}' : ''} `; try { const fragmentGQL = gql ` ${gqlString} `; return fragmentGQL.definitions[0]; } catch (e) { const result = e.message; console.error(`Error "${result}" while generating fragment from ${'\n'} ${gqlString}`); } } return config; }); // @ts-ignore const definitions = [ // Remove fragments définitions from inital query ...query.definitions.filter((d) => d.kind !== Kind.FRAGMENT_DEFINITION), // Add new fragments ...queryFragments, ]; return { kind: query.kind, loc: query.loc, definitions, }; }; export const parseMutation = (...parameters) => { const [mutation, result] = useMutation(...parameters); return Object.assign(Object.assign({}, result), { mutate: (...a) => __awaiter(void 0, void 0, void 0, function* () { const r = yield mutation(...a); return r; }) }); }; export function m(param) { return Object.assign({ mutate: param[0] }, param[1]); } //# sourceMappingURL=gql.js.map