@@ -729,12 +729,12 @@ export default {
729729 // When watching for changes to an entire account, we must pass a pageToken,
730730 // which points to the moment in time we want to start watching for changes:
731731 // https://developers.google.com/drive/api/v3/manage-changes
732+ const fn = ( ) => drive . changes . watch ( watchRequest ) ;
733+ const { data } = await this . retryWithExponentialBackoff ( fn ) ;
732734 const {
733735 expiration,
734736 resourceId,
735- } = (
736- await drive . changes . watch ( watchRequest )
737- ) . data ;
737+ } = data ;
738738 console . log ( `Watch request for drive successful, expiry: ${ expiration } ` ) ;
739739 return {
740740 expiration : parseInt ( expiration ) ,
@@ -744,16 +744,16 @@ export default {
744744 async watchFile ( id , address , fileId ) {
745745 const drive = this . drive ( ) ;
746746 const requestBody = this . _makeWatchRequestBody ( id , address ) ;
747+ const fn = ( ) => drive . files . watch ( {
748+ fileId,
749+ requestBody,
750+ supportsAllDrives : true ,
751+ } ) ;
752+ const { data } = await this . retryWithExponentialBackoff ( fn ) ;
747753 const {
748754 expiration,
749755 resourceId,
750- } = (
751- await drive . files . watch ( {
752- fileId,
753- requestBody,
754- supportsAllDrives : true ,
755- } )
756- ) . data ;
756+ } = data ;
757757 console . log (
758758 `Watch request for file ${ fileId } successful, expiry: ${ expiration } ` ,
759759 ) ;
@@ -1475,5 +1475,32 @@ export default {
14751475 const drive = this . drive ( ) ;
14761476 return ( await drive . accessproposals . resolve ( opts ) ) . data ;
14771477 } ,
1478+ retryWithExponentialBackoff ( func , maxAttempts = 3 , baseDelayS = 2 ) {
1479+ let attempt = 0 ;
1480+
1481+ const execute = async ( ) => {
1482+ try {
1483+ return await func ( ) ;
1484+ } catch ( error ) {
1485+ // retry for error status 422
1486+ const statusCode = error . status || error . response ?. status ;
1487+ if ( attempt >= maxAttempts || statusCode !== 422 ) {
1488+ throw error ;
1489+ }
1490+
1491+ // display error message for 422 status
1492+ const errorMessage = error . message || error . response ?. data ?. message || error . response ?. statusText || "Unknown error" ;
1493+ console . log ( `Received 422 error: ${ errorMessage } . Retrying attempt ${ attempt + 1 } /${ maxAttempts } ...` ) ;
1494+
1495+ const delayMs = Math . pow ( baseDelayS , attempt ) * 1000 ;
1496+ await new Promise ( ( resolve ) => setTimeout ( resolve , delayMs ) ) ;
1497+
1498+ attempt ++ ;
1499+ return execute ( ) ;
1500+ }
1501+ } ;
1502+
1503+ return execute ( ) ;
1504+ } ,
14781505 } ,
14791506} ;
0 commit comments