Просмотр исходного кода

[web] Convert `RecurlyWrapper` functions to async (#18384)

* Rename `RecurlyWrapper` to `promises`, as it will only contain the promises soon

* Update `apiRequest`

* Update `_parseXml`

* Update `_parseXmlAndGetAttribute`

* Update `_parse*Xml`

* Update `updateAccountEmailAddress`

* Update `checkAccountExists`

* Update `createAccount`

* Update `createBillingInfo`

* Update `setAddressAndCompanyBillingInfo`

* Update `createSubscription`

* Update `_createPaypalSubscription`

* Update `_handle422Response`

* Update `_createCreditCardSubscription`

* Update `createSubscription`

* Update `getSubscriptions`

* Update `getSubscription`

* Update `getPaginatedEndpoint`

* Update `getAccount`

* Update `getAccountActiveCoupons`

* Update `getCoupon`

* Update `getBillingInfo`

* Update `getAccountPastDueInvoices`

* Update `attemptInvoiceCollection`

* Update `updateSubscription`

* Update `createFixedAmmountCoupon`

* Update `lookupCoupon`

* Update `redeemCoupon`

* Update `extendTrial`

* Update `listAccountActiveSubscriptions`

* To find which functions to add as callbackified, I used this Regex:
`RecurlyWrapper\.(?!promises)[^.\s]*`

And after adding callbackified functions, we're left with no results with the Regex:
`RecurlyWrapper\.(?!promises|apiUrl|_buildXml|_parseXml|attemptInvoiceCollection|createFixedAmmountCoupon|getAccountActiveCoupons|getBillingInfo|getPaginatedEndpoint|getSubscription|updateAccountEmailAddress)[^.\s]*`

* Update unit tests

* Test `getSubscription` both as "promise" and as "callback"

I'm not sure if we want to generalize this.

* Fix: add missing `await`s (!!)

* Change `apiRequest` to reject errors instead of resolving it in an object

* Fixup for CollectPayPalPastDueInvoice test

* Fix: callbackify `getSubscriptions` (!!)

* Replace `.then(...)` chain by multiple `await`

* Fixup `attemptInvoicesCollection`: prevent reading length of undefined

* Use `return await` when returning promises

Per https://github.com/overleaf/internal/pull/18384#pullrequestreview-2065738771

GitOrigin-RevId: ceda755b24fd29f97a27e60ac5db9bc7e369f932
Antoine Clausse 2 лет назад
Родитель
Сommit
78a0bc2b05

Разница между файлами не показана из-за своего большого размера
+ 331 - 493
services/web/app/src/Features/Subscription/RecurlyWrapper.js


+ 4 - 4
services/web/scripts/recurly/collect_paypal_past_due_invoice.js

@@ -76,7 +76,7 @@ const main = async () => {
       'invoices',
       'invoices',
       { state: 'past_due' },
       { state: 'past_due' },
       (error, invoices) => {
       (error, invoices) => {
-        logger.info('invoices', invoices.length)
+        logger.info('invoices', invoices?.length)
         if (error) {
         if (error) {
           return callback(error)
           return callback(error)
         }
         }
@@ -90,7 +90,7 @@ const main = async () => {
   const INVOICES_COLLECTED_SUCCESS = []
   const INVOICES_COLLECTED_SUCCESS = []
   const USERS_COLLECTED = []
   const USERS_COLLECTED = []
 
 
-  return new Promise(resolve => {
+  return new Promise((resolve, reject) => {
     attemptInvoicesCollection(error => {
     attemptInvoicesCollection(error => {
       logger.info(
       logger.info(
         `DONE (DRY_RUN=${DRY_RUN}). ${INVOICES_COLLECTED.length} invoices collection attempts for ${USERS_COLLECTED.length} users. ${INVOICES_COLLECTED_SUCCESS.length} successful collections`
         `DONE (DRY_RUN=${DRY_RUN}). ${INVOICES_COLLECTED.length} invoices collection attempts for ${USERS_COLLECTED.length} users. ${INVOICES_COLLECTED_SUCCESS.length} successful collections`
@@ -105,11 +105,11 @@ const main = async () => {
       )
       )
 
 
       if (error) {
       if (error) {
-        throw error
+        reject(error)
       }
       }
 
 
       if (INVOICES_COLLECTED_SUCCESS.length === 0) {
       if (INVOICES_COLLECTED_SUCCESS.length === 0) {
-        throw new Error('No invoices collected')
+        reject(new Error('No invoices collected'))
       }
       }
 
 
       resolve({
       resolve({

+ 17 - 29
services/web/test/acceptance/src/CollectPayPalPastDueInvoiceTest.js

@@ -155,44 +155,32 @@ const invoiceCollectXml = `
 </invoice>
 </invoice>
 `
 `
 
 
-// from our logs
-const invoiceCollectErrXml2 = `
-<?xml version="1.0" encoding="UTF-8"?>
-<error>
-  <symbol>not_found</symbol>
-  <description lang="en-US">Couldn't find BillingInfo with account_code = abcdef87654321</description>
-</error>
-`
-
 describe('CollectPayPalPastDueInvoice', function () {
 describe('CollectPayPalPastDueInvoice', function () {
   let apiRequestStub
   let apiRequestStub
   const fakeApiRequests = invoiceIdsAndReturnCode => {
   const fakeApiRequests = invoiceIdsAndReturnCode => {
-    apiRequestStub = sinon.stub(RecurlyWrapper, 'apiRequest')
-    apiRequestStub.callsFake((options, callback) => {
+    apiRequestStub = sinon.stub(RecurlyWrapper.promises, 'apiRequest')
+    apiRequestStub.callsFake(options => {
       switch (options.url) {
       switch (options.url) {
         case 'invoices':
         case 'invoices':
-          callback(
-            null,
-            { statusCode: 200, headers: {} },
-            invoicesXml(invoiceIdsAndReturnCode)
-          )
-          return
+          return {
+            response: { statusCode: 200, headers: {} },
+            body: invoicesXml(invoiceIdsAndReturnCode),
+          }
         case 'accounts/200/billing_info':
         case 'accounts/200/billing_info':
         case 'accounts/404/billing_info':
         case 'accounts/404/billing_info':
-          callback(null, { statusCode: 200, headers: {} }, billingInfoXml)
-          return
+          return {
+            response: { statusCode: 200, headers: {} },
+            body: billingInfoXml,
+          }
         case 'invoices/200/collect':
         case 'invoices/200/collect':
-          callback(null, { statusCode: 200, headers: {} }, invoiceCollectXml)
-          return
+          return {
+            response: { statusCode: 200, headers: {} },
+            body: invoiceCollectXml,
+          }
         case 'invoices/404/collect':
         case 'invoices/404/collect':
-          callback(
-            new OError(`Recurly API returned with status code: 404`, {
-              statusCode: 404,
-            }),
-            { statusCode: 404, headers: {} },
-            invoiceCollectErrXml2
-          )
-          return
+          throw new OError(`Recurly API returned with status code: 404`, {
+            statusCode: 404,
+          })
         default:
         default:
           throw new Error(`Unexpected URL: ${options.url}`)
           throw new Error(`Unexpected URL: ${options.url}`)
       }
       }

Разница между файлами не показана из-за своего большого размера
+ 321 - 397
services/web/test/unit/src/Subscription/RecurlyWrapperTests.js


+ 1 - 1
services/web/test/unit/src/Subscription/SubscriptionHandlerTests.js

@@ -582,7 +582,7 @@ describe('SubscriptionHandler', function () {
           )
           )
       })
       })
 
 
-      it('should call RecurlyWrapper.listAccountActiveSubscriptions with the user id', function () {
+      it('should call RecurlyWrapper.promises.listAccountActiveSubscriptions with the user id', function () {
         this.RecurlyWrapper.promises.listAccountActiveSubscriptions
         this.RecurlyWrapper.promises.listAccountActiveSubscriptions
           .calledWith(this.user_id)
           .calledWith(this.user_id)
           .should.equal(true)
           .should.equal(true)

Некоторые файлы не были показаны из-за большого количества измененных файлов