当前位置: 首页 > Skill >

Publish Wiki Pages

Publish Wiki Pages

Publish Wiki Pages

将 Markdown内容发布到 Wiki.js,保持格式和元数据。用于创建或更新 Wiki 页面,或将笔记/文章转换为 Wiki 格式。

1.2.0 2026.11.13 235
获取Skill文件查看使用说明
作 者:江川 许可证: 更新时间:2026.11.13
本文目录展开

Wiki Publisher

Publish markdown content to Wiki.js with proper formatting and metadata handling.

When to Use

Use this skill when:

  • User wants to publish content to their Wiki.js instance
  • Converting articles, notes, or analysis to wiki format
  • Creating new wiki pages with proper structure
  • Updating existing wiki pages
  • Need to handle Wiki.js GraphQL API operations

Prerequisites

  • WIKI_KEY environment variable must be set (Wiki.js API key)
  • Wiki.js instance URL must be accessible
  • User must have write permissions to the target wiki

Content Formatting Rules

Remove YAML Frontmatter

CRITICAL: Wiki.js stores title/description in API parameters, NOT in content.

❌ Don't include in content:

---
title: Page Title
description: Page description
---

# Page Title

✅ Correct format:

# Page Title

Content starts here...

Heading Structure

  • Always start with H1 (# Title)
  • Use proper hierarchy (H1 → H2 → H3)
  • Don't skip levels

Links

  • Use markdown format: [text](url)
  • Prefer relative links for internal wiki pages
  • External links should use full URL

API Usage

⚠️ CRITICAL: GraphQL String Handling

The #1 cause of failures is incorrect string escaping.

❌ WRONG - Direct String Interpolation

# DON'T DO THIS - will fail with complex content
query = f'''
mutation {{
  pages {{
    create(content: "{content}") {{  # Content with quotes/newlines will break
      page {{ id }}
    }}
  }}
}}
'''

Why it fails:

  • Markdown contains " (quotes) that terminate the GraphQL string
  • Newlines in content break the query syntax
  • Backslashes in code blocks escape incorrectly
  • JSON serialization double-escapes

✅ CORRECT - Use GraphQL Variables (RECOMMENDED)

import json
import requests

query = '''
mutation CreatePage($content: String!, $title: String!, $path: String!) {
  pages {
    create(
      content: $content
      title: $title
      path: $path
      editor: "markdown"
      isPublished: true
      isPrivate: false
      locale: "zh"
    ) {
      page {
        id
        path
        title
      }
      responseResult {
        succeeded
        errorCode
        message
      }
    }
  }
}
'''

variables = {
    "content": raw_content,  # Pass raw content, no preprocessing
    "title": "Page Title",
    "path": "category/page-name",
    "tags": []  # Required - can be empty list
}

# Let json.dumps handle all escaping automatically
payload = json.dumps({
    "query": query,
    "variables": variables
})

response = requests.post(
    WIKI_URL,
    headers={
        "Content-Type": "application/json",
        "Authorization": f"Bearer {WIKI_KEY}"
    },
    data=payload
)

Why this works:

  • json.dumps() properly escapes all special characters
  • GraphQL Variables separate data from query structure
  • Handles quotes, newlines, backslashes, Unicode automatically

✅ ALTERNATIVE - Use Block String (Triple Quotes)

For simple updates when Variables cause issues:

# Replace any """ in content first
safe_content = content.replace('"""', 'x00TRIPLEx00')

mutation = f'''
mutation {{
  pages {{
    update(
      id: {page_id}
      content: """{safe_content}"""
      description: "Updated description"
      editor: "markdown"
      tags: []
    ) {{
      page {{ id path title }}
      responseResult {{ succeeded errorCode message }}
    }}
  }}
}}
'''

Create Page

mutation CreatePage($content: String!, $title: String!, $path: String!, $description: String!, $tags: [String]!) {
  pages {
    create(
      content: $content
      description: $description
      editor: "markdown"
      isPublished: true
      isPrivate: false
      locale: "zh"
      path: $path
      tags: $tags
      title: $title
    ) {
      page {
        id
        path
        title
      }
      responseResult {
        succeeded
        errorCode
        message
      }
    }
  }
}

Variables:

{
  "content": "# TitlennContent...",
  "title": "Page Title",
  "path": "topic/category/page-name",
  "description": "Page description",
  "tags": ["tag1", "tag2"]
}

Important: tags must be provided even if empty ([]). Some Wiki.js versions require this field.

Type Requirements:

  • $content: String! - Required, raw markdown
  • $title: String! - Required
  • $path: String! - Required, URL path
  • $description: String! - Required (can be empty string)
  • $tags: [String]! - Required array of strings (can be empty [])

Update Page

Two-step process:

  1. Query page ID by path
  2. Update page using ID

Step 1: Query Page ID

query GetPage($path: String!) {
  pages {
    single(path: $path) {
      id
      title
      path
      description
      content
    }
  }
}

Variables:

{"path": "tech/api/rpc"}

Or query all pages to find by path:

query {
  pages {
    list {
      id
      path
      title
    }
  }
}

Step 2: Update Page

mutation UpdatePage($id: Int!, $content: String!, $description: String!) {
  pages {
    update(
      id: $id
      content: $content
      description: $description
      editor: "markdown"
      tags: []
    ) {
      page {
        id
        path
        title
      }
      responseResult {
        succeeded
        errorCode
        message
      }
    }
  }
}

⚠️ CRITICAL for Update:

  • tags is REQUIRED even if empty []
  • description is REQUIRED even if empty string ""
  • Missing either will cause: Cannot read properties of undefined (reading 'map')

Variables:

{
  "id": 25,
  "content": "# Updated Contentnn...",
  "description": "Updated description"
}

GraphQL String Type Reference

String Representation

GraphQL supports two string formats:

1. Single-line Strings (Double Quote)

description: "Single line text"

Escape sequences required:

Character Escape Example
" " "Say "hello""
\ "C:\path"
Newline n "Line1nLine2"
Tab t "Col1tCol2"

2. Block Strings (Triple Quote)

content: """
Multi-line
content here
"""

Notes:

  • Preserves newlines
  • Must escape """ within content
  • Leading whitespace is normalized based on first line

Common Escape Pitfalls

Pitfall 1: Markdown Code Blocks

Markdown contains triple backticks that conflict:

```python
def hello():
    pass

When inserted into GraphQL block string:
```graphql
content: """
```python  # ❌ Conflicts with GraphQL """
def hello()

"""


**Solution:** Use GraphQL Variables (recommended) or escape each `` ` `` as ``.

#### Pitfall 2: JSON Double-Escaping

```python
# ❌ WRONG - manual escape then JSON serialize
content_escaped = content.replace('"', '\"')
payload = json.dumps({"query": f'..."{content_escaped}"...'})
# Results in: " (double escaped)

# ✅ CORRECT - pass raw content to variables
payload = json.dumps({
    "query": "mutation($c: String!) { create(content: $c) }",
    "variables": {"c": raw_content}
})

Pitfall 3: Unicode Characters

GraphQL Strings are UTF-8 encoded. Ensure:

  • Source file is UTF-8
  • HTTP request specifies Content-Type: application/json; charset=utf-8
  • No BOM (Byte Order Mark) at file start

Path Conventions

Suggest paths based on content type:

Content Type Suggested Path
Technical docs tech/{category}/{topic}
Thinking models topic/thinking-models/{name}
Financial concepts financial/{category}/{name}
Personal notes notes/{category}/{name}
Project docs projects/{name}/{doc}

Workflow

For New Pages:

  1. Extract content - Get markdown from user or generate it
  2. Clean formatting - Remove YAML frontmatter if present
  3. Suggest metadata - Propose path, tags, description
  4. Confirm with user - Show proposed wiki location
  5. Create - Execute pages.create mutation with all required fields
  6. Return link - Provide wiki page URL

For Existing Pages:

  1. Query page ID - Use pages.single(path: "...") or pages.list
  2. Get current content (optional) - For comparison
  3. Update - Execute pages.update mutation with id + all required fields
  4. Verify - Check response for success
  5. Return link - Provide wiki page URL

Error Handling

Error Cause Solution
ValidationError: Variable $content... invalid value String escaping issue Use Variables + json.dumps
Field "create" argument "tags" of type "[String]!" is required Missing required tags parameter Always provide tags: [] even if empty
GraphQLError: Variable $tags of type [String] Tags type mismatch Use [String]! in mutation signature
Cannot read properties of undefined (reading 'map') Missing tags or description in update Add tags: [] and description: "..."
Unauthorized Invalid API key Check WIKI_KEY env var
Page already exists Path conflict Use update mutation or different path

Debugging Failed Requests

Always check both errors array and responseResult:

result = response.json()

# Check GraphQL-level errors
if 'errors' in result:
    for err in result['errors']:
        print(f"GraphQL Error: {err.get('message')}")

# Check Wiki.js response result
resp_result = result.get('data', {}).get('pages', {}).get('create', {}).get('responseResult', {})
if not resp_result.get('succeeded'):
    print(f"Wiki.js Error {resp_result.get('errorCode')}: {resp_result.get('message')}")

Example: Create Page (Complete)

import os
import json
import urllib.request

WIKI_URL = os.environ.get("WIKI_URL")  # e.g. https://your-wiki.example.com/graphql
WIKI_KEY = os.environ.get("WIKI_KEY")

def create_wiki_page(content: str, title: str, path: str, 
                     description: str = "", tags: list = None) -> dict:
    """
    Create a Wiki.js page using GraphQL API.
    """
    query = '''
    mutation CreatePage($content: String!, $title: String!, 
                       $path: String!, $description: String!, 
                       $tags: [String]!) {
      pages {
        create(
          content: $content
          title: $title
          path: $path
          description: $description
          tags: $tags
          editor: "markdown"
          isPublished: true
          isPrivate: false
          locale: "zh"
        ) {
          page {
            id
            path
            title
          }
          responseResult {
            succeeded
            errorCode
            message
          }
        }
      }
    }
    '''
    
    variables = {
        "content": content,
        "title": title,
        "path": path,
        "description": description or title,
        "tags": tags if tags is not None else []
    }
    
    payload = json.dumps({
        "query": query,
        "variables": variables
    }).encode('utf-8')
    
    req = urllib.request.Request(
        WIKI_URL,
        data=payload,
        headers={
            "Content-Type": "application/json",
            "Authorization": f"Bearer {WIKI_KEY}"
        },
        method='POST'
    )
    
    with urllib.request.urlopen(req) as resp:
        return json.loads(resp.read().decode())

# Usage
with open('article.md', 'r', encoding='utf-8') as f:
    content = f.read()

result = create_wiki_page(
    content=content,
    title="软件反模式(Anti-Patterns)",
    path="tech/patterns/anti_patterns",
    description="软件工程中常见反模式的识别与规避指南",
    tags=["软件设计", "反模式", "最佳实践"]
)

Example: Update Page (Complete)

import os
import json
import urllib.request

WIKI_URL = os.environ.get("WIKI_URL")  # e.g. https://your-wiki.example.com/graphql
WIKI_KEY = os.environ.get("WIKI_KEY")

def update_wiki_page(page_id: int, content: str, description: str = "") -> dict:
    """
    Update a Wiki.js page using GraphQL API.
    
    ⚠️ IMPORTANT: tags and description are REQUIRED even if empty!
    """
    query = '''
    mutation UpdatePage($id: Int!, $content: String!, $description: String!) {
      pages {
        update(
          id: $id
          content: $content
          description: $description
          editor: "markdown"
          tags: []
        ) {
          page {
            id
            path
            title
          }
          responseResult {
            succeeded
            errorCode
            message
          }
        }
      }
    }
    '''
    
    variables = {
        "id": page_id,
        "content": content,
        "description": description
    }
    
    payload = json.dumps({
        "query": query,
        "variables": variables
    }).encode('utf-8')
    
    req = urllib.request.Request(
        WIKI_URL,
        data=payload,
        headers={
            "Content-Type": "application/json",
            "Authorization": f"Bearer {WIKI_KEY}"
        },
        method='POST'
    )
    
    with urllib.request.urlopen(req) as resp:
        return json.loads(resp.read().decode())

def get_page_id_by_path(path: str) -> int:
    """Find page ID by path."""
    query = json.dumps({
        "query": "{ pages { list { id path title } } }"
    }).encode()
    
    req = urllib.request.Request(
        WIKI_URL,
        data=query,
        headers={
            "Content-Type": "application/json",
            "Authorization": f"Bearer {WIKI_KEY}"
        },
        method='POST'
    )
    
    with urllib.request.urlopen(req) as resp:
        data = json.loads(resp.read().decode())
        pages = data.get('data', {}).get('pages', {}).get('list', [])
        for p in pages:
            if p.get('path') == path:
                return p.get('id')
    return None

# Usage: Update existing page
with open('wiki_rpc_article.md', 'r', encoding='utf-8') as f:
    content = f.read()

page_id = get_page_id_by_path("tech/api/rpc")
if page_id:
    result = update_wiki_page(
        page_id=page_id,
        content=content,
        description="RPC协议全面指南,涵盖架构、框架对比、协议设计、性能优化等"
    )
    print(f"Updated: https://<wiki-url>/tech/api/rpc")

Reference

  • GraphQL Spec - String Type
  • Wiki.js API Documentation: https://docs.requarks.io/dev/api

Remember:

  • Create: Use pages.create with all fields including tags: [] and description
  • Update: Use pages.update with id, content, description, and tags: []
  • Query: Use pages.single(path: "...") to find page ID, or pages.list to list all
  • Always use GraphQL Variables for content to avoid escaping issues
  • Always check responseResult for detailed error messages

推荐文章

更多
PHP时间戳与日期字符串相互转换方法详解

本文介绍PHP中时间数值(Unix时间戳)与日期字符串之间的相互转换方法。通过strtotime和date函数,实现将当前时间、指定日期转换为时间戳,以及将时间戳格式化为可读的日期时间字符串,并提供相关在线计算工具推荐。

2025.11.30 1,034
PHP日期转时间戳时区偏差怎么解决

在 PHP 中将日期字符串转换为时间戳时,若未显式指定时区,默认使用脚本配置的 date.timezone 或系统时区。当服务器时区与业务逻辑预期(如 UTC )不一致时,会产生偏差。解决核心是确保输入字符串携带明确时区信息,或在转换前统一设置时区上下文。

2026.10.24 1,031
PHP跨域配置:怎么安全地允许指定域名而非使用通配符

在 PHP 中安全地允许指定域名跨域,核心是解析请求头中的 Origin ,验证其是否在白名单内,然后动态设置 Access-Control-Allow-Origin 响应头。不要使用通配符 * ,也不要硬编码单一域名。

2025.03.29 1,019
JavaScript中利用replace结合正则实现replaceAll效果

JavaScript原生仅支持replace()进行单次或全局替换,缺乏类似Java的replaceAll()便捷方法。本文总结四种在JS中实现全量替换的方案:使用带g标志的正则、带gm标志的正则、扩展String原型以及split后join。通过对比代码示例,展示各方法的实现细节与适用场景,帮助开发者根据需求选择最优解。

2025.04.29 1,017
OpenAI的Jalapeno芯片未落地,教你分辨300兆瓦算力消息

OpenAI计划在SB Energy租赁的数据中心部署约300兆瓦自研Jalapeno推理芯片,但目前双方仍处于洽谈阶段,交易细节与上线时间表均未公布。本文带你按报道原文核实项目所处阶段,厘清芯片发布、电力功率与实际推理算力的边界,并将融资意向与签约、开工、投运节点分开追踪,避免误将规划容量计入现有算力。

2026.12.02 1,014
PHP实现基础文件上传:HTML表单与$_FILES处理流程

在 HTML 表单中设置 enctype="multipart/form-data" ,并在 PHP 后端通过 $_FILES 数组接收文件,调用 move_uploaded_file() 将临时文件移动到目标目录即可完成上传。

2026.09.07 1,014
Skill 文件
  • SKILL.md
    • Wiki Publisher
    • When to Use
    • Prerequisites
    • Content Formatting Rules
      • Remove YAML Frontmatter
      • Heading Structure
      • Links
    • API Usage
      • ⚠️ CRITICAL: GraphQL String Handling
        • ❌ WRONG - Direct String Interpolation
        • ✅ CORRECT - Use GraphQL Variables (RECOMMENDED)
        • ✅ ALTERNATIVE - Use Block String (Triple Quotes)
      • Create Page
      • Update Page
        • Step 1: Query Page ID
        • Step 2: Update Page
    • GraphQL String Type Reference
      • String Representation
        • 1. Single-line Strings (Double Quote)
        • 2. Block Strings (Triple Quote)
      • Common Escape Pitfalls
        • Pitfall 1: Markdown Code Blocks
        • Pitfall 3: Unicode Characters
    • Path Conventions
    • Workflow
      • For New Pages:
      • For Existing Pages:
    • Error Handling
      • Debugging Failed Requests
    • Example: Create Page (Complete)
    • Example: Update Page (Complete)
    • Reference
  • 项目或源文件

相关 Skill

更多
service-qa-coach service-qa-coach Review support quality for chat, email, phone, social DM, or marketplace service teams. Use when a team needs a QA scorecard, failure-mode analysis, coaching plan, calibration checklist, or service-improvement brief without live ticketing, CRM, or contact-center system access.
高中数学作业批改助手 高中数学作业批改助手 >图片识别 直接读取学生手写作答照片,识别公式、符号、步骤 🧮 自动推导 根据题目自动生成参考答案和评分细则,无需教师预设 📊 逐步给分 每个关键步骤独立评分,体现过程分 📝 结构化报告 输出含识别内容、参考答案、逐步评分、改进建议的完整报告 🗂 批量批改 支持一次性批改多道题,最终汇总得分表
Vibration Analysis Vibration Analysis 分析来自CMS趋势、RMS/峰值、频谱及SCADA报警的风机传动链(主轴、齿轮箱、发电机)振动数据。
Traditional Bone Tool Making Basics Traditional Bone Tool Making Basics Use when you need custom, durable, repairable tools like awls, needles, scrapers, harpoons, or fishing hooks made from local animal bones or antlers and comm...
音频混音工具 音频混音工具 名称:Sound Mixing Tool(标识 sound-mixing-tool) 短简介(≤60字):音乐/音效响度精确对齐 + 融合混音工作流:用 ffmpeg 两段式 loudnorm 把多组素材 LUFS 偏差压到 <0.10,再最小干预融合、导出可进引擎的独立分轨。 标签/关键词:音频混音 响度匹配 LUFS ffmpeg 游戏音频 音效设计 Wwise FMOD 分轨导出 后期处理 触发词:混音 · 响度匹配 · LUFS 对齐 · MIX 版本 · 音乐音效分轨 · 融合 · 不打架 · 不能盖住 适用场景 :游戏音频集成、影视短视频配乐、播客后期