npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@wecode-team/cms-supabase-api

v0.5.0

Published

A provider-agnostic CMS API using Hono, backed by PostgreSQL (MySQL-ready interfaces)

Readme

@wecode-team/cms-supabase-api

一个基于 Hono 框架的动态 CMS API 包,支持动态表管理、数据关联、用户认证等功能。

  • postgres(推荐):纯 PostgreSQL(pg 驱动),认证基于 public_auth_0 + bcrypt + JWT
  • supabase(兼容旧版):数据继续走 Supabase SDK/API,但认证不使用 Supabase Auth,改为通过 Supabase API 对 public_auth_0 做 CRUD + bcrypt + JWT;只配置 SUPABASE_URL/KEY 的旧项目可运行
  • mysql:接口已预留,尚未实现

Supabase 托管数据库也可以只当普通 PostgreSQL 使用(配置 DATABASE_URL 即可)。

📖 设计理念

核心思想

本包的核心理念是 "JSON Schema 驱动的动态 CMS":

  1. 模型即配置:通过 JSON Schema 定义数据模型,系统自动创建对应的数据库表
  2. 动态表管理:无需手写 SQL,通过 API 动态创建、修改、删除数据表
  3. 关系支持:支持 belongsTo、hasMany、belongsToMany 三种关联关系
  4. 多租户隔离:通过表名前缀(Session ID)实现数据隔离

架构设计

┌─────────────────────────────────────────────────────────────┐
│                      Hono Application                        │
├─────────────────────────────────────────────────────────────┤
│  Route Helpers                                               │
│  ├── createCmsRoutes()     一键创建所有路由                  │
│  ├── createModelRoute()    模型管理路由                      │
│  ├── createDynamicDataRoute()  动态数据路由                  │
│  ├── createDynamicAuthRoute()  动态认证路由                  │
│  └── createDynamicUserRoute()  用户管理路由                  │
├─────────────────────────────────────────────────────────────┤
│  Handlers (处理器层)                                         │
│  ├── models.ts      模型 CRUD                               │
│  ├── data.ts        数据 CRUD + 关联查询                    │
│  ├── auth.ts        登录/认证                               │
│  └── users.ts       用户 CRUD                               │
├─────────────────────────────────────────────────────────────┤
│  Services (服务层)                                           │
│  ├── PgCmsModelsStore      模型配置 CRUD                    │
│  ├── PgPublicDataStore     统一 JSONB 数据存储              │
│  └── PgAuthProvider        登录/注册/Token/改密             │
├─────────────────────────────────────────────────────────────┤
│  Storage Interfaces (可替换 provider)                        │
│  ├── IPublicDataStore / ICmsModelsStore / IAuthStore ...     │
│  ├── postgres  已实现(pg driver)                          │
│  ├── supabase  已实现(Supabase 数据 API + 数据库认证)      │
│  └── mysql     接口已预留,后续实现                         │
├─────────────────────────────────────────────────────────────┤
│  PostgreSQL / Supabase API                                   │
└─────────────────────────────────────────────────────────────┘

🚀 安装

npm install @wecode-team/cms-supabase-api
# 或
pnpm add @wecode-team/cms-supabase-api
# 或
yarn add @wecode-team/cms-supabase-api

📋 依赖

Peer Dependencies(必须安装)

{
  "hono": "^4.0.0"
}

数据库驱动 pg、密码哈希 bcryptjs、JWT jsonwebtoken 已作为包依赖安装。

🔧 快速开始

第一步:初始化数据库

在目标 PostgreSQL 中执行 pg-setup.sql(Supabase 托管库同样适用):

psql "$DATABASE_URL" -f pg-setup.sql

如果是已有 Supabase 部署,再执行一次迁移脚本(保留原数据库、原账号和原密码):

psql "$DATABASE_URL" -f migrate-from-supabase.sql

迁移脚本会把 auth.users.encrypted_password(bcrypt)和旧 {session_id}_cms_users 用户导入 public_auth_0,并把 _cms_admin_registry 指向新的用户 id;旧用户继续用原邮箱 + 原密码登录。

第二步:创建 Hono 应用

import { Hono } from 'hono'
import { cors } from 'hono/cors'
import {
  initializeProvider,
  initializeOssUpload,
  createCmsRoutes,
  createOssUploadRoute,
} from '@wecode-team/cms-supabase-api'

const app = new Hono()

// CORS 配置
app.use('/*', cors())

// 注入 PostgreSQL 数据层 + 认证层(读取 DATA_PROVIDER / DATABASE_URL / JWT_SECRET)
initializeProvider()

// 初始化 OSS 上传
initializeOssUpload({
  baseURL: process.env.OSS_BASE_URL || 'https://we0.ai',
  prefix: 'cms-assets',
  returnMode: 'both',
  skipValidation: false,
})

// 一键创建所有 CMS 路由
createCmsRoutes(app)

// 创建上传路由
createOssUploadRoute(app)

export default app

第三步:定义数据模型

通过 API 创建模型:

// POST /models
{
  "name": "文章模型",
  "table_name": "posts",
  "json_schema": {
    "fields": [
      {
        "name": "title",
        "type": "string",
        "comment": "文章标题",
        "required": true,
        "maxLength": 255
      },
      {
        "name": "content",
        "type": "text",
        "comment": "文章内容",
        "required": true
      },
      {
        "name": "author",
        "type": "relation",
        "comment": "作者",
        "required": true,
        "relation": {
          "type": "belongsTo",
          "target": "users",
          "foreignKey": "author_id",
          "displayField": "name"
        }
      },
      {
        "name": "status",
        "type": "string",
        "comment": "状态",
        "defaultValue": "draft"
      }
    ]
  }
}

📚 API 路由

CMS 用户管理

管理员认证后,可通过带租户前缀的用户表名管理 CMS 用户。用户表名约定为 {session_id}_cms_users(无租户场景使用 cms_users),并通过 X-Session-Id 请求头再次校验租户边界:

GET    /users/{session_id}_cms_users?page=1&limit=20&search=alice
POST   /users/{session_id}_cms_users
PUT    /users/{session_id}_cms_users/{id}
DELETE /users/{session_id}_cms_users/{id}

创建和更新请求使用 password 字段,服务端负责 bcrypt 哈希;password_hash 不接受来自客户端的写入,也不会出现在用户列表或详情响应中。用户数据统一存放在 public_auth_0(通过 IAuthStore / PgAuthStore),与登录使用的 PgAuthProvider 共用同一份存储。

模型管理

| 方法 | 路径 | 描述 | |------|------|------| | GET | /models | 获取所有模型 | | POST | /models | 创建新模型(同时创建数据表) | | PUT | /models | 更新模型 | | DELETE | /models?id={id} | 删除模型(同时删除数据表) |

数据管理

| 方法 | 路径 | 描述 | |------|------|------| | GET | /data/:tableName | 获取表数据(支持分页、搜索) | | GET | /data/:tableName/with-relations | 获取带关联数据的表数据 | | POST | /data/:tableName | 创建新数据 | | PUT | /data/:tableName | 更新数据 | | DELETE | /data/:tableName?id={id} | 删除数据 |

关联数据

| 方法 | 路径 | 描述 | |------|------|------| | GET | /relation/:tableName/options | 获取关联表选项(用于下拉选择) |

资源上传

| 方法 | 路径 | 描述 | |------|------|------| | POST | /upload | 上传单个文件到 OSS 服务,默认需要管理员登录 |

认证

| 方法 | 路径 | 描述 | |------|------|------| | GET | /auth/signup/status/:tableName | 查询当前 session 是否允许首次注册管理员 | | POST | /auth/signup/:tableName | 首次注册管理员(写入 public_auth_0 + _cms_admin_registry) | | POST | /auth/:tableName/login | 用户登录 | | GET | /auth/:tableName/current | 获取当前用户信息 | | POST | /auth/:tableName/verify | 验证 Token | | GET | /auth/user/:tableName | 获取当前用户信息(兼容历史路径) | | POST | /auth/verify/:tableName | 验证 Token(兼容历史路径) |

提示:后台管理接口(/models、/data/* 等)建议携带请求头 X-Session-Id,用于按 session_id 维度校验管理员权限。

☁️ OSS 上传

宿主项目只需要两步:

  1. 调用 initializeOssUpload(config)
  2. 调用 createOssUploadRoute(app)

最小示例:

initializeOssUpload({
  baseURL: process.env.OSS_BASE_URL || "https://we0.ai",
  prefix: "cms-assets",
  maxSize: 2 * 1024 * 1024,
  returnMode: "both",
  timeout: 30_000,
  retry: { retries: 2, delay: 1000 },
  skipValidation: false,
})

createOssUploadRoute(app)

兼容说明:

  • 推荐使用 baseURL 对接 @wecode-team/oss 服务
  • bucket、endpoint、accessKeyId、accessKeySecret、publicBaseUrl 仍可保留在配置类型中,但在 SDK 模式下不再必填

上传请求要求:

  • POST /upload
  • multipart/form-data
  • 文件字段名固定为 file
  • 可选文本字段:directory、fieldName、tableName
  • 默认要求 Authorization 和 X-Session-Id,并通过现有 admin 鉴权
  • X-Session-Id 为必填,因为 @wecode-team/oss 以 sessionId 作为文件隔离维度

上传成功返回:

{
  "success": true,
  "url": "https://we0.ai/api/oss/files/site_config/logo.png",
  "signedUrl": "https://we0.ai/api/oss/files/site_config/logo.png",
  "objectKey": "cms-assets/logos/20260316120000-abcdef.png",
  "fieldName": "logo",
  "tableName": "site_config"
}

returnMode 说明:

  • public-url: 只返回 url
  • signed-url: 当前 SDK 适配层会把 url 和 signedUrl 都映射为 SDK 返回地址
  • both: 同时返回 url 和 signedUrl

如果 bucket 是私有读,推荐使用 signed-url 或 both。

🏗️ 字段类型

| 类型 | PostgreSQL 类型 | 说明 | |------|-----------------|------| | string | text | 短文本 | | text | text | 长文本 | | integer | int4 | 整数 | | float | float8 | 浮点数 | | boolean | bool | 布尔值 | | date | date | 日期 | | datetime | timestamptz | 日期时间 | | json | jsonb | JSON 对象 | | email | text | 邮箱(前端验证) | | relation | uuid/int4 | 关联字段(外键) |

🔗 关系配置

belongsTo(多对一)

{
  "name": "author",
  "type": "relation",
  "relation": {
    "type": "belongsTo",
    "target": "users",           // 关联的目标表
    "foreignKey": "author_id",   // 当前表的外键字段
    "displayField": "name"       // 下拉显示的字段
  }
}

hasMany(一对多)

{
  "name": "posts",
  "type": "relation",
  "relation": {
    "type": "hasMany",
    "target": "posts",
    "foreignKey": "author_id"    // 目标表的外键字段
  }
}

🔐 多租户支持(Session ID)

通过表名前缀实现数据隔离:

// 前端设置 Session ID
setSessionId("tenant123")

// API 调用时自动添加前缀
// GET /data/posts → 实际查询 tenant123_posts 表

🛠️ 高级用法

自定义路由

import { Hono } from 'hono'
import { 
  createModelRoute,
  createDynamicDataRoute,
  createAuthRoute 
} from '@wecode-team/cms-supabase-api'

const app = new Hono()

// 只创建模型路由
createModelRoute(app)

// 只创建数据路由
createDynamicDataRoute(app)

// 创建固定表名的认证路由
createAuthRoute(app, 'cms_users')

使用认证中间件

import { requireAuth, getModels } from '@wecode-team/cms-supabase-api'

// 保护路由
app.get('/protected/models', requireAuth(getModels))

直接使用存储层

import {
  getCmsModelsStore,
  getPublicDataStore,
} from '@wecode-team/cms-supabase-api'

const modelStore = getCmsModelsStore()
const dataStore = getPublicDataStore()

// 创建模型(JSON Schema 驱动)
await modelStore.create({
  name: 'Article',
  tableName: 'demo_articles',
  jsonSchema: {
    fields: [{ name: 'title', type: 'string', required: true }],
  },
})

// 插入数据(统一存入 public_data_0)
await dataStore.insertData('demo', 'demo_articles', { title: 'Hello' })

🔧 环境变量

| 变量 | 说明 | 默认值 | |------|------|--------| | DATA_PROVIDER | supabase / postgres / mysql(pg 等价于 postgres) | 自动判断 | | DATABASE_URL | PostgreSQL 连接串(provider=postgres) | - | | SUPABASE_URL | Supabase 项目 URL(provider=supabase) | - | | SUPABASE_ANON_KEY | Supabase anon key(provider=supabase) | - | | SUPABASE_SERVICE_ROLE_KEY | Supabase service role key(服务端优先使用) | - | | JWT_SECRET | 自建 PG 认证的 JWT 签名密钥;Supabase 模式下可沿用旧值 | 'your-secret-key-change-in-production' | | UNIFIED_TABLE_NAME | 统一业务数据表名 | public_data_0 |

不设置 DATA_PROVIDER 时:

  • 只有 SUPABASE_*、没有 DATABASE_URL → supabase(兼容旧项目)
  • 其他情况 → postgres

服务端启动时读取 .env / .env.local(包目录或当前工作目录),通过 initializeProvider() 注入数据层和身份认证层。

  • provider=postgres:登录/注册/Token 校验/改密走 PgAuthProvider(public_auth_0 + bcrypt + JWT)
  • provider=supabase:数据层沿用 Supabase SDK/API;认证走 SupabaseAuthProvider(对 public_auth_0 做 CRUD + bcrypt + JWT),不调用 Supabase Auth

旧代码继续使用 initializeSupabase({ url, key }) 也可以,内部会切换到 Supabase provider。

🐛 常见问题

1. 外键约束错误

如果遇到 violates foreign key constraint 错误,是因为数据库中的外键约束引用了错误的表。解决方法:

-- 删除错误的外键约束
ALTER TABLE "your_table" DROP CONSTRAINT IF EXISTS "constraint_name";

2. CHECK 约束错误

如果遇到 violates check constraint 错误:

-- 删除 CHECK 约束
ALTER TABLE "your_table" DROP CONSTRAINT IF EXISTS "table_status_check";

3. 表不存在错误

如果遇到 relation ... does not exist,需要先初始化数据库:

psql "$DATABASE_URL" -f pg-setup.sql

📄 许可证

MIT