Bizzare behaviour from Amazon SQS Javascript SDK (sendMessage) - javascript

I'm at the end of my rope here, so I'll keep it short and simple. Here's my code sample:
var message = JSON.stringify(value)
var url = process.env.SQS_URL + 'ts-notifications'
services.queue.sendMessage({
MessageAttributes: {
"responseId": {
DataType: 'String',
StringValue: responseIdentifier.toString('hex', true)
},
"surveyId": {
DataType: 'String',
StringValue: surveyIdentifier.toString('hex', true)
},
"itemId": {
DataType: 'String',
StringValue: key
}
},
MessageBody: message,
QueueUrl: url,
DelaySeconds: 0
}, function(err, data) {
if (err) {
cb(err)
} else {
cb()
}
})
Running this gets me this error:
{ [UnexpectedParameter: Unexpected key 'MessageAttributes' found in params]
message: 'Unexpected key \'MessageAttributes\' found in params',
code: 'UnexpectedParameter',
time: Sat Jan 07 2017 20:06:33 GMT+0000 (UTC) }
Here's a link to the AWS SQS Javascript SDK for sendMessage: http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SQS.html#sendMessage-property
It seems pretty clear to me that MessageAttributes is a valid parameter of sendMessage. I'm open to any and all suggestions, because this one is stumping me!
P.S., yes, I'm on the correct API version (there's only one anyway), and the variables above correspond to valid things higher up in the code.
Thanks all!

Related

Braintree Node.js cannot get transaction.sale to work

I am building a reactjs app that among others will include Braintree Dropin UI integration. So far, I have managed to make the UI show up and send a payload to the back end. However, I cannot get the gateway.transaction.sale() part to work. Here is my code's relevant parts:
When the user clicks the pay button, this is fired:
instance.requestPaymentMethod().then(function (payload) {
console.log(payload);
completePayment(amount, payload.nonce, userId, sessionId).then((result) => {
console.log( result );
});
}).catch(function (err) {
alert(err.message);
});
And this is the code that should handle the transaction:
return gateway.transaction.sale({
amount: amount,
paymentMethodNonce: nonce,
customFields: {
session_id: sessionId,
user_id: userId
},
options: {
submitForSettlement: true
}
}).then(function (result) {
if (result.success) {
console.log('Transaction ID: ' + result.transaction.id);
} else {
console.error(result.message);
}
}).catch(( error ) => {
alert(error);
});
Every time this function is fired, I get this error from catch:
TypeError: can't assign to property "success" on :not an object
Can anyone point me in the right direction?
Please note that I am not very familiar with react, node etc so my code may not be the best thing around...
Check these points:
make sure you assigned your environment to the sandbox (braintree.Environment.Sandbox);
double check (merchantId, publicKey, and privateKey).

How to execute `Rollup` request using `Xrm.WebApi.execute` method in MS CRM using JS

There is a nice example how Rollup function could be called via MS CRM WebApi here.
But it covers general access to CRM WebApi. Although in most recent versions new JS namespace Xrm.WebApi was introduced. Which provides more straightforward way to access that endpoint.
Method Xrm.WebApi.execute should be able to execute Rollup request, as it is able to execute WhoAmI. But I'm struggling to figure out correct values of parameters to make this execution happen.
Here is my code:
var RollupRequest = function(entityType, id, query) {
this.Target = { entityType: entityType, id: id };
this.RollupType = "Related";
this.Query = {
Query: query
};
};
RollupRequest.prototype.getMetadata = function() {
return {
boundParameter: null,
parameterTypes: {
Target: {
typeName: "Microsoft.Xrm.Sdk.EntityReference",
structuralProperty: 5
},
RollupType: {
typeName: "Microsoft.Dynamics.CRM.RollupType",
structuralProperty: 3
},
Query: {
typeName: "Microsoft.Xrm.Sdk.Query.FetchExpression",
structuralProperty: 5
}
},
operationType: 1, // This is a function. Use '0' for actions and '2' for CRUD
operationName: "Rollup"
};
};
var request = new RollupRequest(
"contact",
"0473FD41-C744-E911-A822-000D3A2AA2C5",
"<fetch><entity name='activitypointer'></entity></fetch>"
);
Xrm.WebApi.execute(request).then(
function(data) {
console.log("Success: ", data);
},
function(error) {
console.log("Failure: ", error);
}
);
The code generates following URL:
/api/data/v9.0/Rollup(Target=#Target,RollupType=#RollupType,Query=#Query)?#Target={"#odata.id":"contacts(0473FD41-C744-E911-A822-000D3A2AA2C5)"}&#RollupType=&#Query={"Query":"<fetch><entity name='activitypointer'></entity></fetch>"}
and the error: "Expression expected at position 0 in ''."
Which, seems to be, indicates that RollupType was not set correctly, because indeed in URL RollupType is missing.
I assume there are more than one potential error, because I'm using FetchXML as query expression. But meanwhile is it possible indicate what should be changed to generate proper URL at least for RollupType property?

Node.js - Google Calendar API showing error "Missing end time" when inserting an event

I am using Google Calendar library for Node.js to get calendar ID and events list from API. This is working as expected. But when I'm trying to insert or modify an event, I'm facing the common(!) error message "Missing end time".
I am trying to send a POST request using Request - Simplified HTTP client and not using Google Library or other package.
Here's my code snippet:
const request = require('request');
// Update Event Title
function insertEventIntoCalendar(calendarId,accessToken){
let endDateTime = {
dateTime: '2018-07-03T10:25:00.000-07:00',//end,
timeZone: 'Asia/Dhaka'
},
startDateTime = {
dateTime: '2018-07-03T10:00:00.000-07:00', //start,
timeZone: 'Asia/Dhaka'
},
url = "https://www.googleapis.com/calendar/v3/calendars/primary/events?access_token="+accessToken,
options = {
data: {
end: endDateTime,
start: startDateTime,
summery: 'ARG will win',
location: '800 Howard St., San Francisco, CA 94103',
attendees: [],
reminders: {
useDefault: true,
}
},
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + accessToken,
'Accept': 'application/json'
},
calendarId: 'primary'
}
request.post(url, options, function (err, res, body) {
console.log('err =>', err);
console.log('body =>', body);
})
}
And here is my console.log message:
err => null
body => {
"error": {
"errors": [
{
"domain": "global",
"reason": "required",
"message": "Missing end time."
}
],
"code": 400,
"message": "Missing end time."
}
}
Note: I've followed all questions and answers related to Google Calendar API and Node.js and still facing the same error. And I've not found any answers where Google Library is not used.
Please share your thoughts if you tried this way, otherwise you can suggest me a better way where I don't need any Config file to get or modify Google Calendar info.
The problem is in declaring the options variable. The documentation of Request - Simplified HTTP client is saying the json data of Request body should be named as 'json'. So the options variable should be,
options = {
url: url
json: {
end: endDateTime,
start: startDateTime,
summery: 'ARG will win',
location: '800 Howard St., San Francisco, CA 94103',
attendees: [],
reminders: {
useDefault: true,
}
}
}
and to send the POST request, the code should be:
request.post(options,function (err, res, body) {
console.log('err =>', err);
// console.log("res =>", res);
console.log("body =>", body);
})
I tried this way and it works :)
bonnopc answer solved it for me. For the people getting here searching for node js + Google Calendar API error, this also works there:
auth.getClient().then(a => {
calendar.events.patch({
json: {
summary: "bablabbla",
start: JSON.stringify(new Date()),
end: JSON.stringify(new Date())
},
auth: a,
calendarId: GOOGLE_CALENDAR_ID,
eventId: changedEvent.id
})
})

JS AWS SDK - copyObject SignatureDoesNotMatch error

I have an application using Node and the AWS-SDK package. I am copying objects from one bucket to another using the copyObject method. I'm getting an error that says SignatureDoesNotMatch: The request signature we calculated does not match the signature you provided. Check your key and signing method.
I've been able to successfully run the code on my local machine and it copies the files from one bucket to another. The error occurs on our AWS server, which I deployed the application to. The full error is:
{ [SignatureDoesNotMatch: The request signature we calculated does not
match the signature you provided. Check your key and signing method.]
message: 'The request signature we calculated does not match the signature you provided. Check your key and signing method.',
code: 'SignatureDoesNotMatch',
region: null,
time: Mon Jul 11 2016 12:11:36 GMT-0400 (EDT),
requestId: <requestId>,
extendedRequestId: <extendedRequestId>,
cfId: undefined,
statusCode: 403,
retryable: false,
retryDelay: 66.48076744750142 }
Also, I'm able to perform the listObjects command. The error is only happening on copyObject.
So far, I've tried
setting correctClockSkew to true
checked the servers time (same as local computer)
checked the key/secret (loading from a config file and is working locally)
checked the file names (there are no strange characters. Alphanumeric, '.', '-' and '/')
Here is the code causing the problem:
AWS.config.update({
accessKeyId: <accessKeyId>,
secretAccessKey: <secretAccessKey>,
correctClockSkew: true
});
var s3 = new AWS.S3();
var params = {
Bucket: <bucket>,
Prefix: <prefix>
};
s3.listObjects(params, function(err, data) {
if (data.Contents.length) {
async.each(data.Contents, function(file, cb) {
var file_name = file.Key.substr(file.Key.indexOf('/')+1);
var copy_params = {
Bucket: <bucket2>,
CopySource: <bucket> + '/' + file.Key,
Key: file_name,
ACL: 'public-read'
};
s3.copyObject(copy_params, function(copyErr, copyData){
if (copyErr) {
console.log('Error:', copyErr);
}
else {
cb();
}
});
}, function(err){
...
}
});
} else {
...
}
});
Not sure if you've found a solution to this or not, but this was an issue raised on github and the solution seems to simply URL encode your CopySource parameter with encodeURI():
https://github.com/aws/aws-sdk-js/issues/1949

REST API testing using vows, tobi and node.js

I am trying to combine the examples here, here to write a vows test for my node.js / express app that:
Creates a new user object
Checks the response was sane
Uses the returned _id to test looking up the newly created user
Again uses the _id to test updating the user
Item 1 and 2 work fine, but there is something wrong with my sub-context 'GET /users/:id'. It errors and I cannot figure out why. Tried Googling and using the debugger, but I still can't see what it is, I am probably just overlooking something obvious.
···✗ Errored » 3 honored ∙ 1 errored
Can anyone tell me why the 4th vow errors?
Here's my vows code:
var vows = require('vows')
, assert = require('assert')
, tobi = require('tobi')
var suite = vows.describe('Users API')
, now = new Date().getTime()
, newUser = { name: now + '_test_user', email: now + '#test.com' }
, browser = tobi.createBrowser(3000, 'localhost')
, defaultHeaders = { 'Content-Type': 'application/json' }
function assertStatus(code) {
return function (res, $) {
res.should.have.status(code)
}
}
var client = {
get: function(path) {
return function() {
browser.get(path, { headers: defaultHeaders }, this.callback)
}
},
post: function(path, data) {
return function() {
browser.post(path, { body: JSON.stringify(data), headers: defaultHeaders }, this.callback)
}
}
}
suite.addBatch({
'GET /users': {
topic: client.get('/users'),
'should respond with a 200 ok': assertStatus(200)
},
'POST /users': {
topic: client.post('/users', newUser),
'should respond with a 200 ok': assertStatus(200),
'should return the new user': function(res, $){
assert.isNotNull(res.body._id)
assert.isNotNull(res.body.created_at)
assert.isTrue(res.body._id.length > 0)
assert.equal(newUser.name, res.body.name)
assert.equal(newUser.email, res.body.email)
},
'GET /users/:id': { // Sub-context of POST /users
topic: function(res) { return client.get('/users/' + res.body._id) },
'should respond with a 200 ok': assertStatus(200)
}
}
})
suite.export(module)
EDIT
I tried simplifying the code as follows to help see if this.callback was the problem, but the error is still there:
'GET /users/:id': { // Sub-context of POST /users
topic: function(res) {
console.log('About to request /users/' + res.body._id)
browser.get('/users/' + res.body._id, { headers: defaultHeaders }, this.callback)
},
'should respond with a 200 ok': assertStatus(200)
}
How are you populating res for the fourth tes?? It wouldn't be visible outside the line
'should return the new user'
Try creating the id variable outside the addBatch call, and set it in the third test. then call
client.get('/users/' + id)
EDIT:
Better yet, put it back into newUser in the third test:
'should return the new user': function(res, $){
newUser.id = res.body._id
....
and then do:
client.get('/users/' + newUser.id)

Categories