在当今快速发展的技术领域,实时数据库已成为构建现代应用程序不可或缺的工具。PocketBase,作为一款开源的实时数据库解决方案,以其类似于Firebase的功能和自托管的能力,为开发者提供了强大的数据管理平台。它不仅提供了实时数据同步和强大的查询功能,还允许用户在自己的服务器上部署和运行数据库,从而确保了数据的安全性和隐私性。
Pocketbase 的应用情景:
- 实时应用程序:Pocketbase 适用于需要实时数据同步的应用,如在线聊天、实时通知、多人协作工具等。
- 快速原型开发:由于其一体化后端解决方案的特点,Pocketbase 非常适合快速构建和迭代原型。
- 小型到中型项目:Pocketbase 适合资源有限的小型到中型项目,可以减少开发和运维的复杂性。
- IoT 应用:Pocketbase 可以用于物联网应用,处理实时数据并支持设备间的快速通信。
- 移动应用后端:Pocketbase 提供了易于集成的客户端 SDK,非常适合作为移动应用的后端服务。
自带后台管理,以及建表的api

Web API 参考 - API 实时
实时 API 是通过服务器发送的事件 (SSE) 实现的。通常,它由 2 个操作组成:
- 建立 SSE 连接
- 提交客户端订阅
SDK方法无缝处理所有这些操作:subscribe和``unsubscribe
import PocketBase from 'pocketbase';
const pb = new PocketBase('http://127.0.0.1:8090');
...
// (Optionally) authenticate
await pb.collection('users').authWithPassword('test@example.com', '1234567890');
// Subscribe to changes in any record in the collection
pb.collection('example').subscribe('*', function (e) {
console.log(e.action);
console.log(e.record);
}, { /* other options like expand, custom headers, etc. */ });
// Subscribe to changes only in the specified record
pb.collection('example').subscribe('RECORD_ID', function (e) {
console.log(e.action);
console.log(e.record);
}, { /* other options like expand, custom headers, etc. */ });
// Unsubscribe
pb.collection('example').unsubscribe('RECORD_ID'); // remove all 'RECORD_ID' subscriptions
pb.collection('example').unsubscribe('*'); // remove all '*' topic subscriptions
pb.collection('example').unsubscribe(); // remove all subscriptions in the collection
1,导入 PocketBase 库:
import PocketBase from 'pocketbase';
这行代码导入了 PocketBase 模块,使得我们可以在代码中使用它提供的功能。
2,创建 PocketBase 实例:
const pb = new PocketBase('http://127.0.0.1:8090');
这里创建了一个 PocketBase 的实例,连接到本地的 PocketBase 服务器,地址是 http://127.0.0.1:8090。
3,(可选)使用用户名和密码进行身份验证:
await pb.collection('users').authWithPassword('test@example.com', '1234567890');
这行代码尝试使用提供的电子邮件和密码对 'users' 集合进行身份验证。authWithPassword 是一个异步函数,需要使用 await 关键字等待其完成。
4,订阅集合中任何记录的变化:
pb.collection('example').subscribe('*', function (e) {
console.log(e.action);
console.log(e.record);
}, { /* other options like expand, custom headers, etc. */ });
使用 subscribe 方法订阅 'example' 集合中的所有记录。* 表示所有记录,传递给函数的 e 对象包含了事件的 action(比如 'created', 'updated', 'deleted')和改变的 record。
5,仅订阅特定记录的变化:
pb.collection('example').subscribe('RECORD_ID', function (e) {
console.log(e.action);
console.log(e.record);
}, { /* other options like expand, custom headers, etc. */ });
这行代码订阅 'example' 集合中特定 RECORD_ID 的记录变化。只有当这个特定记录发生变化时,回调函数才会被触发。
6,取消订阅:
pb.collection('example').unsubscribe('RECORD_ID'); // 移除特定 'RECORD_ID' 的所有订阅
pb.collection('example').unsubscribe('*'); // 移除所有 '*' 主题的订阅
pb.collection('example').unsubscribe(); // 移除集合中的所有订阅
unsubscribe
方法用来取消订阅。第一个参数是记录 ID 或者 '*'
来指定要取消的订阅类型。如果没有提供参数,则取消集合中所有的订阅。
请注意,上述代码只是一个示例,实际使用时需要根据实际的数据库地址、集合名称和业务逻辑进行相应的调整。
缺点:只能用于Golang和javascript编程环境。
优势:1, 不需要另建websocket。2, 对于表更新能产生回调事件,这是mysql办不到的