AWS Amplify Storage.put() Cannot read properties of undefined (reading 'byteLength') - javascript

I created an amplify react native app and attached a S3 Bucket manually, when I called the function "Storage.put()" it displayed this error.
This is my code.
Auth Configuration

Add await for Storage.put():
let data = await Storage.put('cheque/cheque_1', blob)

Related

import or require not working on aws lamda

I am writing a lambda function on aws. I want to send user data after they signup to my mongodb database. I triggered the lambda function using "pre authenticate" method. however, "I am getting this error " preauthentication failed with error cannot find package 'aws-sdk' imported from /var/task/index.mjs. "
my lambda function code:
import AWS from 'aws-sdk'
import {MongoClient} from 'mongodb'
exports.handler = async (event) => {
try{
// Retrieve the user data from the event object
const userData = event.request.userAttributes;
// Connect to the MongoDB database
const client = await MongoClient.connect("database url", {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const db = client.db("Cluster0");
const collection = db.collection("users");
// Insert the user data into the collection
await collection.insertOne(userData);
// Close the database connection
client.close();
}catch(error){
callback(error, event)
}
};
my question is do I have to install mongodb and aws sdk on lambda function folder?
I am writing lambda function from aws website.
cannot find package 'aws-sdk' imported from /var/task/index.mjs
This error is usually caused by using the SDK V2 import statements while using a Lambda runtime which uses SDK V3.
I am guessing you are using the new node runtime 18 on Lambda. This runtime uses the Node SDK V3 which supports modular imports like so:
const { S3Client } = require("#aws-sdk/client-s3");
You can either change to a lower runtime or change your code to suit the Node V3 SDK imports:
https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/#modularized-packages
I also don't believe Lambda runtimes have the MongoDB client built in, which means you will need to create the package locally or use a Lambda Layer
https://www.mongodb.com/developer/products/atlas/serverless-development-lambda-atlas/
If you are not tied down to MongoDB, you can use DynamoDB which has a built in client for the Lambda runtime.

Uncaught SyntaxError: The requested module does not provide an export named 'fs'

I'm not good with javascript. I'm trying to upload a few files to nft.storage as a folder by modifying this example -> https://github.com/nftstorage/nft.storage/blob/main/packages/client/examples/node.js/storeDirectory.js
Instead of uploading via a form, my files are stored in my PC file system. Below is my js code.
<script type="module">
import { NFTStorage, File } from 'https://cdn.skypack.dev/nft.storage'
import { fs } from 'https://cdn.skypack.dev/fs-'
const endpoint = 'https://api.nft.storage' // the default
const token = 'RDA0NjI0MTIzMTA2Mzgy....' // your API key from https://nft.storage/manage
function log(msg) {
msg = JSON.stringify(msg, null, 2)
document.getElementById('out').innerHTML += `${msg}\n`
}
document.querySelector('#upload-file-ipfs').addEventListener('click', async (e) => {
e.preventDefault()
const storage = new NFTStorage({ endpoint, token })
const cid = await storage.storeDirectory([
new File([await fs.promises.readFile('metadata.json')], 'metadata.json'),
new File([await fs.promises.readFile('test.png')], 'test.png'),
])
console.log({ cid })
const status = await storage.status(cid)
console.log(status)
})
</script>
But I keep getting this error below.
Uncaught SyntaxError: The requested module 'https://cdn.skypack.dev/fs-' does not provide an export named 'fs'
I tried replacing 'https://cdn.skypack.dev/fs-' with 'https://www.skypack.dev/view/fs-extra' and ''https://cdn.skypack.dev/graceful-fs' and it gives me the same error.
If I remove the curly braces around 'fs', I get Uncaught Error: [Package Error] "fs" does not exist. (Imported by "fs-").
Any help is highly appreciated. My application is PHP+ JS, not node.js.
It should be without curly braces, as shown in the docs for fs-, but the second error tells you the next problem: You are trying to use a package in the browser which is designed for node.js. (Browsers don't have a native fs module.) Use it in your backend node.js application, not the frontend.
Since you seem to be trying to use this in a browser, probably you shouldn't use the node.js example that you linked (nft.storage/packages/client/examples/node.js/storeDirectory.js) but rather the browser example: https://github.com/nftstorage/nft.storage/blob/main/packages/client/examples/browser
Remember however that a script in a browser can't just read random files from the user's file system. The user has to upload the file in a form (or give access to a certain directory using the browser file system APIs, but that's experimental).

Google sheets API JavaScript: Access sheet with auth

I'm able to access a public google sheet from within my react app but am now trying access the sheet with credentials. I found a tutorial that walks me thru setting up credentials but the code isn't working for me.
const {google} = require('googleapis');
const keys = require('./interstitials-key.json');
const client = new google.auth.JWT(
keys.client_email,
null,
key.private_key,
['https://www.googleapis.com/auth/spreadsheets']
);
client.authorize(function(err, tokens){
if(err){
console.log(err);
return;
}
else{
console.log('connected');
}
});
I'm getting this error:
"TypeError: Expected input to be a Function or Object, got undefined"
This is a known issue, you'll find reference over here:
https://github.com/googleapis/google-api-nodejs-client/issues/1614
I've reproduced it, certainly it's not fixed, you'll face this error as soon as you call the library
const {google} = require('googleapis');
Some of the resources used on the library are not available on the client side, so, it's not possible to call it from the React side, so you either use it on the server side or you have to use the google javascript client api.

Google Cloud Function/google-auth-library: Cannot read property 'user' of undefined

Following this: https://medium.com/#nedavniat/how-to-perform-and-schedule-firestore-backups-with-google-cloud-platform-and-nodejs-be44bbcd64ae
Code is:
const functions = require('firebase-functions'); // is installed automatically when you init the project
const { auth } = require('google-auth-library'); // is used to authenticate your request
async function exportDB () {
const admin = await auth.getClient({
scopes: [ // scopes required to make a request
'https://www.googleapis.com/auth/datastore',
'https://www.googleapis.com/auth/cloud-platform'
]
});
const projectId = await auth.getProjectId();
const url = `https://firestore.googleapis.com/v1beta1/projects/${projectId}/databases/(default):exportDocuments`;
return admin.request({
url,
method: 'post',
data: {
outputUriPrefix: 'gs://name-of-the-bucket-you-created-for-backups'
}
});
}
const backup = functions.pubsub.topic('YOUR_TOPIC_NAME_HERE').onPublish(exportDB);
module.exports = { backup };
When I go to deploy via:
gcloud functions deploy backup --runtime nodejs8 --trigger-topic YOUR_TOPIC_NAME_HERE
I get error:
ERROR: (gcloud.functions.deploy) OperationError: code=3,
message=Function failed on loading user code. Error message: Code in
file index.js can't be loaded. Is there a syntax error in your code?
Detailed stack trace: TypeError: Cannot read property 'user' of
undefined
Is this something with google-auth-library?
I assume that you are trying to deploy GCF function triggered by HTTP request, I suggest you to check this link[1] seems is the same use case and can help you to use Google Cloud Datastore with node.js on GCF
[1] How to return an entire Datastore table by name using Node.js on a Google Cloud Function

Google Drive API Error Daily Limit for Unauthenticated Use Exceeded

Im getting error on using Google API.
having right to connect with Google Drive and add new sheet and insert data into it.
It was working till yesterday but when i run the application today.
Im getting error :
Error appears after users given token and tried to access the DRIVE API to get all the files
domain: "usageLimits"
extendedHelp: "https://code.google.com/apis/console"
message: "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup."
reason: "dailyLimitExceededUnreg"
I have not changed any settings.
Following API are enables for my application access token. Do i have to add / enable more API to make it work.
I was using NodeJS to download a file, but was forgetting to pass the auth.
Initially I was using:
function downloadFiles() {
const service = google.drive('v3');
const dest = fs.createWriteStream('/tmp/foo.csv');
const fileId = '12345_ID_GOES_HERE';
service.files.export({
fileId: fileId,
mimeType: 'text/csv'
});
}
afterwards, I added an auth argument to the function, and passed it to the export method as well:
function downloadFiles(auth) {
const service = google.drive('v3');
const dest = fs.createWriteStream('/tmp/foo.csv');
const fileId = '12345_ID_GOES_HERE';
service.files.export({
auth: auth,
fileId: fileId,
mimeType: 'text/csv'
})
}
I am getting auth by creating an instance of google-auth-library
The problem was while getting access token. I was not providing correct scopes.
When i changed the scope to
https://spreadsheets.google.com/feeds https://docs.google.com/feeds
https://www.googleapis.com/auth/drive.file
it worked fine

Categories

Resources