Skip to content

Instantly share code, notes, and snippets.

@gauravpan
Created July 8, 2023 10:22
Show Gist options
  • Select an option

  • Save gauravpan/2d2cf5b87a5a33ebffa898579c45025c to your computer and use it in GitHub Desktop.

Select an option

Save gauravpan/2d2cf5b87a5a33ebffa898579c45025c to your computer and use it in GitHub Desktop.
Mongodb database extension for hocuspocus server
import { Database, DatabaseConfiguration } from '@hocuspocus/extension-database'
import { Binary, Db, MongoClient } from 'mongodb';
const url = 'mongodb://localhost:27017';
const database = 'hocuspocus';
export interface MongoConfiguration extends DatabaseConfiguration {
database: string,
url: string,
}
export class MongoDB extends Database {
client?: MongoClient
db?: Db
configuration: MongoConfiguration = {
database: database,
url: url,
fetch: async ({ documentName }) => {
const doc = await this.db?.collection('documents').findOne({ documentName: documentName });
if (doc) {
return new Uint8Array(doc.data.buffer);
}
return null;
},
store: async ({ documentName, state, }) => {
return this.db?.collection('documents').findOneAndUpdate({ documentName }, { $set: { documentName, data: new Binary(state), } }, { upsert: true });
},
}
constructor(configuration?: Partial<MongoConfiguration>) {
super({})
this.configuration = {
...this.configuration,
...configuration,
}
}
async onConfigure() {
this.client = new MongoClient(this.configuration.url)
this.db = this.client.db(this.configuration.database);
await this.client.connect()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment