Skip to content

yoleoagain/graphql-codegen-svelte-apollo

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

55 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

GraphQL code generator for Apollo and Svelte

GraphQL Code Generator plugin to use Apollo in Svelte with full Typescript support. Because Svelte and Apollo share the same reactive programming, Apollo queries are treated like Svelte store. Hence that generator is all you need if you want to use Apollo with Svelte. See a live example here, the code for this is in the /example folder

Motivation

Apollo and graphql-code-generator are a powerfull combination for data management in the front-end. Unlike other big frameworks, Svelte was still missing a graphql-code-generator plugin for client queries. It turns out that Svelte with its reactive programming, is particularly well designed to be used together with Apollo

Note

graphql-codegen-svelte-apollo is a plugin for graphql-code-generator ecosystem, please refer to their website for documentation relative to the configuration in codegen.yml

Installation

npm i -S graphql

npm i -D @graphql-codegen/cli @graphql-codegen/typescript @graphql-codegen/typescript-operations graphql-codegen-svelte-apollo

Configuration

  • clientPath (default: null): Path to the apollo client for this project (should point to a file with an apollo-client as default export)
  • asyncQuery (default: null): By default, the plugin only generate observable queries, sometimes it may be useful to generate promise-based queries

Note: typescript and typescript-operations plugins are required.

Example config

overwrite: true
schema:
    - 'https://myschema/graphql'
documents:
    - 'src/**/*.{graphql,gql,ts}'
generates:
    output.ts:
        plugins:
            - 'typescript'
            - 'typescript-operations'
            - 'graphql-codegen-svelte-apollo'
        config:
          clientPath: "PATH_TO_APOLLO_CLIENT"
          asyncQuery: true
hooks:
    afterAllFileWrite:
        - prettier --write

Usage example

Take for example this query that will request all transactions for one ethereum address

# app.gql

fragment TransactionFragment on TransactionDescription {
    contractAddress
    from
    gasUsed
    gasPrice
    input
    isError
    to
    value
}

query Transactions($address: String) {
    transactions(address: $address) {
        ...TransactionFragment
    }
}

graphql-code-generator will generate:

export const TransactionsDoc = gql`
    fragment TransactionFragment on TransactionDescription {
        contractAddress
        from
        gasUsed
        gasPrice
        input
        isError
        to
        value
    }

    query Transactions($address: String) {
        transactions(address: $address) {
            ...TransactionFragment
        }
    }
`;

export const Transactions = (
  options: Omit<QueryOptions<TransactionsQueryVariables>, "query">
): Readable<
  ApolloQueryResult<TransactionsQuery> & {
    query: ObservableQuery<TransactionsQuery, TransactionsQueryVariables>;
  }
> => {
  const q = client.watchQuery({
    query: TransactionsDoc,
    ...options,
  });
  var result = readable<
    ApolloQueryResult<TransactionsQuery> & {
      query: ObservableQuery<TransactionsQuery, TransactionsQueryVariables>;
    }
  >(
    { data: null, loading: true, error: null, networkStatus: 1, query: null },
    (set) => {
      q.subscribe((v) => {
        set({ ...v, query: q });
      });
    }
  );
  return result;
};

And use it as follow in your svelte file:

<script lang="ts">
  import { Transactions } from "codegen";

  var address = "0x0000000000000000000000000000"
  $: t = Transactions({ address });
</script>

<ul>
    {#each $t?.data?.transactions || [] as transaction}
        <li>Sent transaction from {transaction.from} to {transaction.to}</li>
    {/each}
</ul>

Sometimes, you may need/prefer to have an async query (only available with asyncQuery option set to true)

<script lang="ts">
  import { AsyncTransactions } from "codegen";

  var address = "0x0000000000000000000000000000"
</script>

<ul>
  {#await AsyncTransactions({ address })}
    Loading...
  {:then transactions}
    {#each transactions || [] as transaction}
        <li>Sent transaction from {transaction.from} to {transaction.to}</li>
    {/each}
  {/await}
</ul>

For a complete example implementation refer to the example folder

About

Generator plugin that brings Apollo into your Svelte application

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages

  • TypeScript 75.7%
  • JavaScript 12.3%
  • Svelte 10.7%
  • Other 1.3%