当前位置: 首页 > 软件库 > 云计算 > Serverless 系统 >

aws-mobile-react-native-starter

授权协议 Apache-2.0 License
开发语言 JavaScript
所属分类 云计算、 Serverless 系统
软件类型 开源软件
地区 不详
投 递 者 陈马鲁
操作系统 跨平台
开源组织
适用人群 未知
 软件概览

AWS Mobile React Native Starter App - Serverless Pet Tracker

This 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 Overview

AWS Services used:

  • Amazon Cognito User Pools
  • Amazon Cognito Federated Identities
  • Amazon API Gateway
  • AWS Lambda
  • Amazon DynamoDB
  • Amazon S3
  • AWS Mobile Hub

Prerequisites

Getting Started

  1. Create your backend resources and download the sample code inside of my-project folder.

    $ awsmobile start my-project react-native
    
  2. Finally run the app:

    $ cd my-project
    $ npm install
    $ npm run ios #npm run android
    

Done!

Application walkthrough

  1. On a phone or emulator/simulator, open the application

  2. Select the SIGN UP tab in the lower right to register a new user. You will be prompted to enter a valid email and phone number to confirm your registration.

  3. Click Sign Up and you will receive a code via SMS. Enter this into the prompt and press OK.

  4. From the Sign In tab of the application enter the Username and Password of the user you just registered and select SIGN IN.

  5. A code will be sent via SMS. Enter that code in the prompt and press OK.

  6. Press the plus (+) button to upload a photo. After selecting a photo select the Check mark.

  7. Fill out a few details like the name, birthday, breed and gender of your pet. Press Add Pet to upload the photo. This will first transfer the photo to an S3 bucket which only the logged-in user has access to, it will then write the record to a DynamoDB table (via API Gateway and Lambda) that is also restricted on a per-user basis.

  1. You will see a record of your pet on the homescreen.

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 a new React Native App (CRNA) using create-react-native-app
  • cd into your new app dir.
  • Eject your react native app (in our examples call it "myapp")
create-react-native-app <project-directory>
cd <project-directory>
npm run eject # Eject as "React Native"
  • Download the aws-exports.js file from your AWS MobileHub project as outlined earlier in the Getting started section. Place it in the root of your new CRNA directory.

Authentication

  1. Install dependencies with npm install

  2. Install additional dependencies:

npm install aws-amplify --save
npm install aws-amplify-react-native --save
  1. Link the native components by running: react-native link

  2. Open the App.js file.

  3. Import the Auth module from the library and your aws-exports here

import Amplify from 'aws-amplify';
import { withAuthenticator } from 'aws-amplify-react-native';
import {awsmobile} from './aws-exports';
  1. Edit your App component to transform it into one that suports Auth
Amplify.configure(awsmobile);
export default withAuthenticator(class App extends React.Component {
  // ...
});
  1. Test it!npm run ios # or android

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 Control

In 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.

  1. Install additional dependencies
    npm install aws-amplify-react-native --save

  2. Import the aws-exports.js file

import awsmobile from './aws-exports';
  1. Import the API component from the library
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)
  1. Edit your App component to use Amplify's API functions to make REST calls to your API as follows:
async function getData() { 
    let apiName = 'MyApiName';
    let path = '/path';
    let myInit = { // OPTIONAL
        headers: {} // OPTIONAL
    }
    return await API.get(apiName, path, myInit);
}
  1. Test it!
    npm run ios # or android

  2. You can now invoke API Gateway APIs from your React Native that are protected via AWS IAM. You can use other REST calls as shown in this guide for AWS Amplify API component

Storing content in the cloud

Many 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 Storage component requires AWS Credentials to make calls to S3. If you need to store data in private folders for users, you will need to complete the Auth section first. Please follow steps from the earlier Authentication section.

  1. Import Storage component from the library
import Amplify, { Storage } from 'aws-amplify'
  1. Import the aws-exports.js file if you haven't already
import awsmobile from './aws-exports';
  1. Configure Storage using your aws-exports if you haven't already
Amplify.configure(awsmobile);
  1. Call Storage APIs in your code
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 level option with the call.To learn more about the UI components and other API calls for Storage, please refer the AWS Amplify Storage Guide

  1. Test it!
    npm run ios # or android

Modifying Express routes in Lambda

The 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.

  1. After you have cloned this repo, locate ./aws-mobile-react-native-starter/backend/lambdas/crud/app.js and find the following section of code:
app.listen(3000, function () {
  console.log('App started');
});
  1. Immediately Before this code (line_72) add in the following code:
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);
    }
  });
});
  1. Save the file and in the Mobile Hub console for your project click the Cloud Logic card. Expand the View resource details section and note the name of the Lambda function in the list for the next step. It should be something similar to Pets-itemsHandler-mobilehub-XXXXXXXXX.

  2. In a terminal navigate to ./aws-mobile-react-native-starter/backend and run:

npm run build-lambdas
aws lambda update-function-code --function-name FUNCTION_NAME --zip-file fileb://lambdas/crud-lambda.zip

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.

  1. Now that you've updated the Cloud Logic backend modify the client to call the new API route. In the ./aws-mobile-react-native-starter/client/src/Screens directory edit ViewPet.jsx
  • Add the following imports
import { Button } from 'react-native-elements';
import awsmobile from '../../aws-exports';
import API from '../../lib/Categories/API';
  • Add the following function BEFORE the render() method:
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);
    }
  }
  • In the return statement of the render method add in a new button after the <View style={styles.breaker} />:
// ...
      <View style={styles.breaker} />
      <Button
          fontFamily='lato'
          backgroundColor={colors.red}
          large
          title="DELETE PET"
          onPress={this.handleDeletePet.bind(this, pet.petId)} />
// ...
  1. Save the file and run the application again:
cd ./aws-mobile-react-native-starter/client
npm run ios # or android

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 Information

Remote Storage

This 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 Storage

This 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 Permissions

The 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.

  • 由于公司业务需求,最近正在研究React-native,主要参照的资料: 1.reactNative中文网 2.ReactJs网站 3.ReactNative移动开发实战。 在此记录所遇到的疑惑和自己个人的一些想法和感悟。

  • antd-mobile 一 // 下载组件库 1. cnpm install antd-mobile --save // 下载依赖 npm i --save babel-plugin-import npm i react-app-rewired@2.0.2-next.0 --save-dev 二 // 在项目根目录下定义加载配置的js模块: config-overrides.js const

  • 1、跨平台技术简介 跨平台技术主要为三类: H5+原生(Cordova、Ionic、微信小程序) JavaScript开发+原生渲染 (React Native、Weex、快应用) 自绘UI+原生(QT for mobile、Flutter) 2、Hybrid技术简介 2.1 H5+原生混合开发 这类框架主要原理就是将APP的一部分需要动态变动的内容通过H5来实现,通过原生的网页加载控件WebVi

  • 首先在工程当中安装npm install antd-mobile --save 安装完后在.babelrc文件中加入 { "presets": ["react-native"], // "plugins": [ // [ // "import", // {"style": "css" , "libraryName": "antd-mobile" } /

  • react native AsyncStorage explain 在app中必须要将redux和asyncStorage结合,进行数据的管理。比如获取大量数据的列表,就需要结合已经存在asyncStorage的数据和新获得的数据来得到新的列表。对于断网的情况,也能保证程序的正常进行。 refs https://github.com/Txiaozhe/react-native/wiki/react

 相关资料
  • AWS Mobile React Starter Kit This 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 AWS Mobile R

  • Introduction This is a Starter React application for using the Sample app in the AWS AppSync console when building your GraphQL API. The Sample app creates a GraphQL schema and provisions Amazon Dynam

  • 本文向大家介绍react-native 启动React Native Packager,包括了react-native 启动React Native Packager的使用技巧和注意事项,需要的朋友参考一下 示例 在最新版本的React Native上,无需运行打包程序。它将自动运行。 默认情况下,这将在端口8081上启动服务器。要指定服务器所在的端口            

  • 百度移动统计SDK支持使用react native框架的H5页面统计,封装好的插件已经在github上开源,相关用法具体请参考:https://github.com/BaiduMobileAnalysis/baidumobstat-react-native。

  • The React Native environment has a lot of little quirks, so this documentation is aimed at helping smooth those over. Please feel free to create issues on GitHub for recommendations and additions to t

  • React Native 可以基于目前大热的开源JavaScript库React.js来开发iOS和Android原生App。而且React Native已经用于生产环境——Facebook Groups iOS 应用就是基于它开发的。 React Native的原理是在JavaScript中用React抽象操作系统原生的UI组件,代替DOM元素来渲染,比如以<View>取代<div>,以<Ima