I've got a React app that needs to call the AWS S3 API a couple times. Login for my app uses Cognito, set up via Amplify. It's all working fine, but I'm trying to clean up some code and am struggling with the right way to structure the code.
What I am currently doing is importing Auth
from aws-amplify
, as well as AWS
from the aws-sdk
.
This doesn't seem right, but it is the way I've solved it.. but essentially I had to create an async function to get the credentials in a format that works for the AWS SDK. That function looks like this:
const getCreds = async () => {
let curCred = await Auth.currentCredentials()
return Auth.essentialCredentials(curCred)
}
In a useEffect hook when the page loads, I am downloading a JSON file from S3. In order to do so, I have to do this:
const creds = await getCreds()
const myS3 = new AWS.S3({ credentials: creds })
const content = JSON.parse(await myS3.getObject({config}).promise()).Body.toSting('utf-8')
//process content...
I have similar code in other parts of the app to do things like myS3.putObject
or myS3.getSignedURL
etc. But each time I need to get new creds and create a new S3 object.
What I'd like to do is store all of that in a file, so I could import myS3 from './myS3.js'
, then create some help methods like
...
get = async (config) => return JSON.parse(await S3.getObject(config).promise())....
put = ...
sign = ...
and ideally create it in a way that when I call the get
method it automatically refreshes the creds, then runs the get etc.
I'm just going in circles with exports vs. classes vs. functions. Is there a right / sane way to do this?
Turns out what I was trying to do was create Singleton.