Amazon DynamoDB - Scanning Itens using JS - javascript

I've have tried to scan a table and filter it by its secondary key, which is Number named Group. If I applied this sacn at Amazon Web Console, the result is simple and right:
But using JavaScript I only got an empty result. Here is the JS code:
var id;
console.log("scan products")
// Get the id from the pathParams
id = request.pathParams.id;
console.log(id)
var params = {
TableName: request.env.tableName,
FilterExpression: '#product_group = :this_group',
ExpressionAttributeValues : {':this_group': {N:id}},
ExpressionAttributeNames: {'#product_group':'group'}
};
console.log("aqui")
console.log(params.ExpressionAttributeValues)
// post-process dynamo result before returning
return dynamo.scan(params).promise().then(function (response) {
return response;
});
Here you can see my result output:
2018-01-04T16:53:38.223Z ce022431-f16f-11e7-8a90-4f25e3228700 { headers:
{ 'content-type': 'application/json',
'content-length': '40',
connection: 'close',
date: 'Thu, 04 Jan 2018 16:53:38 GMT',
'x-amzn-requestid': 'ce6663b2-f16f-11e7-913f-c1a766cd30ad',
'access-control-allow-origin': '*',
'access-control-allow-headers': 'Content-Type,Authorization,X-Amz-Date,X-Api-Key,X-Amz-Security-Token',
'access-control-allow-methods': 'GET,OPTIONS',
'x-amzn-trace-id': 'sampled=0;root=1-5a4e5c10-f5dbe9d3ad72eb4f1f5bdc12',
'access-control-max-age': '0',
'access-control-allow-credentials': 'true',
'x-cache': 'Miss from cloudfront',
via: '1.1 aa9a6b87feabe1a30d21428a24c1a7d8.cloudfront.net (CloudFront)',
'x-amz-cf-id': 'AvS-yi8Y_-b6nwyYNosEGxpvpBkMptFigjldwZmO3ros6kO8JdBZhQ==' },
body: '{"Items":[],"Count":0,"ScannedCount":14}',
statusCode: 200,
statusMessage: 'OK' }
I don't know what I'm possible doing wrong since it is a really simple scan.

Please scan until the LastEvaluatedKey is null to go through all the items in the Dynamodb table. The single scan will go through only 1 MB of data.
Please execute the scan until LastEvaluatedKey is null.
A single Scan operation will read up to the maximum number of items
set (if using the Limit parameter) or a maximum of 1 MB of data and
then apply any filtering to the results using FilterExpression. If
LastEvaluatedKey is present in the response, you will need to paginate
the result set.
API Scan
Scan table - sample code
Note the below code:-
The scan should be executed until LastEvaluatedKey is undefined or null.
if (typeof data.LastEvaluatedKey != "undefined") {
console.log("Scanning for more...");
params.ExclusiveStartKey = data.LastEvaluatedKey;
docClient.scan(params, onScan);
}

Related

What is causing this TypeError in my Google Apps Script?

I'm trying to call data from Coin Market Cap to a Google sheet via Apps Script. I don't understand the TypeError I'm doing here.
Here is the code:
function getCryptoPrice() {
var sh1=SpreadsheetApp.getActiveSpreadsheet().getSheetByName("EPS data CMC");
var url="https://pro-api.coinmarketcap.com/v2/cryptocurrency/quotes/latest?symbol=BTC"
var requestOptions = {
method: 'GET',
uri: 'https://pro-api.coinmarketcap.com/v2/cryptocurrency/quotes/latest',
qs: {
start: 1,
limit: 5000,
convert: 'USD'
},
headers: {
'X-CMC_PRO_API_KEY': '***********hidden*************'
},
json: true,
gzip: true
};
var httpRequest= UrlFetchApp.fetch(url, requestOptions);
var getContext= httpRequest.getContentText();
var parseData=JSON.parse(getContext);
sh1.getRange(1, 2).setValue(parseData.data.BTC.quote.USD.price)
}
And the error:
TypeError: Cannot read property 'USD' of undefined
getCryptoPrice # Code.gs:24
Keywords : google sheet, apps script, coin market cap, quote, latest, V2, api,
You're getting that error because parseData.data.BTC is returning an array.
Try changing this to:-
sh1.getRange(1, 2).setValue(parseData.data.BTC.quote.USD.price)
this
sh1.getRange(1, 2).setValue(parseData.data.BTC[0].quote.USD.price)

How to use getByDataFilter Sheets API v4 to get specific row data

I need to get specific data row of this table:
Google Sheet Data Base
, for that I am using the following filter parameter:
var filter = {
"dataFilters": [
{
"developerMetadataLookup": {
"metadataValue": "julian#domain3.com"
}
}
]
};
but the current result is as follows:
response: {
"spreadsheetId": "1chGysP"
}
The result I need is something like the following:
response: {
"range": "'Hoja 1'!A4:D4",
"majorDimension": "ROWS",
"values": [
[
"3",
"domain4",
"julian#domain3.com",
"Active"
]
]
}
I found a similar question to mine, and it seems to work but I think I wouldn't be taking advantage of using the api directly like checking quotas, reporting dashboard and so on.
How can I use the Google Sheets (v4) API getByDataFilter to return a specific row of data?
My complete code is as follows:
//function for bot that runs asynchronously from Google Apps Script
function consultData(){
var url = 'https://sheets.googleapis.com/v4/spreadsheets/1chGysP/values:batchGetByDataFilter?key=KAIzaSy'
var service = getOAuthService();
service.reset()
var filter = {
"dataFilters": [
{
"developerMetadataLookup": {
"metadataValue": "julian#domain3.com"
}
}
]
};
var params = {
headers: {
Authorization: 'Bearer ' + service.getAccessToken()
},
method: 'get',
contentType: 'application/json',
payload: JSON.stringify(filter),
muteHttpExceptions: true
};
var response = UrlFetchApp.fetch(url, params).getContentText();
Logger.log('response: ' + response);
return response;
}
API reference:
https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/getByDataFilter
The most practical and scalable solution in my case for having increasing information is not to use sheets as a database, firstly because it has a limit on records https://support.google.com/drive/answer/37603?hl=es
and limit in metadata that is needed for getDataFilter for condition by values
https://developers.google.com/sheets/api/guides/metadata
My quick and effective solution was to have my information repository in Firebase, and with this library it is extremely easy to make the connection, queries, overwrites, creations:
https://github.com/grahamearley/FirestoreGoogleAppsScript

Twitter Search API- How to implement premium access keys in NODE.JS?

I am using npm-twit in node.js to get tweets with the twitter search api.
I am totally new to programming but need it for my master thesis. I therefore got the premium account with full archive access to the search requests.
With the standard free api access my code worked without any problems. But now I do not know how to correctly implement access tokens etc.
I tried putting product and label in different places and changed q to query and data.statues to data.results but anything I tried gives me several error codes - like
'code: 195, message: 'Missing or invalid url parameter.'
'code: 25, message: 'Query parameters are missing.'
'message: 'Sorry, that page does not exist', code: 34'.
Or tells me that tweets.length does not exist (even though it worked before).
Or a simple 'null'
(when I use this code snipped :
T.get('search/tweets/fullarchive/:dev', params , gotData); function gotData(err, data, response){console.log(data)}
)
//This is the current code which is not working
var Twit = require('twit');
var config = require('./config');
var T = new Twit({
consumer_key: 'XXX',
consumer_secret: 'XXX',
access_token: 'XXX',
access_token_secret: 'XXX',
timeout_ms: 60*1000,
strictSSL: true,
app_only_auth: true,
PRODUCT: 'fullarchive',
LABEL: 'dev',});
var params = {
query: 'VW',
fromDate:'201801010000',
toDate:'201901010000',
followers_count:1000,
maxResults: 500,
result_type: 'popular',
lang: 'en'
//next: ''
}
T.get('search/tweets/fullarchive/:dev', params , gotData);
//T.get('search/tweets', params , gotData); - gives me all results in standard api
function gotData(err, data, response)
{
var tweets = data.results; //var tweets = data.statuses - gives me what I need in standard api
for (var i = 0; i < tweets.length; i++)
console.log(tweets[i].text, tweets[i].retweet_count,tweets[i].created_at,tweets[i].id_str,tweets[i].favorite_count,);
With this code I get an error 'Unhandled rejection TypeError: Cannot read property 'results' of null'
Ideally I want to get information about the tweet containing its text, creation date, retweet count, tweet id, favorite count - and if possible the "next" token when needed.
I would really appreciate any help!

Creating an envelope from a template returning "UNSPECIFIED_ERROR"

When I try to create an envelope from a template I get a response of:
{ errorCode: 'UNSPECIFIED_ERROR',
message: 'Non-static method requires a target.' }
Here's what I'm doing so far:
First I login, which returns
{ loginAccounts:
[ { name: '*****',
accountId: '*****',
baseUrl: 'https://demo.docusign.net/restapi/v2/accounts/******',
isDefault: 'true',
userName: '***** ********',
userId: '*******-*****-*****-*****-*********',
email: '********#*******.com',
siteDescription: '' } ] }
So then I take the baseUrl out of that response and I attempt to create the envelope. I'm using the hapi framework and async.waterfall of the async library, so for anyone unfamiliar with either of these my use of the async library uses the next callback to call the next function which in this case would be to get the url for the iframe, and with our usage of the hapi framework AppServer.Wreck is roughy equivalent to request:
function prepareEnvelope(baseUrl, next) {
var createEntitlementTemplateId = "99C44F50-2C97-4074-896B-2454969CAEF7";
var getEnvelopeUrl = baseUrl + "/envelopes";
var options = {
headers: {
"X-DocuSign-Authentication": JSON.stringify(authHeader),
"Content-Type": "application/json",
"Accept": "application/json",
"Content-Disposition": "form-data"
},
body : JSON.stringify({
status: "sent",
emailSubject: "Test email subject",
emailBlurb: "My email blurb",
templateId: createEntitlementTemplateId,
templateRoles: [
{
email: "anemailaddress#gmail.com",
name: "Recipient Name",
roleName: "Signer1",
clientUserId: "1099", // TODO: replace with the user's id
tabs : {
textTabs : [
{
tabLabel : "acct_nmbr",
value : "123456"
},
{
tabLabel : "hm_phn_nmbr",
value : "8005882300"
},
{
tabLabel : "nm",
value : "Mr Foo Bar"
}
]
}
}
]
})
};
console.log("--------> options: ", options); // REMOVE THIS ====
AppServer.Wreck.post(getEnvelopeUrl, options, function(err, res, body) {
console.log("Request Envelope Result: \r\n", JSON.parse(body));
next(null, body, baseUrl);
});
}
And what I get back is:
{ errorCode: 'UNSPECIFIED_ERROR',
message: 'Non-static method requires a target.' }
From a little googling it look like 'Non-static method requires a target.' is a C# error and doesn't really give me much indication of what part of my configuration object is wrong.
I've tried a simpler version of this call stripping out all of the tabs and clientUserId and I get the same response.
I created my template on the Docusign website and I haven't ruled out that something is set up incorrectly there. I created a template, confirmed that Docusign noticed the named form fields, and created a 'placeholder' templateRole.
Here's the templateRole placeholder:
Here's one of the named fields that I want to populate and corresponding data label:
As a side note, I was able to get the basic vanilla example working without named fields nor using a template using the docusign node package just fine but I didn't see any way to use tabs with named form fields with the library and decided that I'd rather have more fine-grained control over what I'm doing anyway and so I opted for just hitting the APIs.
Surprisingly when I search SO for the errorCode and message I'm getting I could only find one post without a resolution :/
Of course any help will be greatly appreciated. Please don't hesitate to let me know if you need any additional information.
Once I received feedback from Docusign that my api call had an empty body it didn't take but a couple minutes for me to realize that the issue was my options object containing a body property rather than a payload property, as is done in the hapi framework.

Contentful API returning 'version mismatch' on entry update

I'm attempting to do the following with the Content Management API for Contentful:
Get an entry (entry1)
Find another entry (entry2) using data from a field in entry1
Update entry1 with data from entry2
My code looks like this:
client.getSpace("xxxxxxxx").then(function(space){
space.getEntries({
"content_type": "xxxxxxxx",
"sys.id": "2KEZYJOgDSeQMCQIE0Oo88",
"limit": 1
}).then(function(places){
//search for relevant category entry
space.getEntries({
"content_type": contentType.category,
"sys.id": places[0].fields.category["en-GB"],
"limit": 1
}).then(function(category){
//update place object
places[0].fields.categoryNew = {
"en-GB": [
{ sys: { type: "Link", linkType: "Entry", id: category[0].sys.id } }
]
};
//update place
request({
method: 'PUT',
url: 'https://api.contentful.com/spaces/xxxxxxxx/entries/' + places[0].sys.id,
headers: {
'Authorization': 'Bearer xxxxxxxx',
'Content-Type': 'application/vnd.contentful.management.v1+json',
'X-Contentful-Content-Type': 'xxxxxxxx'
},
body: JSON.stringify({fields:places[0].fields})
}, function (error, response, body) {
console.log(body);
});
});
});
});
Steps 1 and 2 work fine but the final step, updating the original entry, keeps returning the following error:
Response: {
"sys": {
"type": "Error",
"id": "VersionMismatch"
},
"requestId": "content-api:2PSSF6RtpSs2YyaaisK2wc"
}
How do I stop this happening? I've tried everything I can think of including manually updating the sys.version number, but when updating it seems to ignore any sys data I provide.
Refer to https://www.contentful.com/developers/docs/references/content-management-api/#/introduction/updating-and-version-locking
You need to pass the version as a header parameter called "X-Contentful-Version" with the PUT request.

Categories

Resources