0

Currently i am dealing with the following situation:

I have a ShareDB backend up and running in order to realize real time collaboration (text writing).

Every time a user connects i would like to check if the document the user intends to work on exists in the database. If it DOES NOT exist, create it first. If it DOES exist, proceed normally, this should be done in the "connect" middleware:

var backend = new ShareDB();

backend.use('connect', function(context, next) {
  console.log('connect')

  var connection = backend.connect();
  doc = connection.get('collection_name', 'document_id');
  doc.fetch(function(err) {
    if (err) throw err;
    if (doc.type === null) {
      doc.create({content: ''});
      return;
    }
  });

  next()
})

But it triggers an infinite loop, because i trigger an connect action inside the connect middleware.

So i have no idea how i to access the database in the middleware... any idea?

Thanks!

Creative crypter
  • 1,348
  • 6
  • 30
  • 67
  • Your `doc.fetch` callback only handles scenarios if there is an error or no document exists. See `callback` here: https://github.com/share/sharedb/blob/master/examples/textarea/server.js#L11-L22 – GenericUser Jan 16 '22 at 17:52
  • Additionally, you may not want to call `next()` at the end as you currently are. This will be called regardless of the outcome of fetch. Consider referencing `next` in your fetch when the fetch has settled to an error or success. – GenericUser Jan 16 '22 at 17:57
  • Hey @GenericUser , the example you referenced handles the document creation at server start. What i want to do is: Run createDoc() every time the user connects to sharedb (in the middleware), any ideas? – Creative crypter Jan 16 '22 at 22:35

0 Answers0