首页
/ RxDB-Supabase:项目介绍与使用指南

RxDB-Supabase:项目介绍与使用指南

2025-04-19 02:17:59作者:宣海椒Queenly

1. 项目介绍

RxDB 是一个客户端的、离线优先的数据库,支持多种存储层,包括 IndexedDB。Supabase 是一个开源的 Firebase 替代品,它使用 Postgres 数据库并具有行级安全特性。RxDB-supabase 是一个开源项目,它利用 RxDB 的复制逻辑来实现客户端的 RxDB 数据库与远程 Supabase 表的双向同步,同时允许用户定义自定义的冲突解决策略。

2. 项目快速启动

首先,确保你已经安装了 Node.js 环境。以下步骤将帮助你快速启动并运行 RxDB-supabase。

安装

npm install rxdb-supabase rxdb @supabase/supabase-js --save

创建 RxDB 数据库

如果你的 RxDB 是新用户,请阅读 Quickstart guide 获取更多详细信息。

import { createRxDatabase } from 'rxdb';
import { getRxStorageDexie } from 'rxdb/plugins/storage-dexie';

// 创建你的数据库
const myDatabase = await createRxDatabase({
  name: 'humans',
  storage: getRxStorageDexie()
});

创建集合

根据你的 Supabase 表结构创建一个集合。

const mySchema = {
  title: 'human schema',
  version: 0,
  primaryKey: 'id',
  type: 'object',
  properties: {
    id: {
      type: 'string',
      maxLength: 100
    },
    name: {
      type: 'string'
    },
    age: {
      description: 'age in years',
      type: 'integer'
    }
  },
  required: ['id', 'name', 'age'],
  indexes: ['age']
};

const myCollections = await db.addCollections({
  humans: {
    schema: mySchema
    // conflictHandler: ... 可以在这里自定义冲突处理策略
  }
});

使用数据库

const myCollection = myCollections.humans;

// 查询
myCollection.find({}).$.subscribe(documents => {
  console.log(`query has found ${documents.length} documents`);
});

// 插入
const doc = await myCollection.insert({ id: '1', name: 'Alice' });

// 更新
await doc.patch({ age: 21 });

// 删除
await doc.remove();

3. 应用案例和最佳实践

创建 Supabase 表

为了使复制功能正常工作,你的表需要有一个 _modified 时间戳字段和一个 _deleted 字段。

CREATE TABLE public.humans (
  id text NOT NULL,
  name text NOT NULL,
  age smallint,
  _deleted boolean DEFAULT false NOT NULL,
  _modified timestamp with time zone DEFAULT now() NOT NULL
);

ALTER TABLE ONLY public.humans ADD CONSTRAINT humans_pkey PRIMARY KEY (id);

CREATE TRIGGER update_modified_datetime
BEFORE UPDATE ON public.humans
FOR EACH ROW EXECUTE FUNCTION extensions.moddatetime('_modified');

启动复制

确保你已经初始化了 SupabaseClient,并且如果使用了行级安全,客户端已经通过认证。

const replication = new SupabaseReplication({
  supabaseClient: supabaseClient,
  collection: myCollection,
  // ID 用于复制,以便在应用重新加载时能够恢复复制
  // 如果使用了行级安全,你可能还需要附加用户 ID
});

4. 典型生态项目

在 RxDB-supabase 生态中,你可以找到许多补充项目和工具,这些项目可以帮助你更好地集成和扩展 RxDB 和 Supabase 的功能。例如,你可能需要查看用于不同编程语言的客户端库,或者是用于特定用途的中间件和插件。

请参考官方文档和社区资源,以获取更多关于如何使用这些生态项目的信息。

登录后查看全文
热门项目推荐