@lucagoslar/graphql-fetch
v1.0.0
Published
A small optionally typed 📊QL client leveraging the fetch API. (~435 B min + gz)
Downloads
2
Maintainers
Readme
@lucagoslar/graphql-fetch
A small optionally typed 📊QL client leveraging the fetch API. (~435 B min + gz)
Index
Usage
- Import, instantiate and set up a client.
import { GraphQLClient } from '@lucagoslar/graphql-fetch';
const resource: string = 'ENDPOINT';
const init: RequestInit = {
mode: 'cors',
headers: {
Authorization: '<auth-scheme> <credentials>',
},
};
const client = new GraphQLClient(resource, init);
- Create a GraphQL query or mutation.
import { gql } from '@lucagoslar/graphql-fetch';
const query = gql`
query Country($code: ID!) {
country(code: $code) {
native
}
}
`;
const variables = {
code: 'DE',
};
- Pass optional parameters when executing a request and handle the response.
const result = await client.request<{ country: { native: string } }>(
query,
variables
);
console.log(result); // { data: { country: { native: 'Deutschland' } }, errors: undefined }
Optionally add a custom fetch function.
// Example with SvelteKit
// +page.server.ts
import type { PageServerLoad } from './$types';
export const load: PageServerLoad = async (request) => {
const result = await client
.customFetch(request.fetch)
.request<{ country: { native: string } }>(query, variables);
return result;
};
API
new GraphQLClient(resource, init?)
resource
: stringinit
: RequestInit
new GraphQLClient#customFetch(fetch)
fetch
: fetch Function
new GraphQLClient#customFetch#request(query, variables?)
query
: stringvariables
: Object
new GraphQLClient#request(query, variables?)
query
: stringvariables
: Object
Bundle size
Note that the bundle size depends on your build configuration.
Contribute
Contributions of any kind are very much appreciated.
Getting started
Install all (dev-)dependencies by running the following.
npm i
Make sure husky is being installed too.
npm run prepare
And off we go …
Build this project with the following.
npm run build