1
\$\begingroup\$

I am rather new to JavaScript and never really worked with promises before. My code works but I would like to learn if there is a better approach?

I want to implement the following functionality:

  • Query DB to check if user is in a team
  • if yes, query DB for items belonging to that team

Both functions return promises.

Thanks a lot.

var AWS = require("aws-sdk");
var _ = require("underscore");

AWS.config.update({
  region: "ap-southeast-1",
  endpoint: "http://localhost:8042",
});

var dynamoDb = new AWS.DynamoDB.DocumentClient();

var userID = "user123";
var teamID = "team456";


function checkUserIsTeamMember(teamID, userID) {
  return new Promise(function (resolve, reject) {
    // get team
    let params = {
      TableName: "someTable",
      ScanIndexForward: true,
      KeyConditionExpression: "#PK = :PK And begins_with(#SK, :SK)",
      ExpressionAttributeValues: {
        ":PK": "T#" + teamID,
        ":SK": "U#" + userID,
      },
      ExpressionAttributeNames: {
        "#PK": "PK",
        "#SK": "SK",
      },
    };
    dynamoDb
      .query(params)
      .promise()
      .then((data) => {
        if (data.Count > 0) {
          resolve("User is team member.");
        } else {
          reject("User is not team member.");
        }
      });
  });
}

function getItems(teamID) {
  return new Promise(function (resolve, reject) {
    let params = {
      TableName: "someTable",
      ScanIndexForward: true,
      IndexName: "GSI2",
      KeyConditionExpression: "#PK = :PK And begins_with(#SK, :SK)",
      ExpressionAttributeValues: {
        ":PK": "T#" + teamID,
        ":SK": "I#",
      },
      ExpressionAttributeNames: {
        "#PK": "GSI2PK",
        "#SK": "GSI2SK",
      },
    };

    // check first
    checkUserIsTeamMember(teamID, userID)
      .then((data) => {
        console.log(data);
        
        // resolve another promise
        resolve(dynamoDb.query(params).promise());
      })
      .catch((err) => {
        console.log(err);
        // return empty list if user is not authorized (not team member)
        // not sure if resolving this in the catch block is correct

        resolve([]);
      });
  });
}

getItems(teamID).then((data) => {
  console.log(data.Items);
});

```
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Welcome to the Code Review Community. It helps us give a better review when the title indicates what the code does. \$\endgroup\$
    – pacmaninbw
    Jun 7, 2021 at 14:13

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.