Логотип Hor Resolver Validator

Hor Resolver Validator

Организация
openreachtech
hor-resolver-validator

Implement input-validation classes for GraphQL resolvers under app/validator/forResolver/<endpoint>/{queries,mutations}/, extending BaseInputValidator and delegating value checks to @openreachtech/mentsu-value-inspector. Use this skill whenever the user asks to validate a resolver's input — presence, number, integer, pagination, enum/keyword checks — via a `*InputValidator` class whose failing predicate raises the matching InvalidXxx error.

Обзор

Издательopenreachtech
Репозиторийhora-skills-ort-renchan
Название навыкаhor-resolver-validator
Звёзды
32
Форки
0
Встроенные файлы
2
ЛицензияApache-2.0
Ссылки
  • Инструкции в формате Markdown

    Файл SKILL.md, который модель загружает по необходимости, поэтому токены расходуются только при подходящем запросе.

  • Работает с любой языковой моделью

    Навыки ИИ — это обычный Markdown, а не код для конкретного поставщика, поэтому они работают с GPT, Claude, Gemini, Grok и локальными моделями.

  • Файлы в комплекте: 2

    Скрипты, шаблоны и справочные материалы, которые модель может читать во время работы. Файлы доступны только для чтения и никогда не выполняются.

  • Открытый исходный код

    Опубликовано на GitHub: openreachtech. Перед установкой изучите исходные материалы.

Установка

Установите навык ИИ Hor Resolver Validator в TypingMind, чтобы использовать его с любой LLM, или добавьте его в другой агент, который умеет читать SKILL.md.

1

Установка в TypingMind

TypingMind устанавливает навык прямо из его папки на GitHub: читает SKILL.md, собирает файлы ресурсов и сохраняет результат локально.

  1. Откройте приложение и перейдите в раздел «Плагины → Навыки».
  2. Выберите «Установить из GitHub».
  3. Вставьте указанную ниже ссылку на папку навыка и подтвердите установку.
    https://github.com/openreachtech/hora-skills-ort-renchan/tree/main/kit/skills/hor-resolver-validator
  4. Включите навык в каждом чате, где хотите его использовать.
Плагины → Навыки → Новый навык → По ссылке GitHub, затем вставьте ссылку на папку и нажмите «Продолжить».
2

Установка в другом агенте

Любой агент с поддержкой формата Agent Skills может использовать этот навык — скопируйте папку в каталог навыков этого агента.

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-resolver-validator .claude/skills/hor-resolver-validator
После копирования перезапустите Claude Code, чтобы загрузить новый навык.

Использование в TypingMind

Включите навык Hor Resolver Validator в любом чате TypingMind, и дальше модель всё сделает сама. Его название и описание хранятся в системном промпте, а при появлении подходящего запроса модель сама загружает полные инструкции. Вам не нужно вызывать навык вручную, и до фактического использования он не расходует токены.

Модель сама загружает навык Hor Resolver Validator, как только появляется подходящий для него запрос.

Работает с любой моделью ИИ

Навыки ИИ — это обычные инструкции в Markdown, а не код для конкретного поставщика, поэтому навык Hor Resolver Validator не привязан к модели, для которой он был создан. Установите его один раз в TypingMind и используйте с GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama или локальной моделью, которую запускаете самостоятельно, — со своими API-ключами.

  • Загружается только при необходимости

    Системный промпт содержит только название и описание. Инструкции загружаются при первом подходящем запросе, поэтому неиспользуемый навык не расходует токены.

  • Меняйте модели прямо в чате

    Навык состоит из инструкций, а не кода, поэтому смена модели не нарушает его работу: новая модель читает тот же файл SKILL.md.

Инструкции навыка

Это содержимое файла SKILL.md, которое загружает модель. Прочитайте его перед установкой: навык — это инструкции, которым будет следовать ваша модель.

Resolver Validator

A skill for writing the *InputValidator classes that GraphQL resolvers use to reject bad input. A validator extends BaseInputValidator and declares a list of [predicate, ErrorConstructor] entries; the base runs them and, for the first predicate that returns false, raises that entry's error. Per-value checks (presence / number / integer / positive-integer …) are delegated to @openreachtech/mentsu-value-inspector, imported directly (it is a published module — use it from the package, not a local wrapper).

The support classes (BaseInputValidator, NormalPaginationInputValidator) ship with renchan-boilerplate under app/validator/forResolver/; the inspectors come from the @openreachtech/mentsu-value-inspector module.

Grand principle: declare [predicate, error] entries, let the base run them

A validator is a BaseInputValidator subclass whose only required override is generateValidationEntries() — it returns Array<[() => boolean, RenchanGraphqlErrorCtor]>. Each entry pairs a predicate (returns true when that rule passes) with the error constructor to raise when it fails. The base holds this.input and this.errorHash, iterates the entries, and throws the error of the first failing predicate.

  • Predicates are small isValidX() methods that read this.input and return a boolean. They use the inspector classes and/or composed sub-validators — they never throw.
  • Errors come from this.errorHash (the resolver's error hash, injected into the validator), so each InvalidXxx maps to the resolver's errorCodeHash code.
  • Reuse shared validators (e.g. pagination) by composing them inside entries, not by re-implementing limit/offset/sort.
js
import {
  IntegerValueInspector,
} from '@openreachtech/mentsu-value-inspector'

import BaseInputValidator from '../../BaseInputValidator.js'
import PaginationInputValidator from '../../NormalPaginationInputValidator.js'

const VALID_SORT_COLUMNS = [
  'labelName',
  'fieldPath',
]

/**
 * Class for validating input of the emailInsertableVariables query
 *
 * @extends {BaseInputValidator<ErrorHash, EmailInsertableVariablesInput>}
 */
export default class EmailInsertableVariablesInputValidator extends BaseInputValidator {
  /**
   * Generate validation entries
   *
   * @override
   * @returns {Array<[() => boolean, RenchanGraphqlErrorCtor]>}
   */
  generateValidationEntries () {
    const paginationInputValidator = this.createPaginationInputValidator()

    return [
      [
        () => paginationInputValidator.isValidLimit(),
        this.errorHash.InvalidPaginationLimit,
      ],
      [
        () => paginationInputValidator.isValidOffset(),
        this.errorHash.InvalidPaginationOffset,
      ],
      [
        () => paginationInputValidator.isValidSort(),
        this.errorHash.InvalidPaginationSort,
      ],
      [
        () => this.isValidKeyword(),
        this.errorHash.InvalidKeyword,
      ],
      [
        () => this.isValidOriginObjectCategoryId(),
        this.errorHash.InvalidOriginObjectCategoryId,
      ],
    ]
  }

  // ... isValidX() predicates + create*Inspector helpers (see validator-pattern.md) ...
}

Directory & naming

  • Validators: app/validator/forResolver/<endpoint>/<operation-kind>/<Operation>InputValidator.js
    • <endpoint> tracks the GraphQL endpoint the resolver belongs to (user, customer, admin, …) — it changes per endpoint.
    • <operation-kind> is queries or mutations.
    • e.g. app/validator/forResolver/user/queries/EmailInsertableVariablesInputValidator.js, app/validator/forResolver/user/mutations/CreateFooInputValidator.js.
  • Shared under app/validator/forResolver/: BaseInputValidator.js and reusable validators such as NormalPaginationInputValidator.js (default-exported, commonly imported as PaginationInputValidator).
  • Inspectors: imported directly from @openreachtech/mentsu-value-inspector (ValueInspector / NumberValueInspector / IntegerValueInspector) (inspector-api.md).
  • Class name = <Operation>InputValidator (PascalCase, matching the resolver's schema).

Predicates & the inspector

Each rule is an isValidX() method. For value-shape checks, build an inspector via a small create*ValueInspector({ value }) helper and call its methods:

js
isValidOriginObjectCategoryId () {
  const inspector = this.createIntegerValueInspector({
    value: this.input.originObjectCategoryId,
  })

  // the module has no isPositiveInteger — compose it (string-tolerant *Like)
  return inspector.isIntegerLike()
    && inspector.isPositiveNumberLike()
}

createIntegerValueInspector ({
  value,
}) {
  return IntegerValueInspector.create({
    value,
  })
}
  • Optional field idiom: return true early when the field is absent, then check the shape — e.g. if (!keyword) { return true } before return typeof keyword === 'string'.
  • The *Like methods accept numeric strings, which is what you want at the GraphQL boundary; there is no isPositiveInteger, so compose it (inspector-api.md).

Error hash & resolver wiring

The resolver declares the codes and passes its errorHash into the validator:

js
/** @override */
static get errorCodeHash () {
  return {
    ...super.errorCodeHash,

    InvalidKeyword: '400.C001.001',
    InvalidOriginObjectCategoryId: '400.C001.002',
    InvalidPaginationLimit: '400.C001.003',
    InvalidPaginationOffset: '400.C001.004',
    InvalidPaginationSort: '400.C001.005',
  }
}

/** @override */
async resolve ({
  variables: {
    input,
  },
  context,
}) {
  EmailInsertableVariablesInputValidator
    .create({
      input,
      errorHash: this.errorHash,
    })
    .validate()

  // ... input is now trusted ...
}

create({ input, errorHash }) and validate() come from BaseInputValidator. A resolver that decides itself when to throw calls validateInput(), which returns the error or null.

Testing

Predicates are pure booleans, so unit-test them (and generateValidationEntries) with the hoc-jest skill: feed inputs, assert isValidX() results and that invalid input raises the expected InvalidXxx.

Detail files

  • inspector-api.md — the @openreachtech/mentsu-value-inspector API (strict vs *Like, presence / number / integer, composing positive-integer, cheat sheet)
  • validator-pattern.md — the full validator template (generateValidationEntries, predicates, inspector helpers, composed pagination, typedefs), the BaseInputValidator contract, resolver wiring, and testing

Встроенные файлы

Модель читает эти файлы по мере необходимости, пока навык загружен. Они доступны только для чтения и никогда не выполняются.

Часто задаваемые вопросы

Что делает навык ИИ Hor Resolver Validator?

Implement input-validation classes for GraphQL resolvers under app/validator/forResolver/<endpoint>/{queries,mutations}/, extending BaseInputValidator and delegating value checks to @openreachtech/mentsu-value-inspector. Use this skill whenever the user asks to validate a resolver's input — presence, number, integer, pagination, enum/keyword checks — via a `*InputValidator` class whose failing predicate raises the matching InvalidXxx error.

Зачем использовать Hor Resolver Validator в TypingMind?

Потому что вы устанавливаете навык один раз и используете его с любой моделью. Hor Resolver Validator — это обычный текст в формате Markdown, а не код для конкретного поставщика, поэтому один и тот же навык работает с GPT-5, Claude, Gemini, Grok или локальной моделью. Вы можете менять модель прямо во время чата, и навык продолжит работать. TypingMind использует ваши собственные ключи API, поэтому вы платите поставщикам напрямую, а не оформляете подписку с оплатой за каждое место. Ваши навыки и чаты остаются в вашем собственном хранилище.

Как установить Hor Resolver Validator в TypingMind?

В TypingMind откройте «Плагины → Навыки → Установить из GitHub» и вставьте https://github.com/openreachtech/hora-skills-ort-renchan/tree/main/kit/skills/hor-resolver-validator. TypingMind прочитает файл SKILL.md, включит сопутствующие файлы в пакет и установит навык, который можно включать отдельно для каждого чата.

Какие модели ИИ могут использовать Hor Resolver Validator?

Любая модель, которую вы подключите в TypingMind. Навыки ИИ — это обычные инструкции в формате Markdown, а не код для конкретного поставщика, поэтому GPT, Claude, Gemini, Grok и локальные модели могут загружать этот навык, когда запрос ему соответствует.

Со сколькими моделями ИИ можно использовать Hor Resolver Validator?

С любым количеством. Если модель поддерживает навыки, вы можете использовать с ней Hor Resolver Validator: GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama и другие — всё в TypingMind с вашими собственными ключами API.

Бесплатен ли навык ИИ Hor Resolver Validator?

Да. Навык опубликован на GitHub автором openreachtech по лицензии Apache-2.0. Вы платите только своему поставщику ИИ за использованные токены.

Что такое навыки ИИ?

Навык ИИ — это многоразовый набор инструкций, который объясняет модели ИИ, как выполнять конкретную задачу. Он соответствует открытому формату Agent Skills: файл SKILL.md с названием и описанием, а также любые скрипты, шаблоны или справочные файлы, которые могут понадобиться модели. Модель читает инструкции, только когда ваш запрос соответствует навыку, поэтому установленный навык ничего не стоит, пока не используется.

Чем навыки ИИ отличаются от плагинов и серверов MCP?

Плагин или сервер MCP даёт модели новые инструменты для вызова — код, который где-то выполняется и возвращает результат. Навык ИИ вместо этого даёт модели знания и порядок действий: как подойти к задаче, какие шаги выполнить и каким должен быть хороший результат. Навыки — это обычный текст в формате Markdown, поэтому им не нужны сервер, ключ API или среда выполнения, и они работают с любой моделью.

Все

Создайте свою рабочую ИИ-среду сейчас

Подпишитесь на нашу рассылку, чтобы узнавать о новых функциях и предстоящих розыгрышах 👇