webiny-custom-graphql-api
Что он делает
Этот скилл направляет вашего ИИ при добавлении новых конечных точек GraphQL в серверную часть Webiny. Он нужен разработчикам, которым требуются собственные запросы или мутации, использующие сервисы платформы.
Когда использовать
- ✓Когда нужен собственный запрос или мутация GraphQL помимо встроенных.
- ✓Когда резолверу нужно вызывать серверные сервисы, например операции identity или CMS.
- ✓Когда резолверу GraphQL нужны проверки авторизации.
Ссылка на скилл
https://github.com/webiny/webiny-js/blob/next/skills/user-skills/api/graphql-api/SKILL.mdСкопируйте и вставьте её в ваш ИИ (Claude, ChatGPT или Cursor) с просьбой следовать инструкциям.
Как использовать
Самый простой способ: скопируйте сообщение и вставьте его в свой ИИ. Он прочитает скилл и выполнит инструкции.
Готовое сообщение для вставки
Для Claude Code, Codex или Cursor: запустите в папке проекта, и скилл установится.
Скачайте SKILL.md и положите его в папку скиллов вашего агента.
Пример запроса к вашему ИИ
“Добавь запрос GraphQL, который возвращает десять последних заказов вошедшего пользователя, с проверкой прав.”
5 новых скиллов в неделю. 1 минута чтения.
Как это работает
Скилл объясняет, как реализовать фабрику схемы, которая добавляет определения типов и резолверы. Каждый резолвер получает свои зависимости через контейнер, а фабрика экспортируется по умолчанию.
Технический текст (оригинальный SKILL.md)
Оригинальный текст автора на английском, прямо с GitHub.
Custom GraphQL API
TL;DR
Add custom GraphQL queries and mutations using GraphQLSchemaFactory. Implement GraphQLSchemaFactory.Interface, use the schema builder to add type definitions and resolvers (with per-resolver DI), and export with GraphQLSchemaFactory.createImplementation(). Register as <Api.Extension>.
YOU MUST include the full file path with the .ts extension in every src prop. For example, use src={"/extensions/MySchema.ts"}, NOT src={"/extensions/MySchema"}. Omitting the file extension will cause a build failure.
YOU MUST use export default for the createImplementation() call when the file is targeted directly by an Extension src prop. Using a named export (export const Foo = SomeFactory.createImplementation(...)) will cause a build failure. Named exports are only valid inside files registered via createFeature.
The GraphQLSchemaFactory Pattern
The execute method receives a schema builder and returns it after adding type defs and resolvers.
// extensions/mySchema/MyGraphQLSchema.ts
import { GraphQLSchemaFactory } from "webiny/api/graphql";
class MySchema implements GraphQLSchemaFactory.Interface {
async execute(
builder: GraphQLSchemaFactory.SchemaBuilder
): Promise<GraphQLSchemaFactory.SchemaBuilder> {
builder.addTypeDefs(/* GraphQL */ `
extend type Query {
hello: String!
}
`);
builder.addResolver({
path: "Query.hello",
resolver: () => {
return () => "Hello, World!";
}
});
return builder;
}
}
export default GraphQLSchemaFactory.createImplementation({
implementation: MySchema,
dependencies: []
});
Register as an extension:
// extensions/mySchema/Extension.tsx
import React from "react";
import { Api } from "webiny/extensions";
export const MySchema = () => {
return <Api.Extension src={"@/extensions/mySchema/MyGraphQLSchema.ts"} />;
};
Schema Builder API Reference
| Method | Description |
|---|---|
builder.addTypeDefs(typeDefs: string) |
Add GraphQL type definitions (use extend type Query/Mutation to add to existing root types) |
builder.addResolver<TArgs>(config) |
Add a resolver with optional per-resolver DI dependencies |
addResolver Config
builder.addResolver<TArgs>({
path: "TypeName.fieldName", // dot-separated path
dependencies: [SomeAbstraction], // optional: DI tokens resolved at request time
resolver: (dep1, dep2, ...) => { // factory: receives resolved deps
return ({ parent, args, context, info }) => {
// actual resolver logic
return result;
};
}
});
Key points:
path: Dot-separated GraphQL type path, e.g."Query.hello","Mutation.createOrder","OrderMutation.create"dependencies: Array of DI abstraction tokens. Resolved per-request fromcontext.container, not at schema build timeresolver: A factory function that receives resolved dependencies and returns the actual resolver function- Resolver params: The inner function receives
{ parent, args, context, info }(named object, not positional)
Per-Resolver Dependency Injection
Dependencies in addResolver are resolved at request time from the request-scoped container. This is different from class-level constructor DI — it gives each resolver access to request-scoped services like identity and tenant context.
import { GraphQLSchemaFactory } from "webiny/api/graphql";
import { IdentityContext } from "webiny/api/security";
class WhoAmISchema implements GraphQLSchemaFactory.Interface {
async execute(
builder: GraphQLSchemaFactory.SchemaBuilder
): Promise<GraphQLSchemaFactory.SchemaBuilder> {
builder.addTypeDefs(/* GraphQL */ `
extend type Query {
whoAmI: String
}
`);
builder.addResolver({
path: "Query.whoAmI",
dependencies: [IdentityContext],
resolver: (identityContext: IdentityContext.Interface) => {
return () => {
const identity = identityContext.getIdentity();
return `Hello, ${identity.displayName}!`;
};
}
});
return builder;
Частые вопросы
Почему экспорт должен быть экспортом по умолчанию?
Скилл говорит, что именованный экспорт вызывает ошибку сборки, когда файл регистрируется напрямую.
Нужно ли расширение файла в пути?
Да. Путь к исходнику должен содержать расширение .ts.
Могут ли резолверы использовать серверные сервисы?
Да. Скилл описывает внедрение таких сервисов, как identity, tenancy и операции CMS, в схему.
Подробности
Оригинальное описание автора
Adding custom GraphQL queries and mutations using GraphQLSchemaFactory. Use this skill when the developer wants to add custom GraphQL endpoints, create custom queries or mutations, add business logic to the API layer, build custom resolvers, inject backend services (identity, tenancy, CMS use-cases) into their GraphQL schema, add authorization checks to resolvers, or build dynamic GraphQL inputs from CMS models. Covers the full pattern from simple queries to complex resolvers with dependency injection and permission transformers.
repo: webiny/webiny-js
Популярность
- Звёзды на GitHub
- 8.1k
- Место в рейтинге
- #12587
- Лицензия
- —
- Обновлён
- 02.11.2026
Комментарии
- …
Другие скиллы из этого репозитория
prd-to-plan
8.1kПомогает агенту превратить документ с требованиями к продукту в поэтапный план из небольших сквозных срезов, сохраненный как файл Markdown.
webiny-admin-architect
8.1kУчит агента создавать экраны администратора для платформы Webiny, используя слои бизнес-логики и паттерн presenter.
webiny-admin-permissions
8.1kУчит агента добавлять элементы управления правами в экраны администратора Webiny, включая автоматически генерируемые формы прав и проверки показа или скрытия.
webiny-form-model
8.1kУчит агента создавать формы в Webiny с помощью декларативного конструктора полей, макетов, валидации и условных правил.
Похожие скиллы
api-connector-builder
280kАгент создаёт новые подключения к API по существующему шаблону. Используйте, когда нужна ещё одна интеграция без нового способа делать то же самое.
api-design
280kПомогает агенту проектировать REST API по лучшим практикам: как API общаются, как показываются ошибки и как организовать данные.
backend-patterns
280kПомогает агенту с архитектурными паттернами серверной части и оптимизацией баз данных. Полезен при создании и проверке серверного кода.