Перейти к содержанию
Skillpedia
API и серверы (бэкенд)8.1k · #12598

webiny-api-cms-content-models

Что он делает

Этот скилл направляет вашего ИИ при создании или изменении моделей контента CMS в проекте Webiny через код. Он нужен разработчикам, которые хотят, чтобы структуры данных были описаны в коде под контролем версий.

Когда использовать

  • ✓Когда вы хотите создать модель контента, например товары или записи блога, в коде.
  • ✓Когда полям нужна валидация или ссылки на другие модели.
  • ✓Когда нужно выбрать подходящее отображение поля в админке для данного типа.

Ссылка на скилл

https://github.com/webiny/webiny-js/blob/next/skills/user-skills/content-models/SKILL.md

Скопируйте и вставьте её в ваш ИИ (Claude, ChatGPT или Cursor) с просьбой следовать инструкциям.

Как использовать

Самый простой способ: скопируйте сообщение и вставьте его в свой ИИ. Он прочитает скилл и выполнит инструкции.

Готовое сообщение для вставки

Используй этот скилл, чтобы помочь мне: https://github.com/webiny/webiny-js/blob/next/skills/user-skills/content-models/SKILL.md Прочитай файл SKILL.md по этой ссылке и следуй его инструкциям в моей задаче.
Хотите, чтобы ваш ИИ сам находил такие скиллы?Установите бесплатный MCP Skillpedia: одна строка, и перед каждой задачей он ищет среди 15 000+ скиллов.Установить за 1 минуту →

Пример запроса к вашему ИИ

“Создай модель контента для товаров в коде с названием, ценой и ссылкой на модель категорий.”

5 новых скиллов в неделю. 1 минута чтения.

Как это работает

Скилл показывает класс модели, который использует цепочный конструктор, чтобы объявить поля, макеты, поля заголовка и имена API. Модель регистрируется в файле конфигурации проекта.

Технический текст (оригинальный SKILL.md)

Оригинальный текст автора на английском, прямо с GitHub.

Creating Content Models via Code

TL;DR

Content models are created using the ModelFactory pattern. You define a class implementing ModelFactory.Interface, use the fluent ModelFactory.Builder API to declare fields, validators, layout, and API names, then export with ModelFactory.createImplementation(). Register in webiny.config.tsx as <Api.Extension>.

The ModelFactory Pattern

Every code-based content model follows the same structure:

import { ModelFactory } from "webiny/api/cms/model";

class MyModelImpl implements ModelFactory.Interface {
  async execute(builder: ModelFactory.Builder) {
    return [
      builder
        .public({ modelId: "myModel", name: "My Model", group: "ungrouped" })
        .description("Description of the model")
        .fields(fields => ({
          // field definitions here
        }))
        .layout([/* row definitions */])
        .titleFieldId("fieldId")
        .singularApiName("MyModel")
        .pluralApiName("MyModels")
    ];
  }
}

export default ModelFactory.createImplementation({
  implementation: MyModelImpl,
  dependencies: []
});

Register in webiny.config.tsx:

<Api.Extension src={"/extensions/MyModel.ts"} />

YOU MUST include the full file path with the .ts extension in the src prop. For example, use src={"/extensions/MyModel.ts"}, NOT src={"/extensions/MyModel"}. 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 MyModel = ...) will cause a build failure. Named exports are only valid inside files registered via createFeature.

Model Configuration Methods

Method Purpose
.public({ modelId, name, group }) Creates a public model (accessible via Read API). modelId is the internal DB identifier. group organizes it in the Admin sidebar.
.description("...") Model description shown in Admin UI
.fields(fields => ({ ... })) Define all fields using the fluent field builder
.layout([["field1", "field2"], ["field3"]]) Arrange fields in rows in the Admin editor. Each inner array is one row.
.titleFieldId("name") Which field to use as the entry's display title
.descriptionFieldId("message") Which field to use as the entry's description
.singularApiName("Product") Singular name for GraphQL queries (e.g., getProduct)
.pluralApiName("Products") Plural name for GraphQL queries (e.g., listProducts)
.singleEntry() Makes the model a singleton (only one entry can exist). Automatically adds
Частые вопросы

Как регистрируется модель?

Как расширение API в файле конфигурации webiny, с полным путем к файлу с расширением .ts.

Можно ли вкладывать поля?

Да. Скилл охватывает вложенные макеты внутри полей типа объект и динамическая зона.

Охватывает ли он выбор типов отображения полей?

Да. Он объясняет, какое отображение в админке использовать для каждого типа поля.

Подробности

Оригинальное описание автора

Creating Headless CMS content models via code using the ModelFactory pattern. Use this skill when the developer wants to create, modify, or understand content model definitions, define fields and validators, set up reference fields between models, configure field layouts (including nested layouts inside object or dynamicZone fields), pick the correct Admin UI renderer for a field type (textInput/textInputs, lexicalEditor/lexicalEditors, file/files, objectAccordionSingle/objectAccordionMultiple, etc.), or work with the ModelFactory builder API. Also covers field types (text, longText, number, b

repo: webiny/webiny-js

Популярность

Звёзды на GitHub
8.1k
Место в рейтинге
#12598
Лицензия
—
Обновлён
02.11.2026

Полезен ли этот скилл?

0

Войдите , чтобы голосовать.

Комментарии

  • …

Другие скиллы из этого репозитория

Похожие скиллы