Arthur Roberto Fronza
Arthur Roberto Fronza

Reputation: 11

How to use dynamoDB async in serverless Nodejs project

How do you use async version of dynamo functions such as getItem()?

My code example:

import aws from 'aws-sdk';
import { AppError } from 'errors/AppError';
import { Request, Response } from 'express';
import { injectable } from 'tsyringe';
import { promisify } from 'util';

@injectable()
export class CreateMonitorActivityController {
  async handle(req: Request, res: Response): Promise<Response> {
    aws.config.update({region: 'us-east-1'});
    const DDB = new aws.DynamoDB({
      apiVersion: '2012-08-10',
    });

    const params = {
      TableName: String(table_name),
      Key: {
        'base_activity_id': {
          S: String(base_activity_id)
        }
      }
    };

    const result = DDB.getItem(
      params,
    );

    console.log(result);

    return res.send(result);
  }
}

In this case I just want to return the result, but the code doesn't wait the getItem() method to end.

I already tried to use the promisify from NodeJS utils and the bluebird but didn't fix.

Upvotes: 0

Views: 85

Answers (1)

Arthur Roberto Fronza
Arthur Roberto Fronza

Reputation: 11

Figured out, when using the await before the DDB.getItem() it was not working, but adding a promise() in the end made it works.

Fixed code:

import aws from 'aws-sdk';
import { AppError } from 'errors/AppError';
import { Request, Response } from 'express';
import { injectable } from 'tsyringe';

@injectable()
export class CreateMonitorActivityController {
  async handle(req: Request, res: Response): Promise<Response> {
    const {
      table_name,
      base_activity_id,
    } = req.query;

    aws.config.update({region: 'us-east-1'});
    const DDB = new aws.DynamoDB({
      apiVersion: '2012-08-10',
    });

    const params = {
      TableName: String(table_name),
      Key: {
        'base_activity_id': {
          S: String(base_activity_id)
        }
      }
    };

    const result = await DDB.getItem(
      params,
    ).promise();

    return res.send(result)
  }
}

Upvotes: 1

Related Questions