Hoe een Full Stack-app te bouwen met AWS Amplify and React

AWS Amplify is een tool ontwikkeld door Amazon Web Services die de ontwikkeling van apps eenvoudiger maakt.

Het bevat tal van functies waarmee u snel en gemakkelijk met andere AWS-services kunt werken. Dit betekent dat u meer tijd kunt besteden aan het bouwen van de functies die uw app uniek maken.

Deze tutorial is opgesplitst in vier delen:

  • Hoe de app te maken met inloggen
  • Hoe u een database toevoegt en met de gegevens werkt
  • Hoe u bestandsopslag toevoegt en die bestanden gebruikt
  • Hoe gebruikers hun eigen bestanden en gegevens kunnen uploaden

Als je dit artikel offline wilt lezen, kun je het hier downloaden.

Hoe de app te maken met aanmelden, inloggen en uitloggen

In deze eerste sectie zullen we een nieuwe React-app opzetten met AWS Amplify om Aanmelden, Inloggen en Uitloggen op de gemakkelijkste manier toe te voegen.

We moeten beginnen met het maken van een nieuwe React-app met create-react-app. Open een terminal en voer deze opdrachten uit. Als u geen create-react-app heeft geïnstalleerd, kunt u deze npm i -g create-react-appeerst uitvoeren.

npx create-react-app amplify-react-app cd amplify-react-app

Met die opstelling kunnen we nu Amplify installeren en vervolgens configureren.

npm install -g @aws-amplify/cli amplify configure

Dit opent een AWS-consoletabblad in uw browser. Zorg ervoor dat u bent ingelogd op het juiste account met een gebruiker die beheerdersrechten heeft.

Ga terug naar de terminal en volg de stappen, voeg een regio en naam voor de gebruiker toe. Hiermee gaat u terug naar de browser waar u de stappen kunt volgen om de nieuwe gebruiker aan te maken. Zorg ervoor dat u op de pagina blijft waar u de sleutel en het geheim ziet!

Terug in de terminal kunt u de stappen volgen en desgevraagd de toegangssleutel en het geheim naar de terminal kopiëren. Als je wordt gevraagd of je dit aan een profiel wilt toevoegen, zeg dan Yes. Maak een profiel dat er ongeveer zo uitziet serverless-amplify.

Nu kunnen we de versterkingsconfiguratie initialiseren door uit te voeren amplify init. U kunt het project een naam geven en alle vragen beantwoorden. De meeste zouden al correct moeten zijn. Het duurt dan even voordat de wijzigingen in uw account zijn aangebracht.

Als we klaar zijn, moeten we authenticatie aan de app toevoegen. We doen dit met amplify add auth. Selecteer de methode voor defaulthet aanmelden bij emailen vervolgens no, I am done. We kunnen dit nu inzetten door te draaien amplify push. Dit duurt even, maar uiteindelijk is ons src/aws-exports.jsbestand gemaakt.

Hoe de React-app te bouwen

Nu kunnen we beginnen met het maken van de react-app. Begin met het installeren van de Amplify npm-pakketten die we nodig hebben.

npm install --save aws-amplify @aws-amplify/ui-react

Nu kunnen we beginnen met het bewerken van de code van onze app. In ons src/App.jsbestand kunnen we alles in de headers verwijderen en door dit vervangen:

My App Content

Dit is een zeer eenvoudige opzet, maar u kunt de hoofdinhoud van uw site hier plaatsen en de AmplifySignOutknop plaatsen waar u maar wilt.

We moeten ook wat extra invoer toevoegen aan de bovenkant van het bestand:

import Amplify from 'aws-amplify'; import awsconfig from './aws-exports'; import { AmplifySignOut, withAuthenticator } from '@aws-amplify/ui-react'; Amplify.configure(awsconfig); 

Het laatste dat we moeten doen, is de manier wijzigen waarop we de app exporteren. Verander de laatste regel om export default withAuthenticator(App);Amplify aan deze app toe te voegen.

Als we nu rennen npm start, zouden we een inlogscherm moeten krijgen. We hebben dit niet gemaakt, dus het is afkomstig van Amplify zelf.

Als we proberen in te loggen, lukt dit niet, omdat we ons eerst moeten aanmelden. We kunnen klikken create accounten vervolgens ons e-mailadres en een wachtwoord invoeren om ons aan te melden.

Zodra we onze e-mail hebben bevestigd door de code in te voeren die we hebben ontvangen, komen we op de startpagina van onze app. Als we uitloggen, kunnen we nu weer inloggen zoals verwacht.

Hoe u een database aan onze app kunt toevoegen

Als je gegevens aan je React-app wilt toevoegen maar geen API wilt bouwen, dan is dit de sectie voor jou. We zullen bekijken hoe we AWS-amplify kunnen gebruiken in onze React-app om ons toegang te geven tot onze database aan de achterkant met GraphQL.

Om te beginnen moeten we naar de terminal gaan en uitvoeren:

amplify add api

Dit zal ons starten met een reeks CLI-opties en ons een paar configuratievragen stellen:

Wat voor soort API we willen gebruiken: GraphQL

De naam van de API: songAPI

Hoe we de API willen authenticeren: Amazon Cognito User Pool

Geavanceerde instellingen: Nee, ik ben klaar

Heeft u een schema: Nee

Wat voor soort schema wilt u: enkel object met velden

Na een kleine setup wordt ons gevraagd of we ons nieuwe schema willen bewerken. We willen ja zeggen. Dit opent het GraphQL-schema dat we gaan bijwerken om het hier vermelde schema te worden.

type Song @model { id: ID! title: String! description: String! filePath: String! likes: Int! owner: String! }

Met onze schema-instelling gaan we uitvoeren, amplify pushdie onze huidige versterkingsconfiguratie zal vergelijken met die op ons AWS-account. Omdat we een nieuwe API hebben toegevoegd, hebben we wijzigingen, dus we zullen worden gevraagd of we door willen gaan met de wijzigingen.

Zodra we Ja hebben geselecteerd, worden we in een andere reeks opties geplaatst.

Do we want to generate code for our GraphQL API: Yes

Which Language: JavaScript

File pattern for the new files: src/graphql/**/*.js

Generate all operations: Yes

Maximum statement depth: 2

This will now deploy all of the changes to AWS and also set up the new request files in our React app. This does take a few minutes to do.

Once that is completed we can go into our App.js file and rename it to be App.jsx. This just makes it easier to write our JSX code.

We now need to write a function in here to get the list of songs from our new database. This function calls the GraphQL API passing in the operation of listSongs. We also need to add a new state to the App component.

const [songs, setSongs] = useState([]); const fetchSongs = async () => { try { const songData = await API.graphql(graphqlOperation(listSongs)); const songList = songData.data.listSongs.items; console.log('song list', songList); setSongs(songList); } catch (error) { console.log('error on fetching songs', error); } };

We now need to add or update a few imports to our file to get this working:

import React, { useState, useEffect } from 'react'; import { listSongs } from './graphql/queries'; import Amplify, { API, graphqlOperation } from 'aws-amplify';

The listSongs is one of those functions created by amplify to help us access our data. You can see the other functions that are available in the ./graphql folder.

Now we want this function to be called once when the component renders, but not every time that it re-renders. To do this we use useEffect but make sure to add a second parameter of [] so that it only gets triggered once.

useEffect(() => { fetchSongs(); }, []);

If we now start our app using npm start and then go to the app we can open the console and see a log of song list []. This means that the useEffect has called the fetchSongs which is console logging out the result, but currently there is nothing in the database.

To correct this we need to log into our AWS account and add the DynamoDB service. We should find a new table called something like Song-5gq8g8wh64w-dev. If you can't find it make sure to check other regions as well.

This currently has no data so we need to add some. For now we're going with manually creating new data in here. Under Items click Create item and then make sure the dropdown in the top left shows text. If it shows tree then just click it and change it to text. We can then make the data go into that row.

We start with the GraphQL schema, giving the row some data for each attribute. But we also need to add createdAt and updatedAt values. You can find this using the browser console.

Type new Date().toISOString() and copy the result of that. You should end up with an object like this:

{ "id": "gr4334t4tog345ht35", "title": "My First Song", "description": "A test song for our amplify app", "owner": "Sam Williams", "filePath": "", "likes": 4, "createdAt": "2020-08-13T07:01:39.176Z", "updatedAt": "2020-08-13T07:01:39.176Z" }

If we save that new object then we can go back into our app and refresh the page. We should now be able to see our data in the console.log.

We can now use this data in our app to show the list of songs that we just got. Replace the existing text of song list with this set of JSX.

 {songs.map((song, idx) => { return ( {song.title} {song.owner} {song.likes} {song.description} ); })} 

This code is mapping over each song in the list and rendering a new Paper for them with all the details we need.

We're using the MaterialUI library to help make this look nice for us so we need to make sure to run npm install --save @material-ui/core @material-ui/icons to install those packages and then add them to the imports at the top of the file too:

import { Paper, IconButton } from '@material-ui/core'; import PlayArrowIcon from '@material-ui/icons/PlayArrow'; import FavoriteIcon from '@material-ui/icons/Favorite';

With this, if we save and reload our app we now get this:

Whilst this is ok, we can update the CSS to make it look far better. Open up your App.css file and change it to this:

.App { text-align: center; } .App-logo { height: 10vmin; pointer-events: none; } .App-header { background-color: #282c34; min-height: 5vh; display: flex; align-items: center; justify-content: space-around; font-size: calc(10px + 2vmin); color: white; } .App-link { color: #61dafb; } .songList { display: flex; flex-direction: column; } .songCard { display: flex; justify-content: space-around; padding: 5px; } .songTitle { font-weight: bold; }

Now we get it looking like this - much better.

Now we've got one item in the database so we only get one record. If we go back into Dynamo and create a new item or duplicate the existing one then we can see how multiple songs look. You can duplicate an item by clicking the checkbox to its left

Now that we can get the data, what about updating that info? For this we are going to add the ability to like a song. To start this we can add an onClick function to the icon button that we have for the likes.

 addLike(idx)}>

You may have realised that there is this idx property that we haven't see before. That is short for index.

Where we do the songs.map we can update it slightly to get the position of each item in the list. We can also use this idx to add a key to the top level Paper in that map to remove an errors we get from React.

{songs.map((song, idx) => { return (  ...  )} )}

With the new index and the onClick function call, we now need to make the addLike function.

This function needs to take the index of the song to find the correct song and update the number of likes. It then removes some fields that can't be passed into the updateSong operation before calling that operation.

const addLike = async idx => { try { const song = songs[idx]; song.likes = song.likes + 1; delete song.createdAt; delete song.updatedAt; const songData = await API.graphql(graphqlOperation(updateSong, { input: song })); const songList = [...songs]; songList[idx] = songData.data.updateSong; setSongs(songList); } catch (error) { console.log('error on adding Like to song', error); } };

Once the song has been updated in the database, we need to get that update back into our state. We need to clone the existing songs using const songList = [...songs].

If we just mutate the original list of songs then React wouldn't have re-rendered the page. With that new song list we call setSongs to update our state and we're done with the function.

We just need to add one more import to the top of the file which we get from the mutators that Amplify created:

import { updateSong } from './graphql/mutations';

Now when we click on the like button on a song, it is updated in state and in the database.

How to Add File Storage

Now that we have the song data stored in Dynamo, we want to store the actual MP3 data somewhere. We'll be storing the songs in S3 and accessing them using Amplify.

How to Add Play/Pause Functionality

To get started we're going to add a way to play and pause each of the songs. For now, this will just change the play button to a pause button.

Later we'll be using the Amplify Storage methods to get our MP3 file from S3 and play it directly in our app.

We're going to add a new function to the App component called toggleSong.

const toggleSong = async idx => { if (songPlaying === idx) { setSongPlaying(''); return; } setSongPlaying(idx); return }

To get this working we also need to add a new state variable to the app. This will be used to store the index of the song that is currently playing.

const [songPlaying, setSongPlaying] = useState('');

With this set up we need to make a change to the JSX code to use our new function and variables.

Find the first button in the songCard div. We're going to be adding an onClick which calls our new function. We're also going to use a ternary equation to say that if the song that is playing is this song, show a pause icon instead of a play icon.

 toggleSong(idx)}> {songPlaying === idx ?  : } 

We'll just need to import the PauseIcon at the top of the file and we'll be ready.

import PauseIcon from '@material-ui/icons/Pause';

How to Add the Storage to Amplify

Next, we need to use the Amplify CLI to add the storage to our app. We can start by going into our terminal and running amplify add storage. This will open a CLI where we need to select the following options.

Please select your service = Content (images, audio, video, etc.)

Friendly name for your resource = songStorage

Bucket name = song-storage

Who should have access = Auth Users Only

What access do those users have = Read and Create/Update

Do you want a Lambda trigger?  = No

With that all configured we need to deploy it. We can start that with amplify push which will take a little bit of time to work out what we've changed in our amplify application. You'll then get a little display of all of the resources we have in Amplify.

The only change is the creation of our new songStorage resource. We can select Yes to continuing and then it will create our S3 bucket for us.

How to Access the S3 File through the Amplify Storage methods

Once the deployment has finished we can start using that to access our songs. Back in our toggleSong function we are going to add some extra logic.

const toggleSong = async idx => { if (songPlaying === idx) { setSongPlaying(''); return; } const songFilePath = songs[idx].filePath; try { const fileAccessURL = await Storage.get(songFilePath, { expires: 60 }); console.log('access url', fileAccessURL); setSongPlaying(idx); setAudioURL(fileAccessURL); return; } catch (error) { console.error('error accessing the file from s3', error); setAudioURL(''); setSongPlaying(''); } };

This is getting the file path from the song data (that was stored in Dynamo) and then using Storage.get(songFilePath, { expires: 60 }); to get an access URL for the file.

The { expires: 60 } on the end is saying that the URL returned is only going to work for 60 seconds. After that you won't be able to access the file with it. This is a useful security measure so people can't share the URL to others who shouldn't have access to the files.

Once we have the file, we're also setting that in a new state variable using setAudioURL. At the top of our App we need to add this extra state.

const [audioURL, setAudioURL] = useState('');

Save this and go back into our app. If we press the play button and open the console we'll see the URL being logged out. This is what we're going to use to play the song.

How to Upload Our Songs

We're now getting to the point where we need some songs to play. If we go into our AWS account and search for S3 and then search for song , we should find our new S3 bucket.

In there we need to create a new folder called public. This is because the files will be public to everyone who has signed into the app. There are other ways of storing data which are private and only viewable by specific people.

Inside that folder we need to upload two songs. I have two copyright free songs that I uploaded called epic.mp3 and tomorrow.mp3. Once they have been uploaded we need to update our Dynamo data to point at those songs.

In Dynamo we can find our Songs-(lots of random charachters) table. Under Items we should have two records. Open up the first one and change the filePath to tomorrow.mp3 and the name to Tomorrow.

Save that and open the second song, changing that to "filePath": "epic.mp3" and "name": "Epic" , saving that file too.

If you used your own songs then just make sure the filePath matches the file name of your songs.

We can now go back into our app, refresh the page, and press play on one of the songs. If we look in our console and copy the URL we're given we can paste that into a browser and our song should start playing.

How to Add a Media Player to Our App

Now we want to be able to actually play our song from within our app. To do this we're going to use a library called react-player. We need to first install it with npm install --save react-player.

In our app we can then import it at the top of the file.

import ReactPlayer from 'react-player';

If we find our

className="songCard">, we want to add our player after that component. In the same way we showed the play/pause icons, we're going to show or hide this player based on which song is playing.

 .. .. {songPlaying === idx ? ( toggleSong(idx)} /> ) : null}

The ReactPlayer takes a few parameters. The url is just the file URL to play, which is the one we get from Amplify Storage. controls allows the user to change the volume or pause the song. playing means the song starts playing as soon as it's loaded and onPause is a listener so we can have the inbuilt pause button work the same as our pause button.

With this all done we can save everything again and open our App. In there if we press play on one of the songs, we should see a player appear and the song will be playing.

How to Enable User Uploads

Now we have an app which allows users to view all of the songs and play them from S3. To build upon that we want to allow our users to upload their own songs to the platform.

We first need to create a way to add a song and input some information. We start by creating an Add button.

{ showAddSong ?  :    } 

We then also need to add the AddIcon to our imports.

import AddIcon from '@material-ui/icons/Add'; 

Now we can move onto creating the new AddSong component. We can create this at the bottom of our App.jsx file.

const AddSong = () => { return ( ) } 

We also need to add TextField to our imports from material UI.

import { Paper, IconButton, TextField } from '@material-ui/core'; 

The next thing to do is add the ability to open our new component by controlling the showAddSong variable. We need to create a new state declaration next to the others.

const [showAddSong, setShowAddNewSong] = useState(false); 

We can now update our new AddIcon button to set showAddSong to true.

 setShowAddNewSong(true)}>

To change it back, we can add a parameter to our AddSong component called onUpload. When this gets called we will reset the showAddSong to false.

 { setShowAddNewSong(false); }} />

We then need to update our component to work with that new parameter and a button to "upload" the new song. That button calls a function in the component where we will add the ability to upload the data, but for now we will just call the onUpload function.

const AddSong = ({ onUpload }) => { const uploadSong = async () => { //Upload the song onUpload(); }; return ( ); }; 

And now we add the PublishIcon to our imports and we're ready to test this out.

import PublishIcon from '@material-ui/icons/Publish'; 

When we start up the app and log in we now get a plus icon. By clicking that we can enter some details for the song and click upload.

How to Update AddSong

Now we want to be able to store and access the data that a user enters into the fields when adding a song.

const AddSong = ({ onUpload }) => { const [songData, setSongData] = useState({}); const uploadSong = async () => { //Upload the song console.log('songData', songData); const { title, description, owner } = songData; onUpload(); }; return ( setSongData({ ...songData, title: e.target.value })} />  setSongData({ ...songData, owner: e.target.value })} />  setSongData({ ...songData, description: e.target.value })} /> ); }; 

We've also had to change all of the TextFields to be controlled, passing in a value from out state and providing an onChange too. If we save this and try entering some details before uploading we should see a console.log of the details in our chrome console.

Next we need to add the ability to actually upload the song. For this we'll be using the default html input with a type of file. Add this to the JSX just before the upload icon button.

 setMp3Data(e.target.files[0])} />

As you may have noticed we are calling setMp3Data on change. This is some more state in the AddSong component.

const [mp3Data, setMp3Data] = useState(); 

Now that we have all of the data that we need, we can start by uploading the song to S3 and then the data to our database.

To upload the song we're going to use the Amplify Storage class again. The fileName is going to be a UUID so we also need to run npm install --save uuid in our terminal and then import it at the top of our file import { v4 as uuid } from 'uuid';. We then pass in the mp3Data and a contentType and we get back an object with a key.

const { key } = await Storage.put(`${uuid()}.mp3`, mp3Data, { contentType: 'audio/mp3' }); 

Now that we have the key we can create the record for the song in the database. As there may be multiple songs with the same name, we'll use an UUID as the ID again.

const createSongInput = { id: uuid(), title, description, owner, filePath: key, like: 0, }; await API.graphql(graphqlOperation(createSong, { input: createSongInput })); 

To get this to work we need to import the createSong mutator that was created when we created the dynamo storage with Amplify.

import { updateSong, createSong } from './graphql/mutations'; 

The last thing that we need to do is make the app re-get the data from the database once we've finished uploading it. We can do this by adding a fetchSongs call as part of the onUpload function.

 { setShowAddNewSong(false); fetchSongs(); }} />

Now when we reload the page, we can click to add a new song, input the details, select our new song, upload it and then play it back from the app.

That's all, folks!

If you've liked this article (and accompanying videos) and want to help me out, then the best thing you can do is to subscribe to my Youtube Channel. I create weekly videos on AWS and Serverless to help you become a better developer. Subscribe Here