svelte-ux
Version:
- Increment version in `package.json` and commit as `Version bump to x.y.z` - `npm run publish`
59 lines (58 loc) • 2.55 kB
JavaScript
import { setContext, getContext } from 'svelte';
import { writable } from 'svelte/store';
import { print } from 'graphql';
import { merge } from 'lodash-es';
import fetchStore, { initFetchClient } from './fetchStore';
import { decode } from '../utils/json';
const CONTEXT_KEY = {};
export function initGraphClient(config) {
setContext(CONTEXT_KEY, config);
initFetchClient(config.config);
}
export default function graphStore(baseQueryConfig) {
var _a;
const globalConfig = (_a = getContext(CONTEXT_KEY)) !== null && _a !== void 0 ? _a : { url: '/graphql' };
const { subscribe, fetch, refresh, clear, fetchConfig } = fetchStore();
// Save for building derived requests (ex. exports)
const queryConfigStore = writable(baseQueryConfig);
function doFetch(queryConfig) {
var _a, _b, _c;
const mergedQueryConfig = merge({}, baseQueryConfig, queryConfig);
queryConfigStore.set(mergedQueryConfig);
const { query, variables, config } = mergedQueryConfig;
// https://github.com/apollographql/graphql-tag/issues/144
const queryAsString = typeof query === 'object' ? print(query) : query;
const isMutation = queryAsString.toLowerCase().includes('mutation');
const options = merge({
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ query: queryAsString, variables }),
}, (_b = (_a = globalConfig.config) === null || _a === void 0 ? void 0 : _a.options) === null || _b === void 0 ? void 0 : _b.call(_a), (_c = config === null || config === void 0 ? void 0 : config.options) === null || _c === void 0 ? void 0 : _c.call(config));
const mergedFetchConfig = merge({ force: isMutation ? true : undefined }, globalConfig.config, {
as: async (res) => {
// Use custom JSON reviver to convert Date strings to Date objects
// const body = await res.json();
const text = await res.text();
const body = decode(text);
if (body.errors) {
throw body.errors;
}
else {
return body.data;
}
},
options: () => options,
}, config);
return fetch(globalConfig.url, mergedFetchConfig);
}
return {
subscribe,
fetch: doFetch,
refresh,
clear,
queryConfig: queryConfigStore,
fetchConfig,
};
}