The correct way to use new DocumentClient() - amazon-web-services

I see the following error occasionally in my ec2 instance that uses DynamoDB heavily
{ message: 'Could not load credentials from any providers',
code: 'CredentialsError',
errno: 'ECONNREFUSED',
syscall: 'connect',
address: '169.254.169.254',
port: 80,
time: 2018-07-05T10:02:37.690Z,
originalError:
{ code: 'ECONNREFUSED',
errno: 'ECONNREFUSED',
syscall: 'connect',
address: '169.254.169.254',
port: 80,
message: 'connect ECONNREFUSED 169.254.169.254:80' } } }
The way I am using the AWS sdk to connect and get data from DynamoDB is like the following
'use strict'
const BluebirdPromise = require('bluebird')
AWS.config.setPromisesDependency(BluebirdPromise)
const DocumentClient = AWS.DynamoDB.DocumentClient
class DynamoOne {
get({
key
}) {
return new DocumentClient().get({ // creating new instance every time i want to get Item
Key: key,
TableName: 'TABLE_NAME',
ConsistentRead: consistent,
})
.promise()
.catch(e => console.trace(key, e))
}
}
new DynamoOne.get({
id: 1
}).then((item) => {
console.log(1, item)
})
Is this the correct way to use it ? or I should create new DocumentClient() once and use it all over , like the following code
'use strict'
const BluebirdPromise = require('bluebird')
AWS.config.setPromisesDependency(BluebirdPromise)
const DocumentClient = new AWS.DynamoDB.DocumentClient() // creating new instance once
class DynamoTwo {
get({
key
}) {
return DocumentClient.get({ // reuse DocumentClient
Key: key,
TableName: 'TABLE_NAME',
ConsistentRead: consistent,
})
.promise()
.catch(e => console.trace(key, e))
}
}
new DynamoTwo.get({
id: 1
}).then((item) => {
console.log(1, item)
})
Which one is the correct one DynamoOne or DynamoTwo ?

After researching and asking in github aws repo
I found that the correct way is to use DynamoTwo

Related

Nestjs credential issue with Amazon SQS queue

I am trying to publish a message from my nestjs application to an amazon sqs queue.
Here is a snippet of a simple post request, and i am using the package from aws-sdk:
import * as aws from 'aws-sdk';
--
--
--
--
--
#Post('dummySqs')
async sendMessage(#Body() message: string) {
const config = {
apiVersion: '2022-02-21',
accessKeyId: 'myaccess',
accessSecretKey: 'mysecret',
region: 'us-east-1',
output: 'json',
};
aws.config.update(config);
const sqs = new aws.SQS();
const params = {
MessageBody: 'Something about Daniel',
QueueUrl: 'myurl',
};
sqs.sendMessage(params, (err, data) => {
if (err) {
console.log('ERRROR', err);
} else {
console.log('Success', data.MessageId);
}
});
}
After hitting this post request, i am getting the error below:
ERRROR Error [CredentialsError]: Missing credentials in config, if using AWS_CONFIG_FILE, set AWS_SDK_LOAD_CONFIG=1
at Timeout.connectTimeout [as _onTimeout] (/Users/danielongzh/Documents/poc/schedule-distributed-lock-service/node_modules/aws-sdk/lib/http/node.js:69:15)
at listOnTimeout (internal/timers.js:555:17)
at processTimers (internal/timers.js:498:7) {
code: 'CredentialsError',
time: 2022-02-21T13:31:40.708Z,
retryable: true,
originalError: {
message: 'Could not load credentials from any providers',
code: 'CredentialsError',
time: 2022-02-21T13:31:40.707Z,
retryable: true,
originalError: {
message: 'EC2 Metadata roleName request returned error',
code: 'TimeoutError',
time: 2022-02-21T13:31:40.707Z,
retryable: true,
originalError: [Object]
}
}
}
Any ideas on how to solve it?
Try this:
import * as aws from 'aws-sdk';
import config from '../aws.json'
as.config.update(config);
or
this.athena = new Athena({
region: this.configService.get<IAwsCredentials>('AWS_ATHENA').AWS_REGION,
accessKeyId: this.configService.get<IAwsCredentials>('AWS_ATHENA').AWS_ACCESS_KEY,
secretAccessKey: this.configService.get<IAwsCredentials>('AWS_ATHENA').AWS_SECRET_KEY,
});

AWS - Cannot read "domainName" of undefined

[EDIT]
I am new to AWS and I've been trying to make a real-time chat application. I saw this code, so I might as well try this. I tried to follow everything but it seems there is a problem.
[END]
I got an error with this code stating, Cannot read "domainName" of undefined which got me confused. Is this because of my API Gateway? I already connected this to another route named "Message" and I already have the integration request of my connect and disconnect.
Below is my code:
const AWS = require('aws-sdk');
const db = new AWS.DynamoDB.DocumentClient({region: 'us-east-1'});
require('./index.js');
let send = undefined;
function init(event) {
console.log(event);
const apigwManagementApi = new AWS.ApiGatewayManagementApi({
apiVersion: '2018-11-29',
endpoint: event.requestContext.domainName + '/' + event.requestContext.stage
});
send = async (connectionId, data) => {
await apigwManagementApi.postToConnection({
ConnectionId: connectionId,
Data: `Echo: ${data}` }).promise();
}}
exports.handler = (event, context, callback) => {
init(event);
let message = JSON.parse(event.body).message;
getConnections().then((data) => {
console.log(data.Items);
callback(null, {
statusCode: 200,
});
data.Items.forEach(function(connection) {
console.log("Connection " +connection.connection_id);
send(connection.connection_id, message);
});
});
return {};
};
function getConnections(){
const params = {
TableName: 'GroupChat',
}
return db.scan(params).promise();
}

Querying with apollo-link-state gives the error "Field <name> doesn't exist on type 'Query'"

I'm totally new to both Apollo and GraphQL. I'm following along with this apollo-link-state-tutorial, and am hitting a stumbling block.
I have set up my link with a currentGame property default.
const stateLink = withClientState({
cache: stateCache,
defaults: {
currentGame: {
__typename: 'currentGame',
teamAScore: 0
}
}
})
I'm using it in my client.
const client = new ApolloClient({
stateCache,
link: stateLink,
...
})
I'm defining a GraphQL query like this:
const getCurrentGame = gql`
query {
currentGame #client {
teamAScore
}
}
`
I am connecting it to my component's props.
export default compose(
graphql(getCurrentGame, {
props: ({ data: { currentGame }}) => ({
currentGame
})
})
)
This generates an error in the console.
[GraphQL error]: Message: Field 'currentGame' doesn't exist on type 'Query', Location: [object Object], Path: undefined
I've gone over my code and haven't been able to spot what is surely a typo or simple mistake. How can I debug this error message, or what does it suggest the problem is?
Update: I have tried adding a resolver as suggested by Tal Z, but am still receiving the same error message.
const stateCache = new InMemoryCache()
const stateLink = withClientState({
cache: stateCache,
resolvers: {
Query: {
currentGame: () => {
return {}
}
}
},
defaults: defaultState
})
For what it's worth, most of the few example repositories I've found have queries for fields that do not have resolvers defined. For example, this queries for todo list items, but the only resolver defined is for a mutation.
Well, I figured it out... this breaks:
import ApolloClient from 'apollo-boost'
This works:
import ApolloClient from 'apollo-client'
I have no idea what the difference is.

Parse Server - Missing Push Configuration?

I've been trying to get push notifications to work with my Parse application. I tried to do so my adding the below code into my Parse server.js file but my server does not start up again when this code is contained inside of the file. I have my p12 file available and linked in the code below (on my actual sever) as well so Im not sure what the issue is.
push: {
android: {
senderId: '...',
apiKey: '...'
},
ios: {
pfx: '/file/path/to/XXX.p12',
passphrase: '', // optional password to your p12/PFX
bundleId: '',
production: false
}
}
My server is running on an Amazon EC2 instance as well.
Are you using AWS SNS to use push notification? If so, you can try setting this in your server code:
function sendPhoneNotification() {
AWS = require('aws-sdk');
AWS.config.update({
accessKeyId: '***',
secretAccessKey: '***',
region: 'ap-southeast-1'
});
var sns = new AWS.SNS();
var promise = new Parse.Promise();
sns.createPlatformEndpoint({
PlatformApplicationArn: '***',
Token: "***"
}, function (err, data) {
if (err) {
console.log("Error in endpoint" + err.stack);
//res.error("error stack 1: " + err.stack);
promise.reject(err.stack);
return promise;
}
var endpointArn = data.EndpointArn;
var payload = {
GCM: {
data: {
title: "YOUR TITLE",
message: "HELLO PUSH NOTIFICATION"
}
}
/* APNS: {
aps: {
alert: 'Hello World',
sound: 'default',
badge: 1
}
}*/
};
// payload.APNS = JSON.stringify(payload.APNS);
payload.GCM = JSON.stringify(payload.GCM);
payload = JSON.stringify(payload);
var result = sns.publish({
Message: payload,
MessageStructure: 'json',
TargetArn: endpointArn
}, function (err, data) {
if (err) {
promise.reject(err.stack);
return promise;
}
res.success("push sent " + JSON.stringify(data));
});
});
return promise;
}

AWS S3 promise meteor

So, I'm using AWS = Npm.require('aws-sdk'); from Amazon.
Apparently promise are implemented. http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Request.html#promise-property
See my functions (Server):
s3 = new AWS.S3({ apiVersion: "2006-03-01" });
bucketExists = (bucket) => {
check(bucket, String);
const params = {
Bucket: bucket
};
return s3.putObject({Bucket: 'bucket', Key: 'key'}).promise();
};
Meteor.methods({
addPhoto(userId, photo) {
check(userId, String);
check(photo, Object);
bucketExists(userId)
.then(
function(value) {
console.log("Contents: " + value);
})
.catch(function(reason) {
console.error("Error or timeout", reason);
});
}
});
Exeption:
Exception while invoking method 'addPhoto' TypeError: Object [object Object] has no method 'promise'.
WTF
So, I try without call promise(). Like that:
bucketExists = (bucket) => {
check(bucket, String);
const params = {
Bucket: bucket
};
return new Promise(
(resolve, reject) => {
s3.waitFor('bucketExists', params, (err, res) => {
if (err) reject(err);
else resolve(res);
});
});
};
But nothing appear. I start with ES6. So please help.
Thanks