You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native如何连接已有AWS DynamoDB表?

Connecting React Native Amplify App to an Existing DynamoDB Table 'Movement'

Great question! The official docs lean heavily into creating new tables via the CLI, but connecting to an existing one is totally feasible—here are two solid approaches depending on how you want to interact with your 'Movement' table:

Option 1: Use Amplify API (with AppSync)

This is the most "Amplify-native" path, using AppSync to add a GraphQL layer on top of your existing DynamoDB table.

  1. Log into the AWS Console and open the AppSync service.
  2. Either create a new API or use an existing one. If creating new, select "Build from an existing data source".
  3. Add a DynamoDB data source, pick your 'Movement' table, and set up an IAM role to let AppSync access the table.
  4. Generate a GraphQL schema that matches your table's structure (AppSync can auto-generate this based on the table, or you can write it manually).
  5. Save your API and note these details:
    • GraphQL endpoint (aws_appsync_graphqlEndpoint)
    • Your AWS region (aws_appsync_region)
    • Authentication type (e.g., API_KEY, AMAZON_COGNITO_USER_POOLS)
    • API key (only if using API_KEY authentication)

Step 2: Update Your aws-exports.js

Add the AppSync config to your existing aws-exports.js file:

export default {
  // Keep your existing Amplify config (Cognito settings, etc.)
  aws_cognito_region: 'your-region',
  aws_user_pools_id: 'your-user-pool-id',
  // Add these AppSync-specific fields:
  aws_appsync_graphqlEndpoint: 'https://your-appsync-endpoint.appsync-api.your-region.amazonaws.com/graphql',
  aws_appsync_region: 'your-region',
  aws_appsync_authenticationType: 'API_KEY', // Or your chosen auth type
  aws_appsync_apiKey: 'your-api-key', // Include only if using API_KEY
};

Step 3: Interact with the Table in Your App

First install the required dependency if you haven’t already:

npm install @aws-amplify/api

Then use the API module to query or mutate your table:

import Amplify from 'aws-amplify';
import { API, graphqlOperation } from '@aws-amplify/api';
import aws_exports from './aws-exports';

Amplify.configure(aws_exports);

// Example: Fetch all items from the Movement table
const listMovementsQuery = `
  query ListMovements {
    listMovements {
      items {
        id
        // Add all your table's fields here (e.g., name, timestamp)
      }
    }
  }
`;

const fetchMovements = async () => {
  try {
    const response = await API.graphql(graphqlOperation(listMovementsQuery));
    console.log('Fetched movements:', response.data.listMovements.items);
  } catch (error) {
    console.error('Error fetching movements:', error);
  }
};

Option 2: Use AWS SDK Directly

If you want to skip AppSync and interact with DynamoDB directly, use the AWS SDK for JavaScript:

Step 1: Install Dependencies

npm install aws-sdk

Step 2: Configure the SDK with Amplify Credentials

import Amplify from 'aws-amplify';
import AWS from 'aws-sdk';
import aws_exports from './aws-exports';

Amplify.configure(aws_exports);

// Set up AWS SDK to use Amplify's authentication credentials
AWS.config.update({
  region: aws_exports.aws_cognito_region,
  credentials: await Amplify.Auth.currentCredentials()
});

const docClient = new AWS.DynamoDB.DocumentClient();

Step 3: Run DynamoDB Operations

// Example: Scan the Movement table to get all items
const fetchMovements = async () => {
  const params = {
    TableName: 'Movement',
    // Add filters, projections, or pagination parameters here if needed
  };

  try {
    const result = await docClient.scan(params).promise();
    console.log('Fetched movements:', result.Items);
  } catch (error) {
    console.error('Error scanning table:', error);
  }
};

Critical: IAM Permissions

Whichever approach you choose, ensure the IAM role linked to your Amplify users (Cognito user pool role, or the role used by the SDK) has the necessary permissions for the 'Movement' table. For example:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "dynamodb:GetItem",
        "dynamodb:Scan",
        "dynamodb:PutItem",
        "dynamodb:UpdateItem",
        "dynamodb:DeleteItem"
      ],
      "Resource": "arn:aws:dynamodb:your-region:your-account-id:table/Movement"
    }
  ]
}

内容的提问来源于stack exchange,提问作者Dunsany

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:05:12