AWS Textract does not run callback in error free run of analyzeDocument - aws-lambda

CURRENTLY
I am trying to get AWS Textract working on a Lambda function and am following documentation on https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Textract.html#analyzeDocument-property
My Lambda code:
"use strict";
const AWS = require("aws-sdk");
exports.handler = async (event) => {
let params = JSON.parse(event.body);
console.log("Parse as document...");
let textract = new AWS.Textract();
let doc = params["doc"];
let config = {
Document: {
Bytes: doc,
}
};
textract.analyzeDocument(config, function (err, data) {
console.log("analyzing..."); //<-- nothing logged to console if no error
if (err) {
console.log(err, err.stack);
}
// an error occurred
else {
console.log("data:" + JSON.stringfy(data)); //<-- nothing logged to console if no error
} // successful response
});
console.log("Finished parsing as document.");
};
ISSUE
I cannot get the data back from Textract. It seems I am unable to get the callback working entirely. What's odd is if there is an error e.g. my configuration is wrong, the error handling of the callback will print the log and "analyzing..." log, but without error, none of the logs in the callback print.
Current Logs:
Parse as document...
Finished parsing as document.
Expected / Desired Logs:
Parse as document...
analyzing...
data:{textract output}
Finished parsing as document.
Please help!
NOTES
I am using a role for that Lambda that allows it to access Textract.
I get the same result whether I include the HumanLoopConfig settings or not.

Solved, apparently I needed to setup a promise:
let data = await textract.analyzeDocument(config).promise()
console.log("data:"+data );
console.log("Finished parsing as document.")

Related

Parse Cloud Code Queries do not return anything ever

I have some parse cloud code im running on my self hosted server but im running into an issue where queries are not doing anything. I can run commands through terminal and get data back but when I run a query.find.. nothing happens. For Example:
Parse.Cloud.job("getall", function(request, response) {
var itemStatus = Parse.Object.extend('MovieStatus');
var query = new Parse.Query(itemStatus);
query.find({
success: function(results) {
console.log(results.length)
response.success(results.length);
},
error: function(err) {
response.error(err);
},
useMasterKey : true
})
})
Nothing happens. No error no response. I have added console logs to make sure its at least getting called and it is, but for some reason nothing every returns from the server when I do query.find
I have tried all sorts of things to figure out what the issue is but this affects all of my cloud code so it has to be something in there.
You are using an old syntax. Since version 3.0, Parse Server supports async/await style. Try this:
Parse.Cloud.job("getall", async request => {
​const { log, message } = request;
const ItemStatus = Parse.Object.extend('MovieStatus');
const query = new Parse.Query(ItemStatus);
const results = await query.find({ useMasterKey: true });
log(response.length);
message(response.length);
})
Not this is a job and not a cloud code function. You can invoke this job using Parse Dashboard and you should see the message in the job status section.

GET request with query parameters returns 403 error (signature does not match) - AWS Amplify

Problem
I was trying to use 'aws-amplify' GET API request with query parameters on the client side, but it turned out to be Request failed with status code 403, and the response showed:
"message":"The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.
Note: React.js as front-end, Javascript as back-end.
My code
Front-end
function getData() {
const apiName = 'MyApiName';
const path = '/path';
const content = {
body:{
data:'myData',
},
};
return API.get(apiName, path, content);
}
Back-end
try {
const result = await dynamoDbLib.call("query", params);
} catch (e) {
return failure({ status: false });
}
What I did to debug
The GET lambda function works fine in Amazon Console (Tested)
If I change the backend lambda function so that the frontend request can be made without parameters, i.e. return API.get(apiName, path), then no error shows up.
My question
How can I make this GET request with query parameters works?
I changed GET to POST (return API.post()), everything works fine now.
If anyone can provide a more detailed explanation, it would be very helpful.

How to fetch data from a REST API in serverless?

I am new to serverless. I want to fetch data from google. I am using Google Custom Search engine. Although I got results when I run locally. But when I deploy to AWS Lambda I am getting "Internal Server Error". Can anyone help me to fix the issue?
'use strict';
var request = require('request');
module.exports.get = (event, context, callback) => {
request('https://www.googleapis.com/customsearch/v1?q=Serverless+AWS+Lambda&cx=xxxxxxxxxxx&key=API_key&num=10', function (error, response, body) {
if (!error && response.statusCode == 200) {
callback(null, response);
console.log(body);
} else {
console.warn(error);
}
});
};
I want a json output. I would like to save that result
Internal Server Error mostly points out that your lambda code could not be executed correctly. Did you pack all your dependencies (node_modules) within the ZIP file you provide to AWS lambda (e.g. request ?)

Can I use https.request in vscode extension

I am creating a VSCode Extension.
I have added MSTranslator as a node module because I want to call the Microsoft Translator API
but when I run the example either nothing happens,
or I get a Error Connect EACCES. I get this error 2 or 3 times but now it has stopped returning anything, it just jumps the code and continues
I am running this on a MacBook
if (!api_key) {
console.log('missing api_key');
}
var params = {
text: 'How\'s it going?',
from: 'en',
to: 'es'
};
var client = new MsTranslator({ api_key: api_key });
client.initialize_token(function (err) {
if (err) {
console.log("initialize_token", err);
return;
}
client.translate(params, function (err, data) {
if (err) console.log('error:' + err.message);
console.log(data);
process.exit();
});
});
and when it enters client.initialize_token it reaches this line in MsTranslator and does nothing, just jumps out of function.
var req = https.request(self.options, function(res) {
My Radio Silence firewall is switched off, and the network monitor shows no activity.
If I call the same URL using the same details in self.options using Postman, I get back a token as expected.
Is there a problem running https.request within a VSCode extension, or do I have a different problem?

Cognito post verification lambda call causes failure

I have a lambda function that is invoked when a cognito user submits their verification code.
PostConfirmation failed with error RequestId: 3241xxxx-3cxx-11xx-aexx-8b39059xxxxx Process exited before completing request.
at constructor.e (<anonymous>:21:4685)
at constructor.callListeners (<anonymous>:21:24558)
at constructor.emit (<anonymous>:21:24267)
at constructor.emitEvent (<anonymous>:21:18671)
at constructor.a (<anonymous>:21:14521)
at d.runTo (<anonymous>:22:12444)
at <anonymous>:22:12651
at constructor.<anonymous> (<anonymous>:21:14731)
at constructor.<anonymous> (<anonymous>:21:18726)
at constructor.callListeners (<anonymous>:21:24664)
And my lambda function's job is to receive that submission and publish a message to SQS, and then continue.
module.exports.trigger_userVerified = (event, context, callback) => {
const AWS = require('aws-sdk');
var nickname = event.request.userAttributes.nickname;
var params = {
MessageBody: 'A user has registered an account and has supplied a website address.',
QueueUrl: ' https://sqs.us-east-1.amazonaws.com/xxx/my_sqs_queue',
DelaySeconds: 0,
MessageAttributes: {
'nickname': {
DataType: 'String',
StringValue: nickname
}
}
};
sqs.sendMessage(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
context.done(null, event);
});
};
Is there something wrong with the way I'm handling this lambda function that causes this error? how do I investigate further?
The error "Process exited before completing request" means that the lambda Javascript function exited before calling context.done (or context.succeed, etc.). Most of the times this means that there is an error in the function.
I'm not a Javascript expert (at all) so there may be more elegant ways to find the error but my approach has been to put a bunch of console.log messages in my code, run it, and then look at the logs. I can usually zero in on the offending line and, if I look at it long enough, I can usually figure out my mistake.
Since it's lambda:
Please check your cloudwatch logs and see if you can find more. In your place I would add some console.log statements as well.

Resources