Receber por email
← Voltar para o catálogo

GraphQL Mobile

Integração de cliente GraphQL para aplicativos móveis.

1.4kestrelas
Atualizado há 4 meses

Ver no GitHub ↗ Licença: MIT

Como adicionar

/plugin marketplace add a5c-ai/babysitter

O comando exato pode variar conforme o repositório. Confira o README no GitHub.

Para o autor da skill

Cole no README do seu repo

Mostra que sua skill está catalogada na Skillteca, gera backlink e tráfego rastreável.

[![Skillteca](https://www.skillteca.com.br/api/badge/graphql-mobile/svg)](https://www.skillteca.com.br/skills/graphql-mobile)

Skills relacionadas

Ver todas de Automação →

Alerta por categoria

Receba novas skills de Automação toda segunda

1 email curto, só com as skills novas de Automação. 4 minutos de leitura, sem spam, cancela com 1 clique.

Você confirma o email no primeiro envio. Sem spam. Cancela com 1 clique.

Ler descrição completa

GraphQL Mobile Skill

Overview

This skill provides GraphQL client integration capabilities for mobile applications. It enables configuration of Apollo Client, code generation, caching strategies, and real-time subscriptions.

Allowed Tools

  • bash - Execute codegen and build tools
  • read - Analyze GraphQL schemas and queries
  • write - Generate typed operations and configurations
  • edit - Update GraphQL implementations
  • glob - Search for GraphQL files
  • grep - Search for patterns

Capabilities

Apollo Client (React Native)

  1. Client Configuration
  2. Configure Apollo Client
  3. Set up HTTP and WebSocket links
  4. Configure authentication
  5. Handle error policies
  1. Caching
  2. Configure InMemoryCache
  3. Implement type policies
  4. Handle cache normalization
  5. Configure persistence

Code Generation

  1. GraphQL Codegen
  2. Generate TypeScript types
  3. Generate React hooks
  4. Generate fragments
  5. Handle custom scalars

Flutter GraphQL

  1. graphql_flutter
  2. Configure GraphQL client
  3. Implement queries and mutations
  4. Handle subscriptions
  5. Configure caching

Native Clients

  1. Apollo iOS
  2. Configure Apollo iOS client
  3. Generate Swift types
  4. Handle caching
  5. Implement subscriptions
  1. Apollo Android
  2. Configure Apollo Kotlin client
  3. Generate Kotlin types
  4. Handle normalized cache

Real-time

  1. Subscriptions
  2. Configure WebSocket links
  3. Handle reconnection
  4. Implement subscription hooks
  5. Manage active subscriptions

Target Processes

  • graphql-apollo-integration.js - GraphQL implementation
  • offline-first-architecture.js - Offline caching
  • mobile-performance-optimization.js - Query optimization

Dependencies

  • Apollo Client
  • GraphQL Codegen
  • Platform-specific GraphQL libraries

Usage Examples

Apollo Client Setup (React Native)

// apollo/client.ts
import { ApolloClient, InMemoryCache, createHttpLink, split } from '@apollo/client';
import { GraphQLWsLink } from '@apollo/client/link/subscriptions';
import { getMainDefinition } from '@apollo/client/utilities';
import { setContext } from '@apollo/client/link/context';
import { createClient } from 'graphql-ws';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { AsyncStorageWrapper, CachePersistor } from 'apollo3-cache-persist';

const httpLink = createHttpLink({
  uri: 'https://api.example.com/graphql',
});

const wsLink = new GraphQLWsLink(
  createClient({
    url: 'wss://api.example.com/graphql',
    connectionParams: async () => {
      const token = await AsyncStorage.getItem('authToken');
      return { authorization: token ? `Bearer ${token}` : '' };
    },
  })
);

const authLink = setContext(async (_, { headers }) => {
  const token = await AsyncStorage.getItem('authToken');
  return {
    headers: {
      ...headers,
      authorization: token ? `Bearer ${token}` : '',
    },
  };
});

const splitLink = split(
  ({ query }) => {
    const definition = getMainDefinition(query);
    return definition.kind === 'OperationDefinition' && definition.operation === 'subscription';
  },
  wsLink,
  authLink.concat(httpLink)
);

const cache = new InMemoryCache({
  typePolicies: {
    Query: {
      fields: {
        posts: {
          keyArgs: false,
          merge(existing = [], incoming) {
            return [...existing, ...incoming];
          },
        },
      },
    },
  },
});

export const persistor = new CachePersistor({
  cache,
  storage: new AsyncStorageWrapper(AsyncStorage),
});

export const client = new ApolloClient({
  link: splitLink,
  cache,
  defaultOptions: {
    watchQuery: {
      fetchPolicy: 'cache-and-network',
    },
  },
});

GraphQL Codegen Configuration

# codegen.yml
schema: https://api.example.com/graphql
documents: 'src/**/*.graphql'
generates:
  src/generated/graphql.ts:
    plugins:
      - typescript
      - typescript-operations
      - typescript-react-apollo
    config:
      withHooks: true
      withComponent: false
      withHOC: false
      skipTypename: false
      dedupeFragments: true

Query Hook Usage

// features/posts/hooks/usePosts.ts
import { usePostsQuery, useCreatePostMutation } from '../../../generated/graphql';

export function usePosts() {
  const { data, loading, error, refetch, fetchMore } = usePostsQuery({
    variables: { first: 10 },
    notifyOnNetworkStatusChange: true,
  });

  const [createPost] = useCreatePostMutation({
    update(cache, { data }) {
      cache.modify({
        fields: {
          posts(existingPosts = []) {
            const newPostRef = cache.writeFragment({
              data: data?.createPost,
              fragment: PostFragmentDoc,
            });
            return [newPostRef, ...existingPosts];
          },
        },
      });
    },
    optimisticResponse: (variables) => ({
      __typename: 'Mutation',
      createPost: {
        __typename: 'Post',
        id: 'temp-id',
        title: variables.title,
        body: variables.body,
        createdAt: new Date().toISOString(),
      },
    }),
  });

  const loadMore = () => {
    if (data?.posts.pageInfo.hasNextPage) {
      fetchMore({
        variables: {
          after: data.posts.pageInfo.endCursor,
        },
      });
    }
  };

  return {
    posts: data?.posts.edges.map((e) => e.node) ?? [],
    loading,
    error,
    refetch,
    loadMore,
    createPost,
  };
}

Apollo iOS Setup

// Apollo/Network.swift
import Apollo
import ApolloWebSocket

class Network {
    static let shared = Network()

    private(set) lazy var apollo: ApolloClient = {
        let store = ApolloStore(cache: InMemoryNormalizedCache())

        let provider = DefaultInterceptorProvider(store: store)
        let url = URL(string: "https://api.example.com/graphql")!

        let transport = RequestChainNetworkTransport(
            interceptorProvider: provider,
            endpointURL: url
        )

        return ApolloClient(networkTransport: transport, store: store)
    }()
}

Quality Gates

  • Type safety via codegen
  • Query complexity limits
  • Cache consistency verified
  • Subscription reconnection tested

Related Skills

  • rest-api-integration - REST integration
  • offline-storage - Offline caching
  • firebase-mobile - Firebase alternative

Version History

  • 1.0.0 - Initial release
Compartilhar X LinkedIn