flamelink / flamelink-js-sdk

🦊 Official Flamelink JavaScript SDK for both the Firebase Realtime database and Cloud Firestore
https://flamelink.github.io/flamelink-js-sdk
MIT License
43 stars 5 forks source link

Question: updating arrays from SDK #113

Closed alokjkumar closed 4 years ago

alokjkumar commented 4 years ago

I've had a look through the documentation and can't figure this one out - sorry if I'm being dim.

The model I'm going for is a pretty standard one to many, there's one post and each post can have many comments. The posts are submitted in the flamelink GUI and the comments are submitted by an angular app but the app admin needs to be able to view the comments from the flamelink GUI.

What's the best way to do this in flamelink? My best guess at the moment is to have a "comment" schema which has a relational select field and then a "post" schema with a relational tree select. However, I'm not sure how to update the tree select from the SDK - does the update function support arrays? Even better would be if flamelink supported two way binding between these two however I imagine this might be a few releases away.

Thanks for the help

jperasmus commented 4 years ago

Hi there, thanks for the question.

The way I would tackle this is to create 2 collection schemas like you mentioned: Comments and Posts. Within the Posts schema, I would have a multi Select (Relational) field that links to the Comments schema. Each post can then be linked to multiple comments.

In your app, when you receive a comment you can add it to the Comments collection and store the auto-generated entryID. Then after that, you can update the specific Posts entry by adding a Firestore document reference item to the select relational field.

const post = // you probably have the current post object on the page

// 1. Add new comment
const newComment = await app.content.add({
  schemaKey: 'comments',
  data: { comment: 'Some comment', ...optionalOtherFields }
})

// 2. Prepare new post comments (assuming select relational field is called "comments")
const newCommentRef = firestoreService.collection('fl_content').doc(newComment.id)
const newPostComments = post.comments.concat(newCommentRef)

// 3. Update existing post entry with new comment
await app.content.update({
  schemaKey: 'posts',
  entryId: post.id,
  data: { comments: newPostComments }
})

I haven't tested this, but something like this should work.

alokjkumar commented 4 years ago

This makes sense, I think I agree this is the best way to do it!

Thanks for your help