Logo de Rtk Query Api

Rtk Query Api

Organização
LedgerHQ
rtk-query-api

RTK Query createApi best practices

Visão geral

Publicado porLedgerHQ
Repositórioledger-live
Nome da habilidadertk-query-api
Estrelas
622
Forks
491
Arquivos incluídos
Somente instruções
LicençaMIT
Links
  • Instruções em Markdown

    Um arquivo SKILL.md que o modelo carrega sob demanda, consumindo tokens apenas quando uma solicitação é realmente relevante para a habilidade.

  • Funciona com qualquer LLM

    Habilidades de IA são Markdown simples, não código específico de um provedor, por isso funcionam com GPT, Claude, Gemini, Grok ou um modelo local.

  • Completa em si mesma

    Tudo de que o modelo precisa está nas instruções — sem arquivos extras para sincronizar.

  • Código aberto

    Publicada por LedgerHQ no GitHub. Leia o conteúdo-fonte antes de instalar.

Instalação

Instale a habilidade de IA Rtk Query Api no TypingMind para usá-la com qualquer LLM ou adicione-a a outro agente que leia SKILL.md.

1

Instalar no TypingMind

O TypingMind instala uma habilidade diretamente da pasta dela no GitHub — lê o arquivo SKILL.md, reúne os arquivos de recursos em um pacote e armazena o resultado localmente.

  1. Abra o app e vá para Plugins → Habilidades.
  2. Escolha "Instalar do GitHub".
  3. Cole a URL da pasta da habilidade exibida abaixo e confirme.
    https://github.com/LedgerHQ/ledger-live/tree/develop/.agents/skills/rtk-query-api
  4. Ative a habilidade em cada chat em que quiser disponibilizá-la.
Plugins → Habilidades → Nova habilidade → Via URL GitHub, depois cole a URL da pasta e pressione Continuar.
2

Instalar em outro agente

Qualquer agente que leia o formato Agent Skills pode usar esta habilidade — copie a pasta para o diretório de habilidades desse agente.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/LedgerHQ/ledger-live.git /tmp/ledger-live
mkdir -p .claude/skills
cp -r /tmp/ledger-live/.agents/skills/rtk-query-api .claude/skills/rtk-query-api
Reinicie Claude Code após copiar para que a nova habilidade seja reconhecida.

Use no TypingMind

Ative Rtk Query Api em qualquer chat do TypingMind e o modelo cuida do resto. O nome e a descrição da habilidade ficam no prompt do sistema e, assim que uma solicitação relevante aparece, o modelo carrega as instruções completas automaticamente — sem precisar de acionamento manual e sem consumir tokens até que ela seja realmente usada.

O modelo carrega Rtk Query Api automaticamente assim que uma solicitação é relevante para essa habilidade.

Funciona com qualquer modelo de IA

Habilidades de IA são instruções em Markdown simples, não código específico de um provedor. Por isso, Rtk Query Api não fica vinculada ao modelo para o qual foi criada. Instale-a uma vez no TypingMind e use-a com GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama ou um modelo local executado por conta própria — tudo com suas próprias chaves de API.

  • Carregada apenas quando necessário

    O prompt do sistema contém apenas o nome e a descrição. As instruções são buscadas na primeira solicitação relevante, então uma habilidade sem uso não gera custo.

  • Troque de modelo durante a conversa

    Como a habilidade é composta de instruções, não de código, trocar de modelo não afeta seu funcionamento — o próximo modelo lê o mesmo arquivo SKILL.md.

Instruções da habilidade

Este é o conteúdo de SKILL.md que o modelo carrega. Leia antes de instalar — uma habilidade é um conjunto de instruções que seu modelo seguirá.

RTK Query - createApi

Structure

  • One API slice per base URL / data source — never two createApi calls against the same backend
  • Export generated hooks alongside the API
typescript
// ✅ GOOD - state-manager/api.ts
import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";
import { EntityTags } from "./types";

export const myApi = createApi({
  reducerPath: "myApi",
  baseQuery: fetchBaseQuery({ baseUrl: "/api" }),
  tagTypes: [EntityTags.Entity, EntityTags.Entities],
  endpoints: (build) => ({
    getEntity: build.query<Entity, string>({
      query: (id) => `entities/${id}`,
      providesTags: [EntityTags.Entity],
    }),
  }),
});

export const { useGetEntityQuery } = myApi;

Define tags as enums in state-manager/types.ts:

typescript
export enum EntityTags {
  Entity = "Entity",
  Entities = "Entities",
}

Splitting backend access from use case

In domain/api/, this is the default — not something you reach for once a second use case appears. Always split reaching the backend from what you ask it for:

HalfOwnerContains
Reaching a backend@shared/api-services — one dir per backendBase URL, base query, retry, reducerPath, extraArgument contract
What you ask it for@domain/api-<name>Endpoints, wire schemas, transforms, cache tags, hooks

Doing it upfront costs nothing and means the second use case is a one-line addition rather than a migration. Two createApi calls against one backend would give you two store slices, two caches and two middlewares for one service.

The shared half declares an empty api. The use-case half adds to it with injectEndpoints for endpoints and enhanceEndpoints({ addTagTypes }) for tags. Both mutate and return the same api object, so one reducer, one middleware and one cache serve every use case.

There are no exceptions. If a backend's base query currently needs use-case knowledge — mock handlers keyed by endpoint URL, endpoint-name lookups, response types from its own wire schemas — that is a problem to fix in the base query, not a reason to keep a second createApi.

typescript
// ✅ GOOD - the service api: base query + config. No endpoints, no tags.
export const myServiceApi = createApi({
  reducerPath: "myServiceApi",
  baseQuery: myServiceBaseQuery,
  tagTypes: [],
  endpoints: () => ({}),
});
typescript
// ✅ GOOD - a use case adds its own tags, then its endpoints
export const FIRST_USE_CASE_TAGS = ["Entity"] as const;

export const firstUseCaseApi = myServiceApi
  .enhanceEndpoints({ addTagTypes: FIRST_USE_CASE_TAGS })
  .injectEndpoints({
    endpoints: build => ({
      getEntity: build.query<Entity, string>({
        query: id => `entities/${id}`,
        providesTags: [...FIRST_USE_CASE_TAGS],
      }),
    }),
  });

export const { useGetEntityQuery } = firstUseCaseApi;
  • Cache tags belong to the use case, not the shared api. injectEndpoints does not accept tagTypes, which makes it tempting to declare every tag upfront in the shared file — don't. enhanceEndpoints({ addTagTypes }) widens the tag union in place, so a tag stays next to the endpoints that provide it and adding a use case never means editing a shared file.
  • Register the service api; call endpoints on the use case. Only the injected reference is typed with the endpoints — injectEndpoints cannot retype the original.
  • Injection is a module-level side effect. An endpoint exists only once its use-case module has been evaluated as a value import; a type-only import will not trigger it. Never import an api from @shared/api-services in order to call endpoints on it.
  • A tag-less api has a narrower state type. The registered api declares no tags, so a helper typed on an injected reference (whose use case added some) will not accept an app's State. Type such helpers on the service api.
  • overrideExisting defaults to false — injecting an endpoint name that already exists is silently ignored unless you opt in.

Endpoints

  • Use build.query for GET requests
  • Use build.mutation for POST/PUT/DELETE
  • Type both response and argument: build.query<ResponseType, ArgType>
  • Use void for no arguments: build.query<Data[], void>

Caching & Tags

  • Define tags as enums in types.ts
  • Use providesTags on queries for cache invalidation
  • Use invalidatesTags on mutations to trigger refetch
  • Use keepUnusedDataFor for custom cache duration
typescript
endpoints: (build) => ({
  getItems: build.query<Item[], void>({
    query: () => "items",
    providesTags: [ItemTags.Items],
    keepUnusedDataFor: 60, // seconds
  }),
  addItem: build.mutation<Item, Partial<Item>>({
    query: (body) => ({ url: "items", method: "POST", body }),
    invalidatesTags: [ItemTags.Items],
  }),
}),

Transform Responses

  • Use transformResponse to reshape API data
  • Use transformErrorResponse for custom error handling
typescript
getItems: build.query<Item[], void>({
  query: () => "items",
  transformResponse: (response: ApiResponse) => response.data.items,
}),

Error Handling

  • Always catch errors in custom baseQuery or queryFn
  • Return { data } on success, { error } on failure
typescript
// ✅ GOOD - errors are caught and returned
queryFn: async (arg) => {
  try {
    const data = await fetchData(arg);
    return { data };
  } catch (error) {
    return { error: { status: "CUSTOM_ERROR", data: error } };
  }
},

Registration

Register APIs in reducers/rtkQueryApi.ts, keyed by reducerPath. For a shared backend, register the service api — its endpoints arrive via the use-case packages the view-models import. The registry then reads as a list of the backends the app talks to:

typescript
const APIs = {
  [myApi.reducerPath]: myApi,
  [myServiceApi.reducerPath]: myServiceApi,
};

Two entries whose reducerPath resolves to the same string is a compile error (TS1117: An object literal cannot have multiple properties with the same name), even for computed properties — which is what catches an accidental double-registration of one backend.

Perguntas frequentes

O que a habilidade de IA Rtk Query Api faz?

RTK Query createApi best practices

Por que usar Rtk Query Api no TypingMind?

Porque basta instalar uma vez para usar com qualquer modelo. Rtk Query Api é escrito em Markdown simples, e não em código específico de um provedor, então a mesma habilidade funciona com GPT-5, Claude, Gemini, Grok ou um modelo local — e é possível trocar de modelo no meio do chat sem que ela deixe de funcionar. O TypingMind usa suas próprias chaves de API, então o pagamento é feito diretamente aos provedores, em vez de uma assinatura por licença de usuário, e suas habilidades e chats permanecem no seu próprio armazenamento.

Como instalar Rtk Query Api no TypingMind?

Abra Plugins → Habilidades → Instalar do GitHub no TypingMind e cole https://github.com/LedgerHQ/ledger-live/tree/develop/.agents/skills/rtk-query-api. O TypingMind lê o arquivo SKILL.md e instala a habilidade para que possa ser ativada em cada chat.

Quais modelos de IA podem usar Rtk Query Api?

Qualquer modelo conectado no TypingMind. As habilidades de IA são instruções em Markdown simples, e não código específico de um provedor. Assim, GPT, Claude, Gemini, Grok e modelos locais podem carregar esta habilidade quando uma solicitação corresponder a ela.

Quantos modelos de IA posso usar com Rtk Query Api?

Quantos quiser. Desde que o modelo ofereça suporte a habilidades, é possível usar Rtk Query Api com ele — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama e outros — tudo no TypingMind com suas próprias chaves de API.

A habilidade de IA Rtk Query Api é gratuita?

Sim. A habilidade é publicada no GitHub por LedgerHQ sob a licença MIT. O pagamento é feito apenas ao seu provedor de IA pelos tokens usados.

O que são habilidades de IA?

Uma habilidade de IA é um conjunto reutilizável de instruções que ensina um modelo de IA a realizar uma tarefa específica. Ela segue o formato aberto Agent Skills: um arquivo SKILL.md com nome e descrição, além de scripts, modelos de documento ou arquivos de referência de que o modelo possa precisar. O modelo lê as instruções apenas quando sua solicitação corresponde à habilidade, então uma habilidade instalada não gera custos até ser usada.

Qual é a diferença entre habilidades de IA e plugins ou servidores MCP?

Um plugin ou servidor MCP oferece ao modelo novas ferramentas para chamar — código que é executado em algum lugar e retorna um resultado. Já uma habilidade de IA fornece conhecimento e um processo ao modelo: como abordar uma tarefa, quais etapas seguir e como deve ser um bom resultado. As habilidades são escritas em Markdown simples, por isso não precisam de servidor, chave de API nem ambiente de execução, e funcionam com qualquer modelo.

Ver todos

Crie seu próprio espaço de IA agora

Inscreva-se na nossa newsletter para receber novidades sobre recursos e futuros sorteios 👇