Unable to use AWS JS SDK V3 to list all tables - amazon-dynamodb

I am following the AWS SDK v3 for Javascript guide to display my DynamoDb table names.
https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/welcome.html
However, I am receiving the following error. Any help in understanding why I am receiving this error would be greatly appreciated! :-)
TypeError: Cannot read properties of undefined (reading 'ExclusiveStartTableName')
at serializeAws_json1_0ListTablesInput (C:\source\training\react\portfolio-app\finance_api\node_modules\#aws-sdk\client-dynamodb\dist-cjs\protocols\Aws_json1_0.js:3833:19)
at serializeAws_json1_0ListTablesCommand (C:\source\training\react\portfolio-app\finance_api\node_modules\#aws-sdk\client-dynamodb\dist-cjs\protocols\Aws_json1_0.js:357:27)
at serialize (C:\source\training\react\portfolio-app\finance_api\node_modules\#aws-sdk\client-dynamodb\dist-cjs\commands\ListTablesCommand.js:40:72)
at C:\source\training\react\portfolio-app\finance_api\node_modules\#aws-sdk\middleware-serde\dist-cjs\serializerMiddleware.js:12:27
at C:\source\training\react\portfolio-app\finance_api\node_modules\#aws-sdk\middleware-endpoint\dist-cjs\endpointMiddleware.js:20:16
at async C:\source\training\react\portfolio-app\finance_api\node_modules\#aws-sdk\middleware-logger\dist-cjs\loggerMiddleware.js:5:22
at async listTables (file:///C:/source/training/react/portfolio-app/finance_api/src/helper/listAWSTable.js:6:21)
at async file:///C:/source/training/react/portfolio-app/finance_api/src/helper/runAWSCommands.js:4:1
Here are the contents of the javascript file I am using to extract the list of tables, it's basically copied from the developer-guide.
NB I have substituted in my region and I have AWS credentials loaded in my VSCode.
listAWSTables.js
import { DynamoDBClient, ListTablesCommand } from "#aws-sdk/client-dynamodb";
async function listTables() {
const dbclient = new DynamoDBClient({ region: "ap-southeast-2" });
try {
const results = await dbclient.send(new ListTablesCommand());
results.Tables.forEach(function (item, index) {
console.log(item.Name);
});
} catch (err) {
console.error(err);
}
}
export { listTables };
I call it from another file "runAWSCommands.js":
runAWSCommands.js
import { listTables } from "./listAWSTables.js";
await listTables();
At the commandline I start it off using this command: node runAWSCommands.js

The error:
TypeError: Cannot read properties of undefined (reading 'ExclusiveStartTableName')
It is saying: "The ListTablesCommand cannot read a property from an input that is undefined"
If we look at the definition type of ListTablesCommand:
It expects an input value. If we look at the documentation, we can also see an input variable there.
This input object can be empty, in case you don't want to pass any configuration.
Hence, you can change the line:
const results = await dbclient.send(new ListTablesCommand());
to:
const results = await dbclient.send(new ListTablesCommand({}));
And it should work as expected.

Related

Unable to use array's method "find" in Vue 3

I am trying to get current location of a user and then push it into array. Before I do so, I check whether a city with the same name is already there. In that case, I won't push it into the array. However, when I am trying to check it, it says: Uncaught (in promise) TypeError: Cannot read properties of null (reading 'find').
const found = ref(false);
const weatherResponse = ref([]);
function getLocation() {
console.log("SETTING LOCATION");
navigator.geolocation.getCurrentPosition((position) => {
console.log(`Lat: ${position.coords.latitude}, Lon: ${position.coords.longitude}`);
if (position.coords.latitude && position.coords.longitude) {
axios.get(`https://api.weatherapi.com/v1/current.json?key=${API_KEY}&q=${Math.round(position.coords.latitude)},${Math.round(position.coords.longitude)}&aqi=no`)
.then((response) => {
found.value = weatherResponse.value.find((item) => item.location.name == response.data.location.name);
if (response.data?.error?.code != 1006 && !found.value) {
weatherResponse.value.push(response.data);
this.$store.commit("addToList", response.data);
console.log(weatherResponse.value);
}
})
}
},
(error) => {
console.log(error.message);
}
)
}
I've already tried using fetch, axios to grab the API, but the "find()" method is still not working. Regarding "found" variable, I tried using it in ref as well as declaring it as "let found".
After trying and testing, I've finally managed to get everything to work. My issue was in (weirdly) main.js. Because it was set out like this: createApp(App).use(cors, store).mount('#app') it, I guess, caused VueX.store not to load in properly because mounted hook was called and it was throwing all sorts of mistakes. Putting it like const app = createApp(App); app.use(store); app.use(cors); app.mount("#app"); actually made it work.

Cannot read properties of undefined (reading '_hex') Next js buyNft

so I am building an nft marketplace and everything is good with creating nft .. etc but when attempting to buy an nft I get this error :
ethers.umd.js?e6ac:4395 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading '_hex')
Here is the code snippet:
const buyNft = async (nft) => {
const web3Modal = new Web3Modal();
const connection = await web3Modal.connect();
const provider = new ethers.providers.Web3Provider(connection);
const signer = provider.getSigner();
const contract = new ethers.Contract(
MarketAddress,
MarketAddressABI,
signer
);
const price = ethers.utils.parseUnits(nft.price.toString(), "ether")
console.log(price)
// code stops here
const transaction = await contract.createMarketSale(nft.tokenId, {
value: price,
});
await transaction.wait();
};
when debugging seems that the code stops before the transaction constant.
when console .log the price I get this:
I tried to remove the toString method, also tried to spread the price object in transaction variable like this value:{...price} but still didn't work
The createMarketSale() first agument expects a BigNumber instance (or a stringified number that it would convert to BigNumber).
When you pass it undefined, it throws the error mentioned in your question.
Solution: Make sure that your nft.tokenId is either a BigNumber or string - not undefined.

How do I make a firestore query to be used with both get() and valueChanges()?

I am using Angular 8 and have a form where a user can choose what he wants to query the database for and then click either of two buttons - one to view data in realtime on the website, and the other to download the data.
I thought I could make use of one function to make a query and then call different functions depending on what button the user clicked, using get() for the download and valueChanges() for the realtime data view. But when I try this, I get the following errors in the browser console. (This is with query as type any - if I specify the type as AngularFirestoreCollection I get errors regarding my type for the get() part in VSCode)
ERROR Error: "Uncaught (in promise): TypeError: this.query.get is not
a function
I can add that I previously had two completely separate (working) functions for downloading and viewing in realtime. And for downloading I used the below query. I gather this is actually a Firestore Query, whereas the "query" I'm trying to use in my updated code is an AngularFirestoreCollection. But is there a way I can make some kind of Query/Collection that will work for both get() and valueChanges()?
Old (working) query:
var query = this.afs.collection(collection).ref.where('module', 'in', array_part);
Trying a common function makeQuery():
onSubmit(value, buttonType): void {
if (buttonType=='realtime') {
this.getRealTimeData(value);
}
if (buttonType=='download') {
this.downloadCsv(value);
}
}
async downloadCsv(value) {
this.query = this.makeQuery(value);
this.dataForDownload = await this.getDataForDownload();
this.dataForDownload = JSON.stringify(this.dataForDownload['data']);
console.log('Data: ', this.dataForDownload);
var date = new Date();
var date_str = this.datePipe.transform(date, 'yyyy-MM-ddTHH-mm');
this.makeFileService.downloadFile(this.dataForDownload, 'OPdata-' + date_str);
}
getDataForDownload() {
return this.query.get()
.then(function (querySnapshot) {
var jsonStr = '{"data":[]}';
var dataObj = JSON.parse(jsonStr); //making object we can push to
querySnapshot.forEach(function (doc) {
JSON.stringify(doc.data()), ', id: ', doc.id);
dataObj['data'].push(doc.data());
});
return dataObj;
})
.catch(function (error) {
console.log("Error getting documents: ", error);
});
}
async getRealTimeData(value) {
this.query = await this.makeQuery(value);
this.data = this.query.valueChanges();
}
async makeQuery(value) {
var collection: string;
return this.query = this.afs.collection<DataItem>('CollectionName', ref => ref.where('datetime', '>=', '2020-01-15T09:51:00.000Z').orderBy('datetime', 'desc').limit(100));
}
The valueChanges() is a method used in angularfire to retrieve data from firestore, while the get() method is used to retrieve from firestore but using the vanilla javascript.
Mixing both methods will return an error as you have seen in your code. Therefore, since angularfire was created above the javascript firebase code, then you should be able to use valueChanges() to view data in realtime on the website, and to download the data.

How to make Polymer 2.x Function async

I am trying to use the Shape Detection API (https://developers.google.com/web/updates/2019/01/shape-detection) and am getting an error:
Uncaught SyntaxError: await is only valid in async function
After going through the Polymer 2.x docs (https://polymer-library.polymer-project.org/2.0/api/namespaces/Polymer.Async) I get the following:
ready() {
super.ready();
this.initImageDetection();
}
initImageDetection() {
const barcodeDetector = new BarcodeDetector({
formats: [
'code_128'
]
});
try {
const barcodes = await barcodeDetector.detect(image);
barcodes.forEach(barcode => console.log(barcode));
} catch (e) {
console.error('Barcode detection failed:', e);
}
}
This pattern also failed with the same error:
this.async(() => {
const barcodes = await barcodeDetector.detect(image)
barcodes.forEach(barcode => console.log(barcode)
)});
Also, running initImageDetection prefixed with async and running from a paper-button after the DOM is loaded.
async initImageDetection() {
...
}
I get the following error:
Uncaught (in promise) ReferenceError: BarcodeDetector is not defined
How do I properly make a function async in Polymer 2.x?
How can I instantiate BarcodeDetector in Polymer 2.x?
async functionName() {
// function code here
}
Is the proper way to set async functions in Polymer. However, the BarcodeDetector object is hidden behind a flag in Chrome, so must be enabled in chrome://flags Experimental Web Platform features before using.

Angular Firestore document update causing infinite loop in subscription

I understand the issue but can't figure out the workaround. I am querying a specific document to extract an array of token strings. I need to append a new token to the end of this string and then update the current document with this new token array.
To do this, I have subscribed to a query and within, I update that document. But of course, when you update the same object, the subscription runs again thus creating an infinite loop. I tried incorporating a take(1) pipe rxjs operator but that did not change anything. Any suggestions?
Here's my code:
this.afs.collection('users').doc(user.userUID).valueChanges().pipe(take(1)).subscribe((user: userModel) => {
const currentTokens: string[] = user.notifTokens ? user.notifTokens : [];
//token variable is provided outside this query
currentTokens.push(token);
//this next lines causes the subscription to trigger again
userRef.doc(user.userUID).update({notifTokens: currentTokens})
})
I would recommend you avoid using a subscription in this situation, for exactly this reason. I realize the Angularfire2 docs don't list this method, but the base Firebase package includes a .get() method... and while the AF2 docs don't mention the .get() method... the source code shows that it is supported.
Try something like:
this.afs.collection('users').doc(user.userUID).get().then( (user: userModel) => {
if (user.exists) {
console.log("Document data:", user.data());
// Do stuff with the info you get back here
const currentTokens: string[] = user.data().notifTokens ? user.data().notifTokens : [];
currentTokens.push(token);
userRef.doc(user.data().userUID).update({notifTokens: currentTokens})
} else {
// user.data() will be undefined in this case
console.log("No such document!");
}
}).catch(function(error) {
console.log("Error getting document:", error);
});

Resources