@foretag/tanstack-db-surrealdb
v0.1.18
Published
Add Offline / Local First Caching & Syncing to your SurrealDB app with TanstackDB and Loro (CRDTs)
Maintainers
Readme
TanstackDB SurrealDB Collections
Add Offline / Local First Caching & Syncing to your SurrealDB app with TanstackDB and Loro (CRDTs). For SurrealDB v3-alpha.16 and SurrealDB JS SDK v2 (and above).
- Local / Offline first applications with TanstackDB and Loro
- High performance with Low resource consumption
- Works with Web, Desktop or Native (WASM based)
- Support for React, Svelte, Vue and any Framework!
Installation
NPM
# NPM
npm install @foretag/tanstack-db-surrealdb
# Bun
bun install @foretag/tanstack-db-surrealdbJSR
# NPM
npx jsr add @foretag/tanstack-db-surrealdb
# Bun
bunx jsr add @foretag/tanstack-db-surrealdbUsage
// db.ts
import { Surreal } from 'surrealdb';
export const db = new Surreal();
await db.connect('ws://localhost:8000/rpc');
await db.use({ ns: 'ns', db: 'db' });
// collections/products.ts
import { expr, eq } from 'surrealdb';
import { db } from '../db';
import { createCollection } from '@tanstack/db';
import { surrealCollectionOptions } from '@foretag/tanstack-db-surrealdb';
// Collection Type, could also be generated
type Product = {
id: string;
name: string;
price: number;
};
export const products = createCollection(
surrealCollection<Product>({
db,
useLoro: true, // Optional if you need CRDTs
table: {
name: 'products',
where: expr(eq('store', '123')),
fields: ['name', 'price'] // Optional or defaults to *
},
});
)Vite / Next.JS
Vite
bun install vite-plugin-wasm vite-plugin-top-level-await -Dvite.config.ts
// Plugins
import wasm from 'vite-plugin-wasm';
import topLevelAwait from 'vite-plugin-top-level-await';
export default defineConfig({
plugins: [...otherConfigures, wasm(), topLevelAwait()],
});NextJS
next.config.js
module.exports = {
webpack: function (config) {
config.experiments = {
layers: true,
asyncWebAssembly: true,
};
return config;
},
};CRDTs
If you need to use CRDTs for your application consider adding the following fields to the specific tables and set useLoro: true for the respective table. Please note these fields are opinionated, therefore fixed and required:
DEFINE FIELD OVERWRITE sync_deleted ON <table>
TYPE bool
DEFAULT false
COMMENT 'Tombstone for CRDTs';
DEFINE FIELD OVERWRITE updated_at ON <table>
TYPE datetime
VALUE time::now();While using SurrealDB as a Web Database, please remember to allow
SELECT&UPDATEpermissions for thesync_deletedandupdated_atfields for the respective access.
