在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称(OpenSource Name):amazon-archives/aws-mobile-react-native-starter开源软件地址(OpenSource Url):https://github.com/amazon-archives/aws-mobile-react-native-starter开源编程语言(OpenSource Language):JavaScript 91.1%开源软件介绍(OpenSource Introduction):AWS Mobile React Native Starter App - Serverless Pet TrackerThis sample application has been archived in favor of Amplify JS Samples. While the archived repository will still work, please go +1 this feature request for Serverless Pet Tracker sample if you are looking to use this sample. Bootstrap a React Native application on AWS. This starter automatically provisions a Serverless infrastructure with authentication, authorization, image storage, API access and database operations. It also includes user registration and MFA support. The sample use case is a "Pet Tracker" where after a user registers and logs in they can upload pictures of their pet to the system along with information like the birthday or breed. A companion blog post for this repository can be found in the AWS Mobile Blog: Announcing: React Native Starter Project with One-Click AWS Deployment and Serverless Infrastructure. This starter uses the AWS Amplify JavaScript library to add cloud support to the application. Quicklinks
Architecture OverviewAWS Services used:
Prerequisites
Getting Started
Done! Application walkthrough
Use features in your app.This starter app uses AWS Amplify library to integrate with AWS. The library components can be used in your app to easily add capabilities for Authentication, Storage and API access. You will need Create React Native App for the next sections.
create-react-native-app <project-directory>
cd <project-directory>
npm run eject # Eject as "React Native"
Authentication
import Amplify from 'aws-amplify';
import { withAuthenticator } from 'aws-amplify-react-native';
import {awsmobile} from './aws-exports';
Amplify.configure(awsmobile);
export default withAuthenticator(class App extends React.Component {
// ...
});
The withAuthenticator component adds Sign Up, Sign In with MFA and Sign Out capabilites to your app out of box. You can either use this Higher Order Component, or build your own UI and use the APIs from Amplify too. Cloud APIs and Backend Access ControlIn order to access resources in your AWS account that are protected via AWS Identity and Access Management you will need to sign your requests using the AWS Signature Version 4 signing process. The starter app uses the API component from Amplify to make signed requests to your API's endpoint. To make Authenticated calls to your API, you will need to use the library Auth component first to get the Authentcated AWS Credentials. You can make unauthenticated requests to your API too.
import awsmobile from './aws-exports';
import Amplify, { API } from 'aws-amplify'; 4.Configure Amplify //you can skip this step if Amplify was already configured in the previous section on Auth Amplify.configure(awsmobile)
async function getData() {
let apiName = 'MyApiName';
let path = '/path';
let myInit = { // OPTIONAL
headers: {} // OPTIONAL
}
return await API.get(apiName, path, myInit);
}
Storing content in the cloudMany applications today provide rich media such as images or videos. Sometimes these are also private to users. AWS Amplify Storage module gives a simple mechanism for managing user content in public or private storage. The
import Amplify, { Storage } from 'aws-amplify'
import awsmobile from './aws-exports';
Amplify.configure(awsmobile);
Storage.put('yourFile.txt', 'your key', {
level: 'private', //access control level
contentType: 'text/plain'
})
.then (result => console.log(result))
.catch(err => console.log(err)); Amplify Storage component provides users with APIs to perform PUT, GET, REMOVE and LIST bucket objects. The component is also configurable to store data in either private (Authenticated) folder or the public one. This can be specified using the
Modifying Express routes in LambdaThe sample application invokes a Lambda function running Express which will make CRUD operations to DynamoDB depending on the route which is passed from the client application. You may wish to modify this backend behavior for your own needs. The steps outline how you could add functionality to "delete a Pet" by showing what modifications would be needed in the Lambda function and the corresponding client modifications to make the request.
app.listen(3000, function () {
console.log('App started');
});
app.delete('/items/pets/:petId', (req, res) => {
if (!req.params.petId) {
res.status(400).json({
message: 'You must specify a pet id',
}).end();
return;
}
const userId = req.apiGateway.event.requestContext.identity.cognitoIdentityId;
dynamoDb.delete({
TableName: PETS_TABLE_NAME,
Key: {
userId: userId,
petId: req.params.petId,
}
}, (err, data) => {
if (err) {
console.log(err)
res.status(500).json({
message: 'Could not delete pet'
}).end();
} else {
res.json(null);
}
});
});
REPLACE the FUNCTION_NAME with your Lambda function name from the previous step. This might take a moment to complete based on your network connection. Please be patient. Alternatively you could click the Lambda function resource in the Mobile Hub console which opens the Lambda console and press the Upload button on that page to upload the lambdas/crud-lambda.zip file.
import { Button } from 'react-native-elements';
import awsmobile from '../../aws-exports';
import API from '../../lib/Categories/API';
async handleDeletePet(petId) {
const cloudLogicArray = JSON.parse(awsmobile.aws_cloud_logic_custom);
const endPoint = cloudLogicArray[0].endpoint;
const requestParams = {
method: 'DELETE',
url: `${endPoint}/items/pets/${petId}`,
}
try {
await API.restRequest(requestParams);
this.props.navigation.navigate('Home');
} catch (err) {
console.log(err);
}
}
// ...
<View style={styles.breaker} />
<Button
fontFamily='lato'
backgroundColor={colors.red}
large
title="DELETE PET"
onPress={this.handleDeletePet.bind(this, pet.petId)} />
// ...
If you have previously uploaded any pets click on their thumbnail from the main page (if not upload one now). You should see a new button DELETE PET. Click on it and the pet should be removed from the screen. The record should also have been removed from the DynamoDB table. You can validate this by going to the Resources section of your Mobile Hub project and opening up the DynamoDB table. Security InformationRemote StorageThis starter app uploads content to an S3 bucket. The S3 bucket is configured by Mobile Hub to use fine-grained access control to support public, protected and private access, you can find more information here. To learn more about restricting this access further, see Amazon S3 Security Considerations. Local StorageThis starter app uses React Native's AsyncStorage to persist user tokens locally (accessKeyId, secretAccessKey and sessionToken). You can take further actions to secure these tokens by encrypting them. API Handler Table PermissionsThe Lambda function in this starter will read and write to DynamoDB and it's role will be granted the appropriate permissions to perform such actions. If you wish to modify the sample to perform a more restricted set of actions see Authentication and Access Control for Amazon DynamoDB. |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论