Skip to content
Source
Sign inSign up
TanStack/db

Adding server-generated properties to transaction in Collection.onInsert etc. #456

Send to my agent
OpenOliverGeneser(GitHub profile, opens in a new tab) opened this issue 2 comments

In my onInsert handler, I call a TRPC endpoint which returns the server-generated publicId of the newly created document:

onInsert: async ({ transaction }) => {
  const newDocument = transaction.mutations[0].modified;

  const data = await trpcClient.documents.create.mutate({
    data: newDocument.data,
    multiple: newDocument.data.length > 1,
    templateId: newDocument.templateId,
  });

  // `data.publicId` is available here
};

But when inserting into the collection:

const tx = documentCollection.insert({
  data: documentData,
  multiple: documentData.length > 1,
  templateId: params.templateId,
  publicId: "", // <-- should come from server
  status: "pending",
  createdAt: new Date(),
  updatedAt: new Date(),
  deletedAt: null,
  createdBy: "",
  error: null,
  version: 1,
  key: null,
});

const data = await tx.isPersisted.promise;

// How can I access the `publicId` returned by the server here?

Currently, the transaction doesn’t provide a way to pass back arbitrary data (like publicId) from the TRPC call into the persisted collection record.

Proposed solution:

It would be helpful if the transaction itself exposed a way to attach response metadata from async mutations. For example: A method like transaction.setResponseData({...})

  1. I had the same question especially with object ids generated on the server or db

    Another question I have is the possibility to return the data from the api call directly in the onInsert and that will be committed to the collection, without the need to refetch the entire collection

    onInsert: async ({ transaction }) => {
      const newDocument = transaction.mutations[0].modified;
    
      const data = await trpcClient.documents.create.mutate({
        data: newDocument.data,
        multiple: newDocument.data.length > 1,
        templateId: newDocument.templateId,
      });
    
      return data //goal is to commit the full document with id and disable refetch of the collection 
    };

    Maybe I missed something, that there is a way to modify the transaction after the api call?

  2. It would be helpful if the transaction itself exposed a way to attach response metadata from async mutations. For example: A method like transaction.setResponseData({...})

    @OliverGeneser i think it has a metadata although idk if this matches your usecase (at the third example)

    insert(data: { user: string; text: string; id: number; } | { user: string; text: string; id: number; }[], config?: InsertConfig): Transaction<Record<string, unknown>> | Transaction<{ user: string; text: string; id: number; }>
    
    Inserts one or more items into the collection
    
    *@returns* — A Transaction object representing the insert operation(s)  
    
    *@throws* — {SchemaValidationError} If the data fails schema validation  
    
    *@example*  
    
    // Insert a single todo (requires onInsert handler)
    const tx = collection.insert({ id: "1", text: "Buy milk", completed: false })
    await tx.isPersisted.promise
    
    *@example*  
    
    // Insert multiple todos at once
    const tx = collection.insert([
      { id: "1", text: "Buy milk", completed: false },
      { id: "2", text: "Walk dog", completed: true }
    ])
    await tx.isPersisted.promise
    
    *@example*  
    
    // Insert with metadata
    const tx = collection.insert({ id: "1", text: "Buy groceries" },
      { metadata: { source: "mobile-app" } }
    )
    await tx.isPersisted.promise
    
    *@example*  
    
    // Handle errors
    try {
      const tx = collection.insert({ id: "1", text: "New item" })
      await tx.isPersisted.promise
      console.log('Insert successful')
    } catch (error) {
      console.log('Insert failed:', error)
    }
    - `[config?: InsertConfig]` - Optional configuration including metadata

Sign in to join this conversation.