smart-crud-client
v0.1.5
Published
一个轻量级的前端数据库 CRUD 操作解决方案,无需编写后端代码即可连接数据库
Maintainers
Readme
Smart CRUD Client
一个轻量级的前端数据库 CRUD 操作解决方案,无需编写后端代码即可连接数据库。
功能特性
- 💻 前端框架支持:可用于 Vue 和 React 项目
- ⚙️ 数据库兼容:支持 MySQL、SQLite、PostgreSQL
- 📁 多表自动路由:自动生成多表的 CRUD 接口(RESTful)
- 🔧 前端配置连接信息:前端提供配置(数据库类型、连接信息、表名)
- 📦 构建后可部署:打包后仍然可以访问数据库,无需单独启动后端
- 🚀 开箱即用:引入包 + 写配置 + 调用接口 = 拿到数据库数据
安装
npm install smart-crud-clientsmart-crud-client/ ├── plugin/ # 构建 & dev 插件 │ └── vitePlugin.js # 注册插件:dev 启动服务 + 自动注入接口 ├── runtime/ │ ├── server.js # 启动 express 服务并连接数据库 │ ├── routerFactory.js # 动态创建 CRUD 接口 │ ├── db.js # 使用 knex 封装连接逻辑 ├── client/ │ └── useCRUD.js # 提供 hooks/工具函数给前端调用 ├── smart-crud.config.schema.json # 校验配置结构 ├── index.js # 导出 vite 插件 & client 工具
使用方法
配置文件 (smart-crud.config.js)
module.exports = {
dbType: 'mysql', // 'mysql', 'sqlite', 'pg'
connection: {
host: 'localhost',
user: 'root',
password: 'password',
database: 'mydb',
},
tables: ['users', 'products', 'orders'], // 需要生成CRUD接口的表
}在 Vite 项目中使用
// vite.config.js
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue' // 或 react
import { smartCRUDPlugin } from 'smart-crud-client'
import crudConfig from './smart-crud.config.js'
export default defineConfig({
plugins: [vue(), smartCRUDPlugin(crudConfig)],
})在前端组件中使用
// Vue 组件
import { useCRUD } from 'smart-crud-client'
export default {
setup() {
const { users } = useCRUD()
// 获取所有用户
const fetchUsers = async () => {
const data = await users.getAll()
console.log(data)
}
// 创建用户
const createUser = async () => {
await users.create({ name: 'John', email: '[email protected]' })
}
return { fetchUsers, createUser }
},
}数据库配置示例
MySQL
{
dbType: 'mysql',
connection: {
host: 'localhost',
port: 3306,
user: 'root',
password: 'password',
database: 'mydb'
},
tables: ['users', 'products']
}PostgreSQL
{
dbType: 'pg',
connection: {
host: 'localhost',
port: 5432,
user: 'postgres',
password: 'password',
database: 'mydb'
},
tables: ['users', 'products']
}SQLite
{
dbType: 'sqlite',
connection: {
filename: './mydb.sqlite'
},
tables: ['users', 'products']
}API 参考
useCRUD()
返回一个对象,包含每个表的 CRUD 操作方法。
每个表对象包含以下方法:
- getAll(params) : 获取所有记录,支持过滤、排序和分页
- getById(id) : 获取单个记录
- create(data) : 创建新记录
- update(id, data) : 更新记录
- delete(id) : 删除记录
许可证
MIT
