@@ -18,6 +18,7 @@ import {
1818 OptionalClass ,
1919 UnknownClass ,
2020 Server ,
21+ core ,
2122} from './index.js' ;
2223import { authenticate , fetchWebSocket , startWebsocket } from './websockets.js' ;
2324
@@ -89,6 +90,10 @@ export class Store {
8990 private serverUrl : string ;
9091 /** All the resources of the store */
9192 private _resources : Map < string , Resource > ;
93+
94+ /** List of resources that have parents that are not saved to the server, when a parent is saved it should also save its children */
95+ private batchedResources : Map < string , Set < string > > = new Map ( ) ;
96+
9297 /** Current Agent, used for signing commits. Is required for posting things. */
9398 private agent ?: Agent ;
9499 /** Mapped from origin to websocket */
@@ -478,7 +483,9 @@ export class Store {
478483 }
479484
480485 // We clone for react, because otherwise it won't rerender
481- Promise . allSettled ( callbacks . map ( async cb => cb ( resource . clone ( ) ) ) ) ;
486+ const cloned = resource . clone ( ) ;
487+ this . _resources . set ( subject , cloned ) ;
488+ Promise . allSettled ( callbacks . map ( async cb => cb ( cloned ) ) ) ;
482489 }
483490
484491 public async notifyResourceSaved ( resource : Resource ) : Promise < void > {
@@ -772,6 +779,52 @@ export class Store {
772779 return Array . from ( this . resources . values ( ) ) . filter ( filter ) ;
773780 }
774781
782+ /**
783+ * @Internal
784+ * Add the resource to a batch that is saved when the parent is saved. Only gets saved when the parent is new.
785+ */
786+ public batchResource ( subject : string ) {
787+ const resource = this . _resources . get ( subject ) ;
788+
789+ if ( ! resource ) {
790+ throw new Error (
791+ `Resource ${ subject } can not be saved because it is not in the store.` ,
792+ ) ;
793+ }
794+
795+ const parent = resource . get ( core . properties . parent ) ;
796+
797+ if ( parent === undefined ) {
798+ throw new Error (
799+ `Resource ${ subject } can not be added to a batch because it's missing a parent.` ,
800+ ) ;
801+ }
802+
803+ if ( ! this . batchedResources . has ( parent ) ) {
804+ this . batchedResources . set ( parent , new Set ( [ subject ] ) ) ;
805+ } else {
806+ this . batchedResources . get ( parent ) ! . add ( subject ) ;
807+ }
808+ }
809+
810+ /**
811+ * @Internal
812+ * Saves all resources that are in a batch for a parent.
813+ */
814+ public async saveBatchForParent ( subject : string ) {
815+ const subjects = this . batchedResources . get ( subject ) ;
816+
817+ if ( ! subjects ) return ;
818+
819+ for ( const resourceSubject of subjects ) {
820+ const resource = this . _resources . get ( resourceSubject ) ;
821+
822+ await resource ?. save ( this ) ;
823+ }
824+
825+ this . batchedResources . delete ( subject ) ;
826+ }
827+
775828 private randomPart ( ) : string {
776829 return Math . random ( ) . toString ( 36 ) . substring ( 2 ) ;
777830 }
0 commit comments