notion-reference-architecture

jeremylongshore/claude-code-plugins-plus-skills

Проектирование архитектуры продакшен-интеграции с Notion: слои, кэш, ошибки, тесты.

Звёзды2 926
Авторjeremylongshore

Установка

SKILL.md

Notion Reference Architecture

Overview

Production-grade architecture for Notion integrations using @notionhq/client. This skill defines a four-layer architecture — client singleton, repository pattern, service layer, and caching — that scales from simple scripts to enterprise applications, with multi-integration setups, event-driven processing, and testing strategies.

Notion API version: 2022-06-28 | Rate limit: 3 requests/second per integration | Max page size: 100

Prerequisites

  • Node.js 18+ with TypeScript strict mode enabled
  • @notionhq/client v2.x installed (npm install @notionhq/client)
  • A Notion internal integration created at https://www.notion.so/my-integrations
  • NOTION_TOKEN environment variable set with the integration token
  • Target databases/pages shared with the integration via "Add connections"

Instructions

Build the architecture in four layers, bottom-up. Each layer depends only on the ones below it, so wire them in order. The full copy-ready code for every layer lives in the implementation reference — scaffold the project layout first, then follow the steps below.

Step 1: Client singleton with retry and rate limiting

Wrap @notionhq/client in a singleton with explicit rate limiting (Notion caps at 3 req/s per integration) and exponential-backoff retry. Expose separate reader and writer clients so a read-heavy and a write-scoped integration can run side by side and double effective throughput.

// src/notion/client.ts — skeleton (full code in the implementation reference)
export function getReaderClient(): Client { /* singleton, NOTION_READER_TOKEN ?? NOTION_TOKEN */ }
export function getWriterClient(): Client { /* singleton, NOTION_WRITER_TOKEN ?? NOTION_TOKEN */ }
export async function rateLimitedCall<T>(fn: () => Promise<T>): Promise<T> { /* 3 req/s window */ }
export async function withRetry<T>(fn: () => Promise<T>, maxRetries = 3): Promise<T> { /* backoff */ }

See the full singleton, rate limiter, and retry wrapper in the implementation reference (Step 1).

Step 2: Repository and service layers

The repository layer wraps raw Notion API calls with pagination (Notion caps at 100 results per request), type extraction, and error handling. The service layer sits above it with business logic, schema validation, and cache-aware operations. Keep API shape in the repository and domain rules in the service so each is independently testable.

// Layer boundary — full classes in the implementation reference
class NotionDatabaseRepo { queryAll(); getRecords(); create(); getSchema(); }  // API shape
class NotionService { getActiveTasks(); createTask(); validateSchema(); }       // domain rules

See NotionDatabaseRepo, NotionService, and the TTL cache in the implementation reference (Steps 2 and 3).

Step 3: Event-driven processing and testing

Add the event queue, polling-based change detection, and the test suite last. See event-driven processing and testing patterns for the event queue, unit tests with a mocked @notionhq/client, live integration tests, the headless CMS pattern, the project tracker example, and the multi-integration architecture.

Output

Applying this architecture produces:

  • Client singleton with separate reader/writer integrations, rate limiting (3 req/s), and exponential-backoff retry
  • Repository layer (NotionDatabaseRepo) encapsulating all Notion API calls with automatic pagination
  • Service layer (NotionService) with business logic, schema validation, and cache-aware operations
  • TTL cache between the application and the Notion API, reducing redundant reads
  • Event-driven processing with polling-based change detection and typed event handlers
  • Test suite with a mocked @notionhq/client for fast unit tests and conditional live integration tests

Error Handling

IssueCauseSolution
401 UnauthorizedInvalid or expired integration tokenVerify NOTION_TOKEN at https://www.notion.so/my-integrations; tokens do not expire but can be regenerated
404 object_not_foundPage/database not shared with integrationIn Notion, click "..." on the page, select "Add connections", and add the integration
400 validation_error: property not foundProperty name mismatch (case-sensitive)Call databases.retrieve() first to get exact property names; use schema validation before bulk ops
429 rate_limitedExceeded 3 req/s per integrationThe withRetry wrapper handles this automatically; for sustained throughput, use separate reader/writer integrations to double capacity
502/503 server errorsNotion service degradationCheck https://status.notion.so; the retry wrapper auto-recovers with backoff
Stale cache dataCache TTL too long for write-heavy workloadsInvalidate on writes (shown in NotionService.createTask); reduce TTL for volatile databases
Polling misses changesPoll interval too wide or clock skewUse 10s intervals; store last_edited_time from the most recent page, not the system clock

Safety Justification

This skill scaffolds a multi-file TypeScript project, so it needs Write/Edit alongside shell access — a combination that warrants explicit scoping:

  • Bash is scoped, not blanket. Only Bash(npm:*) (install @notionhq/client, run npm test) and Bash(npx:*) (run TypeScript tooling like npx tsc/npx vitest) are granted — no arbitrary subprocesses, no curl-pipe-shell surface.
  • Write/Edit scope is the project source tree. The skill creates files only under the layout shown in the implementation reference (src/notion/, src/repositories/, src/services/, src/cache/, tests/); it never writes credentials or touches files outside the project.
  • No secret handling. NOTION_TOKEN is read from the environment by the generated code at runtime; the skill never echoes, fabricates, or persists token values.

Examples

See the event-driven and testing reference for full examples including Notion as Headless CMS, Project/Task Tracker, and Multi-Integration Architecture patterns.

Resources

  • Notion API Reference — complete endpoint documentation
  • @notionhq/client SDK — official TypeScript/JavaScript SDK
  • Working with Databases — filtering, sorting, pagination
  • Block Types Reference — all supported content block types
  • Authorization Guide — internal integrations and OAuth
  • Status Page — check for Notion service degradation

Next Steps

  • For environment-specific configuration, see notion-multi-env-setup
  • For webhook and polling patterns in depth, see notion-webhooks-events
  • For performance optimization, see notion-performance-tuning
  • For error troubleshooting, see notion-common-errors and notion-advanced-troubleshooting

Вставить в README

Ссылка на карточку для вашего README — без картинок и счётчиков.

[DarkPlay: notion-reference-architecture](https://darkplay.ru/ai/skills/jeremylongshore-claude-code-plugins-plus-skills-notion-reference-architecture)

Похожие скиллы и другие разделы каталога

Популярное в разделе «Скиллы»

Самые востребованные скиллов раздела по установкам и звёздам.

find-skillsvercel-labs · Помогает находить и устанавливать навыки агентов по запросам вроде «как сделать X»…
4 400 000 устан.
grill-memattpocock · Настойчивое интервью для доработки плана или дизайна.
1 600 000 устан.
hyperframesheygen-com · Обязательная точка входа для любых задач по видео, анимации и motion-графике в…
1 600 000 устан.
hyperframes-cliheygen-com · Цикл разработки HyperFrames CLI: init, add, render, preview, publish и другие команды.
1 600 000 устан.
agent-browservercel-labs · CLI для автоматизации браузера для ИИ-агентов: навигация по страницам, заполнение форм…
1 600 000 устан.
media-useheygen-com · Agent Media OS: единый навык для медиа в HyperFrames — BGM, SFX, изображения, голос, LUT.
1 500 000 устан.
hyperframes-registryheygen-com · Установка и подключение блоков реестра в композиции HyperFrames через add и catalog.
1 400 000 устан.
grill-with-docsmattpocock · Настойчивое интервью для доработки плана или дизайна, попутно создающее документацию (ADR…
1 300 000 устан.
improve-codebase-architecturemattpocock · Поиск в кодовой базе возможностей для углубления, визуальный HTML-отчёт о них и детальный…
1 300 000 устан.
tddmattpocock · Разработка через тестирование (TDD): red-green-refactor и интеграционные тесты.
1 300 000 устан.
Похожее в других разделах каталога

Соседние разделы каталога: возможно, нужный инструмент живёт там.

Architectaffaan-m · Специалист по архитектуре ПО для проектирования систем, масштабируемости и принятия…
225 587 ★
Code Architectaffaan-m · Проектирует архитектуру функций, анализируя существующие паттерны и соглашения кодовой…
225 587 ★
Code Exploreraffaan-m · Глубоко анализирует существующие функции кодовой базы, прослеживая пути выполнения…
225 587 ★
Csharp Revieweraffaan-m · Ревьюер C#: конвенции .NET, async, безопасность, nullable-типы, производительность.
225 587 ★
Flutter Revieweraffaan-m · Ревьюер кода Flutter и Dart: виджеты, управление состоянием, идиомы и архитектура.
225 587 ★
Java Revieweraffaan-m · Ревьюер Java для Spring Boot и Quarkus: архитектура, JPA, безопасность и конкурентность.
225 587 ★
Kotlin Revieweraffaan-m · Ревьюер Kotlin и Android/KMP: корутины, Compose, архитектура и типичные ошибки.
225 587 ★
Network Architectaffaan-m · Проектирует корпоративные и распределённые сети с маршрутизацией и автоматизацией.
225 587 ★
Network Config Revieweraffaan-m · Проверяет конфигурации роутеров и свитчей: безопасность, ошибки и риски изменений.
225 587 ★
Opensource Forkeraffaan-m · Форкает проект для open-source: чистит секреты, ссылки и историю git.
225 587 ★

Лучшие ИИ-инструменты для программирования

ИИ для программирования

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

GenAPIGenapi
По запросу
5.0
Notepad++ AINotepad-plus-plus
По запросу
4.9
GitHub CopilotGitHub
По подписке
4.9
Creatium MaxCremax
По запросу
4.8
Emacs AIGnu
По запросу
4.8
KiteKite
По запросу
4.8
Amazon Q DeveloperAmazon
По запросу
4.8
VECTA
Есть бесплатный тариф
4.8
SoftPractice
Есть бесплатный тариф
4.8
VibeForge
Есть бесплатный тариф
4.7

Лучшие ИИ-инструменты для генерации видео

Генерация видео

Подборка нейросетей для генерации и монтажа видео. Инструменты, которые превращают текст в готовые ролики, экономят часы на съемках и постпродакшне. Подходит для SMM-специалистов,

VEED.IOVeed
По запросу
5.0
MootionMootion
По запросу
5.0
FlyviFlyvi
Есть бесплатный тариф
4.9
Google Veo 3.1Google
Платно
4.9
Sora (OpenAI)OpenAI
Платно
4.9
PikaPika
Платно
4.9
captions space
Есть бесплатный тариф
4.8
Клайп
Есть бесплатный тариф
4.8
viralpulse.appViralpulse
По запросу
4.8
Viral Maker AIViral-maker
Есть бесплатный тариф
4.8

Лучшие ИИ-инструменты для генерации текста и копирайтинга

Генерация текста и копирайтинг

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

NeuroscribeNeuroscribe
Есть бесплатный тариф
5.0
GoGPTGogpt
По запросу
5.0
ChatsonicChatsonic
По запросу
4.9
НейроТекстерNeuro-texter
По запросу
4.9
ChatGPTOpenAI
По подписке
4.9
Редактум
Есть бесплатный тариф
4.8
ChadGPTChadgpt
По запросу
4.8
Cosmo ScribeCosmoscribe
Есть бесплатный тариф
4.8
Memo HelperCopilot33
По запросу
4.8
LibraChatLibrachat
Есть бесплатный тариф
4.8