What's the point of GraphQL client libraries over fetch?

preview_player
Показать описание

Рекомендации по теме
Комментарии
Автор

It depends on what proejct needs.
In general -- better not to use GQL-client libraries than to use them.

const gql = String.raw; // then you can use the gql tag to write queries and get the syntax highliting in your IDE

const createGqlQueryRunner =
(uri: string, baseHeaders: Record<string, any>, fetchFn: typeof global.fetch = global.fetch) =>
(query: string, variables?: Record<string, any>, headers?: Record<string, any>): unknown => fetchFn(uri, , {
method: "POST",
headers: { "Content-Type": "application/json", ...baseHeaders, ...headers },
data: JSON.stringify({ query, operationName: getOperationName(query), variables }),
}).then(res => res.ok ? res.json() : Promise.reject(new TypeError(`Failed GQL Query`));


const query = gql`
query SampleQueryOperation {
hello
}
`;


const result = await runGqlQuery(query);

All further improvements are also possible as simple decorators for the GqlQueryRunner.
So, you can start with fetch, and then extend your solution with all other features.

dimitro.cardellini