piral-urql
Version:
Plugin for providing a GraphQL client in Piral.
55 lines • 1.98 kB
JavaScript
import { createRequest } from 'urql';
import { pipe, subscribe } from 'wonka';
function pipeToPromise(source) {
return new Promise((resolve, reject) => {
pipe(source, subscribe(({ data, error }) => {
if (error) {
reject(error);
}
else {
resolve(data);
}
}));
});
}
/**
* Executes a new GraphQL query.
* @param client The client to use as base.
* @param q The GraphQL query to run.
* @param options The options for the query.
*/
export function gqlQuery(client, q, options = {}) {
const { variables, cache, headers = {} } = options;
const request = createRequest(q, variables);
const response = client.executeQuery(request, { requestPolicy: cache, fetchOptions: { headers } });
return pipeToPromise(response);
}
/**
* Executes a new GraphQL mutation.
* @param client The client to use as base.
* @param q The GraphQL mutation to run.
* @param options The options for the mutation.
*/
export function gqlMutation(client, q, options = {}) {
const { variables, headers = {} } = options;
const request = createRequest(q, variables);
const response = client.executeMutation(request, { fetchOptions: { headers } });
return pipeToPromise(response);
}
/**
* Establishes a new GraphQL subscription.
* @param client The client to use as base.
* @param q The GraphQL subscription to establish.
* @param subscriber The callback when new data has arrived.
* @param options The options for the query.
*/
export function gqlSubscription(client, q, subscriber, options = {}) {
const { variables, headers = {} } = options;
const request = createRequest(q, variables);
const response = client.executeSubscription(request, { fetchOptions: { headers } });
const { unsubscribe } = pipe(response, subscribe(({ data, error }) => {
subscriber(data, error);
}));
return unsubscribe;
}
//# sourceMappingURL=queries.js.map