Logo de Hor Stub Api

Hor Stub Api

Organização
openreachtech
hor-stub-api

Implement a stub GraphQL resolver: a query/mutation resolver that returns hardcoded, schema-accurate data with no DB access and no business logic, so the frontend can develop against the API contract before the real backend exists. Use this skill whenever the user asks to add or edit a stub resolver (a class under server/graphql/resolvers/<audience>/stub/), wants "a fake API the frontend can call now", or needs to migrate a finished stub into a real resolver under actual/.

Visão geral

Publicado poropenreachtech
Repositóriohora-skills-ort-renchan
Nome da habilidadehor-stub-api
Estrelas
32
Forks
0
Arquivos incluídos
Somente instruções
LicençaApache-2.0
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 openreachtech no GitHub. Leia o conteúdo-fonte antes de instalar.

Instalação

Instale a habilidade de IA Hor Stub 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/openreachtech/hora-skills-ort-renchan/tree/main/kit/skills/hor-stub-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/openreachtech/hora-skills-ort-renchan.git /tmp/hora-skills-ort-renchan
mkdir -p .claude/skills
cp -r /tmp/hora-skills-ort-renchan/kit/skills/hor-stub-api .claude/skills/hor-stub-api
Reinicie Claude Code após copiar para que a nova habilidade seja reconhecida.

Use no TypingMind

Ative Hor Stub 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 Hor Stub 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, Hor Stub 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á.

Stub API (schema-accurate stub resolvers)

A skill for implementing stub resolvers: query/mutation resolver classes that return hardcoded, schema-accurate data. They exist so the frontend can build against the API contract while the real backend logic is still unwritten. A stub lives under server/graphql/resolvers/<audience>/stub/{queries,mutations}/ (where <audience> is one of the app's audience folders, e.g. customer / admin); the matching real resolver later lives under server/graphql/resolvers/<audience>/actual/… with the same class name and interface.

The schema the stub must mirror is authored per hor-graphql-schema. The real implementation the stub is eventually replaced by is authored per hor-query-resolver / hor-mutation-resolver; this skill covers only the stub itself and the hand-off to the real resolver.

Grand principle: a stub returns hardcoded literals only — no logic of any kind

Everything a stub's resolve() returns is a hardcoded literal. No DB access, no service calls, no validation, no computation, no conditionals, no map/filter/reduce over input. The single exception is the pagination slice (2).

  • Why literals only: a stub's job is to pin down the contract (the response shape), not to approximate the behavior. Any logic you write in a stub is unverified pseudo-implementation — it can drift from the real rules, the frontend starts depending on it, and the divergence shows up as breakage at migration time. A literal cannot lie about anything except the shape, and the shape is exactly what a stub exists to guarantee.
  • Why schema-accurate: the returned shape must match the GraphQL schema exactly (every required field present, correct types). A stub that omits fields forces the frontend to discover the gap against the real API later — the one failure mode a stub is supposed to prevent.
  • Echo input back only where the schema result mirrors it (e.g. a mutation that returns the id it was given); otherwise return plausible hardcoded ids/values. Echoing is reading a field, not computing — transforming input is already logic and belongs to the real resolver.
js
// Good: every field is a hardcoded literal — the stub pins the shape and nothing else
/** @override */
async resolve ({
  variables: {
    input,
  },
  context,
}) {
  return {
    shippingAddressId: 1003,
  }
}
js
// Avoid: computing values from input in a stub
//   → unverified pseudo-logic the frontend starts depending on; it drifts from the real rules and breaks at migration time
async resolve ({
  variables: {
    input,
  },
}) {
  const normalizedCode = input.postalCode.replace('-', '') // computation — belongs to the real resolver
  return {
    shippingAddressId: normalizedCode.length > 0
      ? 1003
      : null, // conditional — a stub never branches
  }
}

1. Query stub

Extend BaseQueryResolver. schema is a static get returning the camelCase GraphQL operation name. resolve() destructures { variables: { input }, context } and returns literals.

js
import {
  BaseQueryResolver,
} from '@openreachtech/renchan'

/**
 * Stub resolver: shippingCarriers query.
 *
 * @extends {BaseQueryResolver}
 */
export default class ShippingCarriersQueryResolver extends BaseQueryResolver {
  /**
   * get: Operation name.
   *
   * @override
   * @returns {string}
   */
  static get schema () {
    return 'shippingCarriers'
  }

  /**
   * Resolve. Returns hardcoded, schema-accurate data.
   *
   * @override
   */
  async resolve ({
    variables: {
      input: {
        searchParameters,
      },
    },
    context,
  }) {
    const allCarriers = [
      {
        shippingCarrierId: 1,
        shippingCarrierName: 'Alpha Express',
        shippingCarrierCode: 'ALPHA',
      },
      {
        shippingCarrierId: 2,
        shippingCarrierName: 'Beta Logistics',
        shippingCarrierCode: 'BETA',
      },
    ]

    return {
      shippingCarriers: allCarriers,
    }
  }
}
  • If the query takes no input, drop the input destructuring and keep just resolve () or resolve ({ context }).
  • The file name is <Operation>QueryResolver.js, matching the class name.

2. Paginated query stub

When the query is paginated (input.pagination with limit / offset / sort), hardcode a full const all<Things> array of at least 10 records (every value unique), then return the correct page. The slice below is the only operation the whole stub is allowed to do.

js
import {
  BaseQueryResolver,
} from '@openreachtech/renchan'

/**
 * Stub resolver: customerBillingHistories query (paginated).
 *
 * @extends {BaseQueryResolver}
 */
export default class CustomerBillingHistoriesQueryResolver extends BaseQueryResolver {
  /**
   * get: Operation name.
   *
   * @override
   * @returns {string}
   */
  static get schema () {
    return 'customerBillingHistories'
  }

  /**
   * Resolve. Returns the requested page of hardcoded records.
   *
   * @override
   */
  async resolve ({
    variables: {
      input: {
        pagination: {
          limit,
          offset,
          sort,
        },
      },
    },
  }) {
    const allBillingHistories = [
      {
        orderPaymentId: 50001,
        totalPrice: '5450.00',
        paidAt: new Date('2024-01-18T14:00:00.000Z'),
        // ... the rest of the schema-required fields, all hardcoded
      },
      // ... at least 10 hardcoded records total, every value unique
    ]

    const totalRecords = allBillingHistories.length
    const billingHistories = allBillingHistories.slice(offset, offset + limit)

    return {
      billingHistories,
      pagination: {
        limit,
        offset,
        sort,
        totalRecords,
      },
    }
  }
}
  • Use slice(offset, offset + limit) — it returns a copy of the requested page. Do not use splice, which mutates the source array.
  • totalRecords is the array's .length (never a hardcoded number), so the page math stays correct as records are added.
  • Hardcode at least 10 records with every value unique, so the frontend can see paging actually advance and distinguish the records on screen.
  • This slice + .length is the only computation permitted; every field inside the records is a hardcoded literal.

3. Mutation stub

Extend BaseMutationResolver. Same static get schema (), plus a static get errorCodeHash () that spreads super.errorCodeHash. Stubs keep the hash empty — real error codes are added during migration (4).

js
import {
  BaseMutationResolver,
} from '@openreachtech/renchan'

/**
 * Stub resolver: addShippingAddress mutation.
 *
 * @extends {BaseMutationResolver}
 */
export default class AddShippingAddressMutationResolver extends BaseMutationResolver {
  /**
   * get: Operation name.
   *
   * @override
   * @returns {string}
   */
  static get schema () {
    return 'addShippingAddress'
  }

  /**
   * get: Error code hash. Kept empty in a stub.
   *
   * @override
   * @returns {Record<string, string>}
   */
  static get errorCodeHash () {
    return {
      ...super.errorCodeHash,
    }
  }

  /**
   * Resolve. Returns hardcoded, schema-accurate data.
   *
   * @override
   */
  async resolve ({
    variables: {
      input,
    },
    context,
  }) {
    return {
      shippingAddressId: 1003,
    }
  }
}

Echo input back when the result mirrors it — destructure exactly the fields you return:

js
/** @override */
async resolve ({
  variables: {
    input: {
      originObjectCategoryId,
      originObjectUniqueKey,
    },
  },
  context,
}) {
  return {
    originObjectCategoryId,
    originObjectUniqueKey,
    updatedColumnsWithValues: [],
  }
}

4. Migrating a stub to a real resolver

Preserve the interface, swap only the body. The frontend must not notice the switch except that the data becomes real.

  1. Keep the class name, static get schema (), and static get errorCodeHash (). Move the file from …/stub/… to …/actual/….

  2. Fill errorCodeHash with real codes (spread super.errorCodeHash first):

    js
    /** @override */
    static get errorCodeHash () {
      return {
        ...super.errorCodeHash,
    
        InvalidPostalCode: '203.M004.001',
        InvalidPrefecture: '203.M004.002',
      }
    }
  3. Replace the literal return with real work — validate input, run DB/transaction logic through Sequelize models, and format the response with the same shape the stub returned. Structure the real resolver per hor-query-resolver / hor-mutation-resolver (extracted validateInput / transaction callback / formatResponse — not everything inlined in resolve()).

  4. Throwing an error-code key surfaces it via errorCodeHash — this is where the codes added in step 2 come into play.

Finishing checklist

  • Is every returned field a hardcoded literal (no DB, no service calls, no validation, no conditionals, no map/filter/reduce)?
  • Does the returned shape match the GraphQL schema exactly (all required fields, correct types)?
  • Is the file under server/graphql/resolvers/<audience>/stub/{queries,mutations}/, with class name <Operation>QueryResolver / <Operation>MutationResolver and a matching file name?
  • Does static get schema () return the camelCase operation name?
  • Does a mutation stub define static get errorCodeHash () spreading super.errorCodeHash, kept empty?
  • Paginated stub: ≥ 10 hardcoded records with unique values, page via slice(offset, offset + limit) (never splice), totalRecords = array .length?
  • Is input echoed back only where the schema result mirrors it (no transformation of input)?
  • When migrating: same class name / schema / errorCodeHash interface, file moved to actual/, real codes filled in, response shape unchanged?

Perguntas frequentes

O que a habilidade de IA Hor Stub Api faz?

Implement a stub GraphQL resolver: a query/mutation resolver that returns hardcoded, schema-accurate data with no DB access and no business logic, so the frontend can develop against the API contract before the real backend exists. Use this skill whenever the user asks to add or edit a stub resolver (a class under server/graphql/resolvers/<audience>/stub/), wants "a fake API the frontend can call now", or needs to migrate a finished stub into a real resolver under actual/.

Por que usar Hor Stub Api no TypingMind?

Porque basta instalar uma vez para usar com qualquer modelo. Hor Stub 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 Hor Stub Api no TypingMind?

Abra Plugins → Habilidades → Instalar do GitHub no TypingMind e cole https://github.com/openreachtech/hora-skills-ort-renchan/tree/main/kit/skills/hor-stub-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 Hor Stub 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 Hor Stub Api?

Quantos quiser. Desde que o modelo ofereça suporte a habilidades, é possível usar Hor Stub 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 Hor Stub Api é gratuita?

Sim. A habilidade é publicada no GitHub por openreachtech sob a licença Apache-2.0. 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 👇