Anab
Anab

Reputation: 99

Listing cognito userpool users on AWS lambda

I'm trying to list all of my cognito users in my lambda function, however i get nothing in the return as if the callback not getting executed. What am I doing wrong?

The output of the code below just gives me a hello in the console.

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

const cognitoidentityserviceprovider = new AWS.CognitoIdentityServiceProvider();
export async function main() {
console.log("hello")
  var params = {
    UserPoolId: "myuserpoolid",
    AttributesToGet: ["username"]
  };

  cognitoidentityserviceprovider.listUsers(params, (err, data) => {
    if (err) {
      console.log(err, err.stack);
      return err;
    } else {
      console.log(data);
      return data;
    }
  });
}

Upvotes: 4

Views: 2996

Answers (2)

koral
koral

Reputation: 6650

For AttributesToGet, don't use username because it is one of the fields that always gets returned. The following are members of the Attributes array, and can be used in the AttributesToGet field:

sub, email_verified, phone_number_verified, phone_number, email.

e.g.

AttributesToGet: ["email","email_verified"]

Upvotes: 0

Matus Dubrava
Matus Dubrava

Reputation: 14462

First of all, the structure of the code is wrong. The header of Lambda function should have a certain structure, either using async function or non-async function. Since you are using non-async code in your example I will show you how to do the later.

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

const cognitoidentityserviceprovider = new AWS.CognitoIdentityServiceProvider();

exports.handler =  function(event, context, callback) {
  console.log("hello")
  var params = {
    UserPoolId: "myuserpoolid",
    AttributesToGet: ["username"]
  };

  cognitoidentityserviceprovider.listUsers(params, (err, data) => {
    if (err) {
      console.log(err, err.stack);
      callback(err)        // here is the error return
    } else {
      console.log(data);
      callback(null, data) // here is the success return
    }
  });
}

In this case, Lambda will finish only when callback is called (or when it times out).

Similarly, you can use async function but you will need to restructure your code accordingly. Here is an example taken from official docs. Note how the promise wrapper is used.

const https = require('https')
let url = "https://docs.aws.amazon.com/lambda/latest/dg/welcome.html"

exports.handler = async function(event) {
  const promise = new Promise(function(resolve, reject) {
    https.get(url, (res) => {
        resolve(res.statusCode)
      }).on('error', (e) => {
        reject(Error(e))
      })
    })
  return promise
}

Upvotes: 4

Related Questions