AWS - Cannot read property 'username' of undefined - amazon-web-services

I got an error: Cannot read property 'username' of undefined and also the const username will say that it is not used.
Complete Errror:
Response:
{
"errorType": "TypeError",
"errorMessage": "Cannot read property 'username' of undefined",
"trace": [
"TypeError: Cannot read property 'username' of undefined",
" at Runtime.exports.handler (/var/task/index.js:7:50)",
" at Runtime.handleOnce (/var/runtime/Runtime.js:66:25)"
]
}
Code:
exports.handler = (event, context, callback) => {
console.log(event);
const connectionId = event.requestContext.connectionId;
const username = event.queryStringParameters.username;
addConnectionId(connectionId).then(() => {
callback(null, {
statusCode: 200,
});
});};
function addConnectionId(connectionId) {
const params = {
TableName: 'Chat',
Item: {
'connection_id' : connectionId,
'username' : username
}
};
return ddb.put(params).promise();
}

You need to enable Use Lambda Proxy integration to access query parameters.

Related

Lambda function with UpdateRestApiCommand, how to update to work in version node 18

I updated a lambda function to node 18, but there are changes to do with my UpdateRestApiCommand.
Here's the original that worked in the older version:
const request = apigateway.updateRestApi(params);
request
.on('success', function(response) {
console.log("Success!");
resolve(response.data);
}).
on('error', function(error, response) {
console.log("Error!");
reject(response.error);
}).
on('complete', function(response) {
console.log("Done!");
})
.send()
});
Here's my imports:
const https = require("https");
const env = process.env.ENV;
const resource = process.env.RESOURCE;
const restApiId = process.env.REST_API_ID;
const ce_base_url = process.env.CE_BASE_URL;
const { APIGatewayClient, UpdateRestApiCommand } = require("#aws-sdk/client-api-gateway");
const stage = process.env.STAGE;
And now I've found I need to use UpdateRestApiCommand I think so I've got this:
new UpdateRestApiCommand(params)
.on('success', function(response) {
console.log("Success!");
resolve(response.data);
}).
on('error', function(error, response) {
console.log("Error!");
reject(response.error);
}).
on('complete', function(response) {
console.log("Done!");
})
.send()
});
Here's the error I'm getting:
ERROR Invoke Error
{
"errorType": "TypeError",
"errorMessage": "(intermediate value).on is not a function",
"stack": [
"TypeError: (intermediate value).on is not a function",
" at /var/task/index.js:64:8",
" at new Promise (<anonymous>)",
" at exports.handler (/var/task/index.js:36:25)",
" at process.processTicksAndRejections (node:internal/process/task_queues:95:5)"
]
}
The nodejs18.x runtime has the AWS JS SDK v3 pre-installed. Earlier runtime versions came with v2.
Here's the basic pattern to use the v3 SDK clients in a Lambda handler:
const client = new APIGatewayClient({
region: process.env.AWS_REGION,
});
export async function handler(event, context) {
// ...
const cmd = new UpdateRestApiCommand(params);
const response = await client.send(cmd);
}

finding user on aws cognito throws error cognitoidentityserviceprovider is not defined

I am new to AWS services and I am trying out various services provided by AWS. I have this lambda function on which I am trying to find a user with the phone number on AWS Cognito -
const AWS = require('aws-sdk');
async function findCognitoUser(userId) {
console.log('CognitoUser-FindCognitoUser');
var params = {
UserPoolId: 'poolId',
AttributesToGet: [
'phone_number','displayName'
],
Filter: `phone_number = \"${userId}\"`,
};
cognitoidentityserviceprovider.listUsers(params, function(err, data) {
if (err) {
return 'ERROR OCCURED';
}
else {
return data.Users[0].displayName;
}
});
}
module.exports = findCognitoUser;
I do get an error saying cognitoidentityserviceprovider is not defined
Here is the error on CloudWatch -
"errorType": "ReferenceError",
"errorMessage": "cognitoidentityserviceprovider is not defined",
"stack": [
"ReferenceError: cognitoidentityserviceprovider is not defined",
" at findCognitoUser (/var/task/user-queries/findCognitoUser.js:13:5)",
" at Runtime.exports.handler (/var/task/index.js:14:19)",
" at Runtime.handleOnce (/var/runtime/Runtime.js:66:25)"
]
CODE UPDATED -
const AWS = require('aws-sdk');
async function findCognitoUser(userId) {
console.log(userId);
var csp = new AWS.CognitoIdentityServiceProvider({apiVersion: '2016-04-18'});
var params = {
UserPoolId: 'poolid',
AttributesToGet: [
'phone_number','given_name'
],
Filter: `phone_number = \"${userId}\"`,
};
csp.listUsers(params, function(err, data) {
console.log(data);
if (err) {
return 'ERROR OCCURED';
}
else {
return data.Users[0].given_name;
}
});
}
module.exports = findCognitoUser;

Hi, I try to run a Lambda function but i get the next error when I execute a test event

This is my complete error on the test event details execution, whe i try to test my function this error its appears
{
"errorType": "TypeError",
"errorMessage": "Cannot read property 'NaN' of undefined",
"trace": [
"TypeError: Cannot read property 'NaN' of undefined",
" at findCar (/var/task/index.js:87:22)",
" at processTicksAndRejections (internal/process/task_queues.js:95:5)",
" at async Runtime.exports.handler (/var/task/index.js:46:17)"
]
}
This is the code for the lambda function for execute the requesting a car on my website...
const randomBytes = require('crypto').randomBytes;
const AWS = require('aws-sdk');
const ddb = new AWS.DynamoDB.DocumentClient();
const params = {
TableName : 'Cars'
}
async function listCars(){
console.log("Starting query to fetch cars data.")
try {
const data = await ddb.scan(params).promise()
console.log("Data retrieved, Printing Data from Cars table......")
console.log(data)
return data
} catch (err) {
console.log("Error occurred while retrieving cars......" + err)
return err
}
}
exports.handler = async (event, context, callback) => {
if (!event.requestContext.authorizer) {
errorResponse('Authorization not configured', context.awsRequestId, callback);
return;
}
const rideId = toUrlString(randomBytes(16));
console.log('Received event (', rideId, '): ', event);
// Because we're using a Cognito User Pools authorizer, all of the claims
// included in the authentication token are provided in the request context.
// This includes the username as well as other attributes.
const username = event.requestContext.authorizer.claims['cognito:username'];
// The body field of the event in a proxy integration is a raw string.
// In order to extract meaningful values, we need to first parse this string
// into an object. A more robust implementation might inspect the Content-Type
// header first and use a different parsing strategy based on that value.
const requestBody = JSON.parse(event.body);
const pickupLocation = requestBody.PickupLocation;
const car = await findCar(pickupLocation);
return recordRide(rideId, username, car).then(() => {
// You can use the callback function to provide a return value from your Node.js
// Lambda functions. The first parameter is used for failed invocations. The
// second parameter specifies the result data of the invocation.
// Because this Lambda function is called by an API Gateway proxy integration
// the result object must use the following structure.
callback(null, {
statusCode: 201,
body: JSON.stringify({
RideId: rideId,
Car: car,
CarName: car.carName,
Eta: '30 seconds',
Rider: username,
}),
headers: {
'Access-Control-Allow-Origin': '*',
},
});
}).catch((err) => {
console.error("printing error on record ride: "+ err);
// If there is an error during processing, catch it and return
// from the Lambda function successfully. Specify a 500 HTTP status
// code and provide an error message in the body. This will provide a
// more meaningful error response to the end client.
errorResponse(err.message, context.awsRequestId, callback)
});
};
// This is where you would implement logic to find the optimal car for
// this ride (possibly invoking another Lambda function as a microservice.)
// For simplicity, we'll just pick a car at random.
async function findCar(pickupLocation) {
console.log('Finding car for ', pickupLocation.Latitude, ', ', pickupLocation.Longitude);
const cars = await listCars();
return cars.Items[Math.floor(Math.random() * cars.Count)];
}
function recordRide(rideId, username, car) {
console.log("Car inside recordRide function" + car.carName)
return ddb.put({
TableName: 'Rides',
Item: {
RideId: rideId,
User: username,
Car: car,
CarName: car.carName,
RequestTime: new Date().toISOString(),
},
}).promise();
}
function toUrlString(buffer) {
return buffer.toString('base64')
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=/g, '');
}
function errorResponse(errorMessage, awsRequestId, callback) {
callback(null, {
statusCode: 500,
body: JSON.stringify({
Error: errorMessage,
Reference: awsRequestId,
}),
headers: {
'Access-Control-Allow-Origin': '*',
},
});
}
And finally my testEvent code that I establish for testing my function...
{
"path": "/ride",
"httpMethod": "POST",
"headers": {
"Accept": "*/*",
"Authorization": "fDjWQiOiJLTzRVMWZs",
"content-type": "application/json; charset=UTF-8"
},
"queryStringParameters": null,
"pathParameters": null,
"requestContext": {
"authorizer": {
"claims": {
"cognito:username": "the_username"
}
}
},
"body": "{\"PickupLocation\":{\"Latitude\":47.6174755835663,\"Longitude\":-122.28837066650185}}"
}
I hope that you can help me with this...
You aren't checking that anything is returned from the database after querying for cars. If the returned data has neither Items nor Count properties, then you get the error that you see:
> cars = {}
{}
> cars.Items[Math.floor(Math.random() * cars.Count)]
Uncaught TypeError: Cannot read property 'NaN' of undefined

lambda function outputted an error "e is not a function"

created two lambda functions by serverless-framework. first function "record-song-vote" writes DynamoDB, it works fine. second function "get-vote-counts" reads all records from DynamoDB, but it continually return error:
{
"errorType": "TypeError",
"errorMessage": "e is not a function",
"trace": [
"TypeError: e is not a function",
" at Runtime.handler (/var/task/serverless_sdk/index.js:9:131872)",
" at Runtime.handleOnce (/var/runtime/Runtime.js:66:25)"
]
}
function get-vote-counts:
'use strict';
const AWS = require("aws-sdk");
const dynamodb = new AWS.DynamoDB.DocumentClient();
module.exports.handler = async event => {
const params = {
TableName: process.env.DYNAMODB_TABLE
};
const result = await dynamodb.scan(params, (error, data) => {
if (error) {
console.error("Unable to update item. Error JSON:", JSON.stringify(error, null, 2));
} else {
console.log("UpdateItem succeeded:", JSON.stringify(data, null, 2));
}
}).promise();
const outputData = result["Items"].map((item) => {
return {
songName: item['songName'],
votes: item['votes']
}
});
return {
"statusCode": 200,
"headers": {
"Access-Control-Allow-Origin": "*"
},
"body": JSON.stringify(outputData)
}
};
I have tried to comment all line in this file. but I still got same error. does anybody have idea?

"Converting circular structure to JSON" while reading data from MYSQL and putting it in DynamoDB

I am reading data from read replica of Aurora and putting it into the DynamoDB. I getting data from RDS correctly but facing problems while inserting it into DynamoDB. I am sharing my code and error message please guide me....
var AWS = require("aws-sdk");
var mysql = require('mysql');
const client = new AWS.DynamoDB.DocumentClient({region : 'eu-west-1'});
var connection = mysql.createPool({
host : "**********",
user : "****",
password : "*****",
database : "mydb",
port : "3306"
});
exports.handler = (event, context, callback) => {
connection.query('select * from demo where id=2;', function (error, results, fields) {
if (error) {
if (error) throw error;
} else {
var data = {results};
var params = {
Item:{
test_id:data.id,
name:data.name,
result:data.result
},
TableName: 'demo_rds_dynamoDB'
};
connection.end(function (err) {
callback(err, client.put(params, function(error,data){
if(error){
callback(error,null);
}else{
callback(null,data);
}
})
);
});
}
});
};
Following is the data I am getting from Aurora and I want to put in DynamoDB
Response:
[
{
"id": 2,
"name": "Display",
"result": "Pass"
}
]
And the response m getting is as follow and sometimes i get error as Cannot read property "id" undefined,
Response:
{
"errorMessage": "Converting circular structure to JSON",
"errorType": "TypeError",
"stackTrace": []
}
Request ID:
"896a64e3-573e-11e8-bb94-67c4be71eb3d"
Function Logs:
START RequestId: 896a64e3-573e-11e8-bb94-67c4be71eb3d Version: $LATEST
Unable to stringify response body as json: Converting circular structure to JSON: TypeError
at Object.stringify (native)
Item:{
test_id:results[0].id,
name:results[0].name,
result:results[0].result
}
results[0].columnname