Created
July 8, 2023 10:22
-
-
Save gauravpan/2d2cf5b87a5a33ebffa898579c45025c to your computer and use it in GitHub Desktop.
Mongodb database extension for hocuspocus server
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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