Search code examples
loopbackjsloopback4

How to return a callback's function return value


I'm using loopback-next along with the stripe api. In the stripe API, I call retrieve account as follows, in a payments.controller.ts file:

@post('/payments/retrieve-stripe/{id}', {
    responses: {
      '200': {
        description: 'User model instance',
        content: {'application/json': {schema: {'x-ts-type': User}}},
      },
    },
  })
  async retrieveStripe(@param.path.number('id') id: number,
  @requestBody() req: any): Promise<any> {
    console.log(req);
    if (!req.stripeAccountId) {
      throw new HttpErrors.NotFound('No Stripe Account');
    }
    else {
    return await stripe.accounts.retrieve(
  req.stripeAccountId,
  function(err: any, account: any) {
    return err ?  err : account
  })
    }
  }

However, when I try return account, nothing is returned in the JSON body. If i try, response.json on the front end, it said that the JSON unexpectedly finished, meaning there is nothing in the body. How would I be able to successfully return account in the above function inside of a controller function?

This was the same problem I had for trying to return a string as well. I'm not sure what to do.

EDIT: I learned that you cannot return variables in a callback and that is the issue.


Solution

  • You have to require type definitions (@types/stripe) to use its library in promise style. After that you can use in following way:-

     @post('/payments/retrieve-stripe/{id}', {
        responses: {
          '200': {
            description: 'User model instance',
            content: { 'application/json': { schema: { type: 'object' } } },
          },
        },
      })
      async retrieveStripe(@param.path.number('id') id: number,
        @requestBody() req: any): Promise<any> {
        console.log(req);
        if (!req.stripeAccountId) {
          throw new HttpErrors.NotFound('No Stripe Account');
        } else {
          return await stripe.accounts.retrieve(req.stripeAccountId).then((res: any) => {
            return res;
          }).catch((err: any) => {
            console.debug(err);
            throw new HttpErrors.InternalServerError('Something went wrong!')
          });
        }
      }
    

    For more details https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/stripe/stripe-tests.ts