Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create parent and child in a single batch #1844

Open
lud opened this issue Oct 18, 2024 · 0 comments
Open

Create parent and child in a single batch #1844

lud opened this issue Oct 18, 2024 · 0 comments

Comments

@lud
Copy link

lud commented Oct 18, 2024

Hello,

I would like to create initial data from a template. But I want it to be transactional, I don't want to have only the parent then a failure, or only a part of the children.

So far I have done this and it seems to work:

function createFromTemplate(database: Database, index: number) {
  const template: Template = TEMPLATES[index]
  
  return database.write(async () => {
    const posts = await database.get('posts')
    const comments = await database.get('comments')
    
    const postOp = posts.prepareCreate((post) => {
      post.name = template.name
      post.steps = template.steps
    })
    
    const commentOps = template.comments.map(raw => comments.prepareCreate((comment) => {
      comment.name = raw.name
      comment.step = raw.step
      comment.post.set(postOp._raw)
    }))

    await database.batch([postOp, ...commentOps])
  })
}

But I am not sure of the correctness. Will that be transactional? Notably, usage of _raw seems off.

Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant