Full-Stack Development
数据与 CRUD
用 TOML 定义数据模型,自动生成 REST API,构建前端数据层。
流程
TOML 定义 → 自动建表 → 自动 CRUD API → 前端数据层你只需定义 Schema,其余全部自动完成。
第 1 步 — 定义内容类型
在项目中创建 TOML 文件:
name = "Article"
table = "articles"
plural = "articles"
[fields.title]
type = "text"
required = true
index = true
[fields.slug]
type = "text"
required = true
unique = true
[fields.body]
type = "rich_text"
[fields.excerpt]
type = "text"
max_length = 500
[fields.cover_image]
type = "media"
accept = "image/*"
[fields.category]
type = "relation"
related_type = "categories"
relation = "many_to_one"
[fields.tags]
type = "relation"
related_type = "tags"
relation = "many_to_many"
[fields.status]
type = "enum"
options = ["draft", "published", "archived"]
default = "draft"
[fields.published_at]
type = "timestamp"重启服务,数据库表和 API 自动创建。
第 2 步 — 使用自动生成的 API
| 方法 | 端点 | 描述 |
|---|---|---|
GET | /api/v1/admin/cms/articles | 列表(分页、筛选、搜索) |
POST | /api/v1/admin/cms/articles | 创建 |
GET | /api/v1/admin/cms/articles/:id | 按 ID 获取 |
PUT | /api/v1/admin/cms/articles/:id | 更新 |
DELETE | /api/v1/admin/cms/articles/:id | 删除 |
查询示例
# 分页列表
GET /api/v1/admin/cms/articles?page=1&limit=10
# 按状态筛选
GET /api/v1/admin/cms/articles?status=published
# 搜索
GET /api/v1/admin/cms/articles?search=入门指南
# 按日期倒序
GET /api/v1/admin/cms/articles?sort=created_at&order=desc第 3 步 — 前端数据层
import { client } from "@/lib/client";
// 列表
const { data } = await client.contentTypes.list("articles", {
page: 1,
limit: 10,
status: "published",
sort: "created_at",
order: "desc",
});
// 创建
const article = await client.contentTypes.create("articles", {
title: "My Article",
slug: "my-article",
body: "<p>Content here</p>",
status: "draft",
});
// 更新
await client.contentTypes.update("articles", article.id, {
status: "published",
});
// 删除
await client.contentTypes.delete("articles", article.id);可用字段类型
| 类型 | 描述 | 用途示例 |
|---|---|---|
text | 短文本(最多 255 字符) | 标题、名称 |
rich_text | 长 HTML 内容 | 正文、描述 |
number | 整数或浮点数 | 价格、数量 |
boolean | 真/假 | 是否发布、是否启用 |
enum | 预定义选项 | 状态、角色 |
timestamp | 日期/时间 | 创建时间、定时发布 |
media | 文件上传 | 封面图、附件 |
relation | 关联其他类型 | 作者、分类 |
json | 任意 JSON 数据 | 元数据、配置 |
关联关系
# 多对一:每篇文章属于一个分类
[fields.category]
type = "relation"
related_type = "categories"
relation = "many_to_one"
# 多对多:文章可以有多个标签
[fields.tags]
type = "relation"
related_type = "tags"
relation = "many_to_many"
# 一对一:一个用户有一个档案
[fields.profile]
type = "relation"
related_type = "profiles"
relation = "one_to_one"下一步
准备好构建真实项目了吗?跟着博客实战开始。
