[]
This tutorial guides you how to configure database adapters for data persistence. A SQLite3 adapter is implemented as a practical example to show configuration steps.
Complete the Real-Time Collaborative Text Editor tutorial
Foundational knowledge of Database Adapter
npm install sqlite3 @mescius/js-collaboration-ot-sqlite
Replace the code from the basic tutorial with the following content:
import express from "express";
import { createServer } from "http";
import { Server } from "@mescius/js-collaboration";
import OT from "@mescius/js-collaboration-ot";
import richText from "rich-text";
import sqlite3 from "sqlite3";
import { SqliteDb } from "@mescius/js-collaboration-ot-sqlite";
// Register the rich-text type
OT.TypesManager.register(richText.type);
const port = 8080;
const app = express();
const httpServer = createServer(app);
const server = new Server({ httpServer });
// Initialize SQLite Database And Database Adapter
const db = new sqlite3.Database("./data.db");
const sqliteDbAdapter = new SqliteDb(db);
// Initialize OT document services
const documentServices = new OT.DocumentServices({ db: sqliteDbAdapter });
server.useFeature(OT.documentFeature(documentServices));
// Serve static files
app.use(express.static('public'));
// Start the server
httpServer.listen(port, () => {
console.log(`Server listening on port ${port}`);
console.log(`http://127.0.0.1:8080/index.html`);
});
Create the file init-database.js
in the root directory.
import sqlite3 from "sqlite3";
const db = new sqlite3.Database("./data.db");
async function initSqliteDataTables(db) {
const run = (sql) => {
return new Promise((resolve, reject) => {
db.run(sql, (e) => (e ? reject(e) : resolve()));
});
};
await run(
`CREATE TABLE IF NOT EXISTS documents (
id TEXT PRIMARY KEY,
type TEXT NOT NULL,
version INTEGER NOT NULL,
snapshot_version INTEGER NOT NULL
)`
);
await run(
`CREATE TABLE IF NOT EXISTS operations (
doc_id TEXT NOT NULL,
version INTEGER NOT NULL,
operation TEXT NOT NULL,
PRIMARY KEY (doc_id, version),
FOREIGN KEY (doc_id) REFERENCES documents (id) ON DELETE CASCADE
)`
);
await run(
`CREATE TABLE IF NOT EXISTS snapshot_fragments (
doc_id TEXT NOT NULL,
fragment_id TEXT NOT NULL,
data TEXT NOT NULL,
PRIMARY KEY (doc_id, fragment_id),
FOREIGN KEY (doc_id) REFERENCES documents (id) ON DELETE CASCADE
)`
);
}
// Call the initialization function
initSqliteDataTables(db);
Execute this file to initialize the database tables:
node init-database.js
Build the Client Code
npm run build
Start the Server
npm run start
Test the Functionality
Enter "123" in the input field.
Restart the server. You can see the same string in the input field.
To learn how to implement a custom database adapter, see: Custom Database Adapter.