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);
});
```