Skip to content

Instantly share code, notes, and snippets.

@Eboubaker
Last active November 3, 2021 14:20
Show Gist options
  • Save Eboubaker/9ed4c5850175dab8b5a981e21f418f92 to your computer and use it in GitHub Desktop.
Save Eboubaker/9ed4c5850175dab8b5a981e21f418f92 to your computer and use it in GitHub Desktop.
My custom graphql apollo client request helper
import {DocumentNode} from "graphql";
import apollo from "@/grapthql/apollo"; // pre-configured apollo client (authorization...etc)
/**
* contains apollo request helpers
*/
const request = {
/**
* send an apollo mutate request
* @param mutation the gqlMutation definition
* @param variables any variables required by the gqlMutation
* @param onSuccess a function which will be chained on the promise .then() method,
* it is suggested that the onSuccess method returns the value back to allow other .then() promise-chain methods to consume the value
* @template E the type of the expected result default is Boolean
* @return promise, if the onSuccess function was passed and it didnt return the value back, then you can't consume the value on the next .then() promise-chain
*/
mutate: function <E = boolean>(mutation: DocumentNode, variables?: {}, onSuccess?: (result: E) => void | E): Promise<E> {
const promise = apollo.mutate<E[]>({
mutation: mutation,
variables: variables
}).then(res => Object.values(res.data as E[])[0])
if (onSuccess) {
promise.then(onSuccess)
}
return promise
},
/**
* send an apollo query request
* @param query the gqlQuery definition
* @param variables any variables required by the gqlQuery
* @param onSuccess a function which will be chained on the promise .then() method,
* it is suggested that the onSuccess method returns the value back to allow other .then() promise-chain methods to consume the value
* @template E the type of the expected result
* @return promise, if the onSuccess function was passed and it didnt return the value back, then you can't consume the value on the next .then() promise-chain
*/
query: function <E>(query: DocumentNode, variables?: {}, onSuccess?: (result: E) => void | E): Promise<E> {
const promise = apollo.query<E[]>({
query: query,
variables: variables
}).then(res => Object.values(res.data)[0])
if (onSuccess) {
promise.then(onSuccess)//
}
return promise
}
}
export default request
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment