### Automated REST API Setup with Amplify CLI Source: https://docs.amplify.aws/gen1/react-native/prev/build-a-backend/restapi/set-up-rest-api This command initiates the automated setup for a REST API in your Amplify project. It guides you through selecting service types like REST and configuring resources such as Lambda functions or DynamoDB tables. After setup, 'amplify push' deploys these resources. ```bash amplify add api amplify push ``` -------------------------------- ### Initialize Expo Project with Amplify (Expo CLI) Source: https://docs.amplify.aws/gen1/react-native/prev/build-a-backend/more-features/datastore/set-up-datastore Initializes a new Expo project, navigates into the project directory, runs the Amplify app setup script, and installs necessary AWS Amplify dependencies for Expo. ```bash npx create-expo-app AmplifyDataStoreExpo cd AmplifyDataStoreExpo npx amplify-app@latest expo install aws-amplify amazon-cognito-identity-js @react-native-community/netinfo @react-native-async-storage/async-storage @azure/core-asynciterator-polyfill ``` -------------------------------- ### Perform GET Request with Axios Configuration Source: https://docs.amplify.aws/gen1/react-native/prev/build-a-backend/restapi/fetch-data Demonstrates how to make a GET request using Amplify's API module. It shows how to configure headers, response handling, and query string parameters. The example uses a Promise-based approach. ```javascript const apiName = 'MyApiName'; const path = '/path'; const myInit = { headers: {}, // OPTIONAL response: true, // OPTIONAL (return the entire Axios response object instead of only response.data) queryStringParameters: { name: 'param' // OPTIONAL } }; API.get(apiName, path, myInit) .then((response) => { // Add your code here }) .catch((error) => { console.log(error.response); }); ``` -------------------------------- ### Initialize React Native Project with Amplify (CLI) Source: https://docs.amplify.aws/gen1/react-native/prev/build-a-backend/more-features/datastore/set-up-datastore Initializes a new React Native project using the React Native CLI, navigates into the project directory, runs the Amplify app setup script, and installs necessary AWS Amplify dependencies. ```bash npx react-native@0.68.2 init AmplifyDataStoreRN --version 0.68.2 cd AmplifyDataStoreRN npx amplify-app@latest npm install aws-amplify@^5 amazon-cognito-identity-js @react-native-community/netinfo @react-native-async-storage/async-storage @azure/core-asynciterator-polyfill ``` -------------------------------- ### Initialize React Native Project with SQLite Adapter Source: https://docs.amplify.aws/gen1/react-native/build-a-backend/more-features/datastore/set-up-datastore Initializes a new React Native project with the CLI and installs Amplify packages along with the SQLite adapter for DataStore. This setup is for enhanced local database performance. ```bash npx react-native init AmplifyDataStoreRN cd AmplifyDataStoreRN npm install aws-amplify @aws-amplify/react-native @react-native-community/netinfo @aws-amplify/datastore-storage-adapter react-native-sqlite-storage @react-native-async-storage/async-storage react-native-get-random-values @azure/core-asynciterator-polyfill npx pod-install ``` -------------------------------- ### Perform GET Request with Async/Await Source: https://docs.amplify.aws/gen1/react-native/prev/build-a-backend/restapi/fetch-data Provides an example of making a GET request using async/await syntax with Amplify's API module. This approach simplifies asynchronous code handling by abstracting away Promise chains. ```javascript function getData() { const apiName = 'MyApiName'; const path = '/path'; const myInit = { headers: {} // OPTIONAL }; return API.get(apiName, path, myInit); } (async function () { const response = await getData(); })(); ``` -------------------------------- ### Mock Amplify API Locally Source: https://docs.amplify.aws/gen1/react-native/start/getting-started/data-model This command starts a local mock environment for the Amplify API. It requires Java to be installed and allows for testing GraphQL operations without deploying to the cloud, simulating backend behavior. ```bash amplify mock api ``` -------------------------------- ### Amplify CLI Commands for Lambda Function Setup Source: https://docs.amplify.aws/gen1/react-native/prev/build-a-backend/graphqlapi/connect-from-server-runtime Illustrates the Amplify CLI commands used to add a new Lambda function to your project. It guides through selecting the runtime (NodeJS), template, and configuring advanced settings like resource access permissions. ```bash amplify add function ? Select which capability you want to add: Lambda function (serverless function) ? Provide an AWS Lambda function name: myfunction ? Choose the runtime that you want to use: NodeJS ? Choose the function template that you want to use: Hello World Available advanced settings: - Resource access permissions - Scheduled recurring invocation - Lambda layers configuration - Environment variables configuration - Secret values configuration ? Do you want to configure advanced settings? Yes ? Do you want to access other resources in this project from your Lambda function? Yes ? Select the categories you want this function to have access to. api ? Select the operations you want to permit on Query, Mutation, Subscription You can access the following resource attributes as environment variables from your Lambda function API__GRAPHQLAPIENDPOINTOUTPUT API__GRAPHQLAPIIDOUTPUT API__GRAPHQLAPIKEYOUTPUT ENV REGION ``` -------------------------------- ### Initialize Amplify Auth for Admin Queries (Amplify CLI) Source: https://docs.amplify.aws/gen1/react-native/build-a-backend/auth/admin-actions This command initializes the Amplify CLI for authentication setup. It guides the user through manual configuration to enable user pool groups and an admin queries API, restricted to a specific group. ```bash amplify add auth ``` -------------------------------- ### Define Global Authorization Rule (Amplify CLI) Source: https://docs.amplify.aws/gen1/react-native/build-a-backend/graphqlapi/customize-authorization-rules This snippet illustrates how to define a global authorization rule using the AMPLIFY input in the GraphQL schema. This rule, set to public in this example, applies to all data models by default. It's intended for getting started and should be replaced with model-specific rules in production. ```graphql input AMPLIFY { globalAuthRule: AuthRule = { allow: public } } ``` -------------------------------- ### Initialize Amplify Project from GitHub Repository Source: https://docs.amplify.aws/gen1/react-native/tools/cli/usage/headless This command initializes an Amplify project by cloning a sample project from a specified GitHub repository. It requires the directory to be empty and the repository to contain specific Amplify configuration files. ```bash amplify init --app git@github.com:/.git ``` -------------------------------- ### Add Push Notifications Resources with Amplify CLI Source: https://docs.amplify.aws/gen1/react-native/build-a-backend/push-notifications/set-up-push-notifications This command initiates the setup process for push notification resources using the Amplify CLI. It guides you through selecting notification channels (APNS, FCM) and configuring necessary details like resource names and authorization for analytics events. Ensure you have Amplify CLI version 12.12.3+ installed. ```bash amplify add notifications ``` -------------------------------- ### Install Amplify CLI with cURL (Windows) Source: https://docs.amplify.aws/gen1/react-native/tools/cli/start/set-up-cli Installs the Amplify CLI on Windows systems using cURL. This command downloads an installation script and executes it to set up the Amplify CLI for your Windows environment. ```cmd curl -sL https://aws-amplify.github.io/amplify-cli/install-win -o install.cmd && install.cmd ``` -------------------------------- ### Initialize Expo App and Install Dependencies Source: https://docs.amplify.aws/gen1/react-native/build-a-backend/more-features/datastore/set-up-datastore Creates a new Expo managed project and installs necessary Amplify and community packages, including the SQLite adapter for DataStore. ```bash npx create-expo-app AmplifyDataStoreExpo cd AmplifyDataStoreExpo expo install aws-amplify @aws-amplify/react-native @react-native-community/netinfo @aws-amplify/datastore-storage-adapter react-native-sqlite-storage @react-native-async-storage/async-storage react-native-get-random-values @azure/core-asynciterator-polyfill ``` -------------------------------- ### GET /posts Source: https://docs.amplify.aws/gen1/react-native/tools/cli-legacy/http-directive Example of a simple GET request to list posts using the @http directive. ```APIDOC ## GET /posts ### Description This endpoint fetches a list of posts from a specified URL. ### Method GET ### Endpoint /posts ### Query Parameters None ### Request Body None ### Request Example ```graphql query { listPosts { id title } } ``` ### Response #### Success Response (200) - **id** (ID!) - The unique identifier for the post. - **title** (String) - The title of the post. #### Response Example ```json { "id": "123", "title": "Example Post" } ``` ``` -------------------------------- ### Initialize Amplify Project and Environment Source: https://docs.amplify.aws/gen1/react-native/tools/cli/teams/shared This snippet demonstrates how to initialize an Amplify project and select an existing environment for team collaboration. Ensure the 'amplify' folder exists to reuse environments. If 'team-provider-info.json' is missing, pull the environment using the provided command. ```bash cd amplify init # Follow prompts to choose an existing environment (e.g., 'dev') ``` ```bash # If team-provider-info.json is missing: amplify pull --appId --envName ``` ```bash # After initialization or pull, add/update resources and push changes: amplify add/update amplify push ``` -------------------------------- ### Install Amplify CLI Globally Source: https://docs.amplify.aws/gen1/react-native/tools/cli/plugins/authoring Installs the AWS Amplify CLI globally on your system using npm. This is a prerequisite for using Amplify for project setup and management. ```bash npm install -g @aws-amplify/cli ``` ```bash curl -sL https://aws-amplify.github.io/amplify-cli/install | bash && $SHELL ``` ```bash curl -sL https://aws-amplify.github.io/amplify-cli/install-win -o install.cmd && install.cmd ``` -------------------------------- ### API GET Request Example Source: https://docs.amplify.aws/gen1/react-native/build-a-backend/restapi/test-api This snippet shows an example of an HTTP GET request to an API endpoint, including a query string parameter for limiting results. It's used for testing API functionality directly through the API Gateway console. ```HTTP GET /todos?limit=10 ``` -------------------------------- ### Amplify CLI Interactive Prompts for Project Setup Source: https://docs.amplify.aws/gen1/react-native/build-a-backend/existing-resources/cli Demonstrates the interactive prompts of the Amplify CLI during the `amplify pull` process. It covers selecting authentication methods, default editor, app type, framework, and project paths, as well as handling backend environment updates. ```bash ? Select the authentication method you want to use: AWS profile For more information on AWS Profiles, see: https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-profiles.html ? Please choose the profile you want to use AwsWest1 Amplify AppID found: dfn3u8j1nvzjc. Amplify App name is: reactamplified Backend environment dev found in Amplify Console app: reactamplified ? Choose your default editor: Visual Studio Code ✔ Choose the type of app that you're building · javascript Please tell us about your project ? What javascript framework are you using react ? Source Directory Path: src ? Distribution Directory Path: build ? Build Command: npm run-script build ? Start Command: npm run-script start ? Do you plan on modifying this backend? Yes ⠋ Fetching updates to backend environment: dev from the cloud. ⚠️ WARNING: your GraphQL API currently allows public create, read, update, and delete access to all models via an API Key. To configure PRODUCTION-READY authorization rules, review: https://docs.amplify.aws/cli/graphql/authorization-rules ⠇ Fetching updates to backend environment: dev from the cloud. ✅ GraphQL schema compiled successfully. Edit your schema at /Users/malakamm/development/react-amplify-connect/amplify/backend/api/reactamplified/schema.graphql or place .graphql files in a directory at /Users/malakamm/development/react-amplify-connect/amplify/backend/api/reactamplified/schema ✔ Successfully pulled backend environment dev from the cloud. Browserslist: caniuse-lite is outdated. Please run: npx update-browserslist-db@latest Why you should do it regularly: https://github.com/browserslist/update-db#readme ✅ ✅ Successfully pulled backend environment dev from the cloud. Run 'amplify pull' to sync future upstream changes. ``` -------------------------------- ### Start React Native App Source: https://docs.amplify.aws/gen1/react-native/start/getting-started/setup Starts the React Native development server and runs the application. Provides commands for reloading, opening the developer menu, and running on specific platforms (iOS/Android). ```bash npm start r - reload the app d - open developer menu i - run on iOS a - run on Android ``` -------------------------------- ### Install Amplify CLI with cURL (Mac/Linux) Source: https://docs.amplify.aws/gen1/react-native/tools/cli/start/set-up-cli Installs the Amplify CLI on macOS and Linux systems using cURL. This script downloads and executes the installation command, setting up the CLI for use in your shell environment. ```bash curl -sL https://aws-amplify.github.io/amplify-cli/install | bash && $SHELL ``` -------------------------------- ### Automated Storage Setup with Amplify CLI Source: https://docs.amplify.aws/gen1/react-native/prev/build-a-backend/storage/set-up-storage This snippet shows how to initiate the automated setup for storage using the Amplify CLI. It involves running 'amplify add storage' and selecting 'Content' as the service type, followed by 'amplify push' to update the backend. The AWS configuration is then automatically generated in 'aws-exports.js'. ```bash amplify add storage ``` ```bash amplify push ``` -------------------------------- ### Install Amplify CLI with npm Source: https://docs.amplify.aws/gen1/react-native/tools/cli/start/set-up-cli Installs the Amplify Command Line Interface (CLI) globally using npm. This toolchain is used to create AWS cloud services for your application. Ensure Node.js and npm are installed before running this command. ```bash npm install -g @aws-amplify/cli ``` -------------------------------- ### Initialize Production Amplify Environment and Git Repository Source: https://docs.amplify.aws/gen1/react-native/tools/cli/teams This snippet initializes a new Amplify project for the production environment and sets up a corresponding Git repository. It involves running `amplify init`, configuring AWS profiles, adding Amplify categories, initializing Git, committing initial files, and pushing to the 'prod' branch of a remote repository. ```shell $ amplify init ? Enter a name for the environment: prod // Provide AWS Profile info // Add amplify categories using `amplify add ` $ git init $ git add $ git commit -m "Creation of a prod amplify environment" $ git remote add origin git@github.com: $ git push -u origin prod ``` -------------------------------- ### Example Session Start Event Structure Source: https://docs.amplify.aws/gen1/react-native/prev/build-a-backend/more-features/analytics/auto-track-sessions This JSON object represents the structure of a session start event that is sent to the Amazon Pinpoint Service when auto-tracking is enabled. It includes the event type and any associated attributes. ```json { eventType: '_session_start', attributes: { attr: 'attr' } } ``` -------------------------------- ### Making a GET Request with Query Parameters (JavaScript) Source: https://docs.amplify.aws/gen1/react-native/build-a-backend/restapi/fetch-data Provides an example of how to make a GET request to a REST API using the Amplify `get` function, including specifying query parameters. This demonstrates client-side interaction with the backend API. ```javascript async function getTodo() { try { const restOperation = get({ apiName: 'todo-api', path: '/todo', options: { queryParams: { id: '123' } } }); const response = await restOperation.response; console.log('GET call succeeded: ', response); } catch (e) { console.log('GET call failed: ', JSON.parse(e.response.body)); } } ``` -------------------------------- ### Initialize React Native Project and Install Dependencies Source: https://docs.amplify.aws/gen1/react-native/build-a-backend/more-features/datastore/set-up-datastore Initializes a new React Native project using the React Native CLI, navigates into the project directory, and installs necessary Amplify and community packages. This command assumes you are using React Native version 0.72 or below and need to set the iOS deployment target manually. ```bash npx react-native init AmplifyDataStoreRN cd AmplifyDataStoreRN npm install aws-amplify @aws-amplify/react-native @react-native-community/netinfo @react-native-async-storage/async-storage react-native-get-random-values @azure/core-asynciterator-polyfill ``` -------------------------------- ### Install Amplify Library using npm Source: https://docs.amplify.aws/gen1/react-native/build-a-backend/graphqlapi/connect-to-api Installs the Amplify client library, which is recommended for connecting to GraphQL APIs. This command should be run in the root folder of your frontend project. ```bash npm install aws-amplify ``` -------------------------------- ### Configure Storage Access Controls with Amplify CLI Source: https://docs.amplify.aws/gen1/react-native/build-a-backend/auth/user-group-management This example demonstrates configuring access controls for storage resources using the Amplify CLI. It shows how to set permissions for authenticated users, guest users, and specific user groups like 'Admins'. Amplify automatically generates the necessary IAM policies. ```bash amplify add storage # Select content ? Restrict access by? (Use arrow keys) Auth/Guest Users Individual Groups ❯ Both Learn more Who should have access? ❯ Auth and guest users What kind of access do you want for Authenticated users? ❯ create/update, read What kind of access do you want for Guest users? ❯ read Select groups: ❯ Admins What kind of access do you want for Admins users? ❯ create/update, read, delete ``` -------------------------------- ### Get Current User in Route Handler Source: https://docs.amplify.aws/gen1/react-native/build-a-backend/server-side-rendering/nextjs Provides an example of a Next.js API route handler (`GET /apis/get-current-user`) that retrieves the current user's information. It uses `runWithAmplifyServerContext` with request cookies to call the `getCurrentUser` API and returns the user data as JSON. ```javascript import { getCurrentUser } from 'aws-amplify/auth/server'; import { cookies } from 'next/headers'; import { NextResponse } from 'next/server'; import { runWithAmplifyServerContext } from '@/utils/amplifyServerUtils'; export async function GET() { const user = await runWithAmplifyServerContext({ nextServerContext: { cookies }, operation: (contextSpec) => getCurrentUser(contextSpec) }); return NextResponse.json({ user }); } ``` -------------------------------- ### Cloning and Setting Up a New Amplify Sandbox Environment Source: https://docs.amplify.aws/gen1/react-native/tools/cli/teams/sandbox This code snippet demonstrates the initial steps for a team member to clone an Amplify project, create a new sandbox environment, configure backend infrastructure, and push changes to a new Git branch. It involves Git commands for branching and cloning, and Amplify CLI commands for environment management and deployment. ```bash $ git clone $ cd $ git checkout -b mysandbox $ amplify env add ? Do you want to use an existing environment? No ? Enter a name for the environment mysandbox // Rest of init steps // Add/update any backend configurations using amplify add/update $ amplify push $ git push -u origin mysandbox ``` -------------------------------- ### Get Customer Phone Number Source: https://docs.amplify.aws/gen1/react-native/build-a-backend/graphqlapi/best-practice/warehouse-management Retrieves the phone number of a customer using their unique ID. ```APIDOC ## GET /graphql ### Description Fetches a customer's phone number using their unique identifier. ### Method GET (or POST for GraphQL queries) ### Endpoint /graphql ### Parameters #### Query Parameters (for GraphQL request payload) - **query** (string) - Required - The GraphQL query string. - **variables** (object) - Optional - Variables for the query. - **customerID** (ID!) - Required - The unique ID of the customer. ### Request Example ```json { "query": "query getCustomer($customerID: ID!) { getCustomer(id: $customerID) { phoneNumber } }", "variables": { "customerID": "cust789" } } ``` ### Response #### Success Response (200) - **data.getCustomer** (object) - The customer's details. - **phoneNumber** (string) - The customer's phone number. #### Response Example ```json { "data": { "getCustomer": { "phoneNumber": "555-9012" } } } ``` ``` -------------------------------- ### Get Employee Details by ID Source: https://docs.amplify.aws/gen1/react-native/build-a-backend/graphqlapi/best-practice/warehouse-management Retrieves detailed information about an employee using their unique ID. ```APIDOC ## GET /graphql ### Description Fetches an employee's details using their unique identifier. ### Method GET (or POST for GraphQL queries) ### Endpoint /graphql ### Parameters #### Query Parameters (for GraphQL request payload) - **query** (string) - Required - The GraphQL query string. - **variables** (object) - Optional - Variables for the query. - **id** (ID!) - Required - The unique ID of the employee. ### Request Example ```json { "query": "query getEmployee($id: ID!) { getEmployee(id: $id) { id name phoneNumber startDate jobTitle } }", "variables": { "id": "employee123" } } ``` ### Response #### Success Response (200) - **data.getEmployee** (object) - The employee's details. - **id** (string) - The employee's unique ID. - **name** (string) - The employee's full name. - **phoneNumber** (string) - The employee's phone number. - **startDate** (string) - The employee's start date. - **jobTitle** (string) - The employee's job title. #### Response Example ```json { "data": { "getEmployee": { "id": "employee123", "name": "John Doe", "phoneNumber": "555-1234", "startDate": "2022-01-15", "jobTitle": "Software Engineer" } } } ``` ``` -------------------------------- ### Auth.signIn Migration Example (v6) Source: https://docs.amplify.aws/gen1/react-native/build-a-backend/auth/auth-migration-guide Demonstrates the usage of the Auth.signIn API in AWS Amplify v6, showing how to import and call the function, and access the 'isSignedIn' and 'nextStep' properties from the output. ```javascript import { signIn } from 'aws-amplify/auth'; const handleSignIn = async ({ username, password }) => { try { const { isSignedIn, nextStep } = await signIn({ username, password }); // Handle success or next step based on nextStep object } catch (error) { console.error('Sign in failed:', error); // Handle sign in errors } }; ``` -------------------------------- ### Troubleshoot 'Failed to get profile credentials' with AWS IAM Identity Center Source: https://docs.amplify.aws/gen1/react-native/tools/cli/project/troubleshooting This example provides a workaround for the 'Failed to get profile credentials' error when using AWS IAM Identity Center (formerly AWS SSO). It highlights the potential need for a `credential_process` workaround configuration. ```text 🛑 Failed to get profile credentials Cannot read properties of undefined (reading 'accessKeyId') Learn more at: https://docs.amplify.aws/cli/project/troubleshooting/ ``` -------------------------------- ### Amplify CLI Configuration Prompts Source: https://docs.amplify.aws/gen1/react-native/start/getting-started/installation Provides example prompts and user inputs for configuring the Amplify CLI, including specifying the AWS region, entering access key ID, secret access key, and profile name. Follow the console instructions for user creation and key generation. ```bash Specify the AWS Region ? region: # Your preferred region Enter the access key of the newly created user: ? accessKeyId: # YOUR_ACCESS_KEY_ID ? secretAccessKey: # YOUR_SECRET_ACCESS_KEY This would update/create the AWS Profile in your local machine ? Profile Name: # (default) ``` -------------------------------- ### GraphQL Query: Get Recently Hired Employees by Start Date Source: https://docs.amplify.aws/gen1/react-native/tools/cli-legacy/data-access-patterns Retrieves a list of recently hired employees, ordered or filtered by their start date, using a specific query enabled by the `@key` directive. ```graphql query employeesNewHireByDate { employeesNewHireByStartDate(newHire: "true") { items { id name phoneNumber startDate jobTitle } } } ``` -------------------------------- ### Configure Amplify Project with Parameters Source: https://docs.amplify.aws/gen1/react-native/tools/cli/usage/headless Configures Amplify project settings using the `amplify configure project` command, mirroring parameters from `amplify init`. It takes JSON objects for amplify, frontend, and providers configurations, and a --yes flag to skip prompts. ```bash #!/bin/bash set -e IFS='|' REACTCONFIG="{\"SourceDir\":\"src\",\"DistributionDir\":\"build\",\"BuildCommand\":\"npm run-script build\",\"StartCommand\":\"npm run-script start\"}" AWSCLOUDFORMATIONCONFIG="{\"configLevel\":\"project\",\"useProfile\":false,\"profileName\":\"default\",\"accessKeyId\":\"headlessaccesskeyid\",\"secretAccessKey\":\"headlesssecrectaccesskey\",\"region\":\"us-east-1\"}" AMPLIFY="{\"projectName\":\"headlessProjectName\",\"defaultEditor\":\"code\"}" FRONTEND="{\"frontend\":\"javascript\",\"framework\":\"react\",\"config\":$REACTCONFIG}" PROVIDERS="{\"awscloudformation\":$AWSCLOUDFORMATIONCONFIG}" amplify configure project \ --amplify $AMPLIFY \ --frontend $FRONTEND \ --providers $PROVIDERS \ --yes ``` -------------------------------- ### Install Amplify UI for React Native and Dependencies (npm) Source: https://docs.amplify.aws/gen1/react-native/prev/build-a-backend/more-features/in-app-messaging/integrate-application Installs the Amplify UI library for React Native and its specific dependency, react-native-safe-area-context. This UI library simplifies the integration of Amplify features like In-App Messaging. ```bash npm install @aws-amplify/ui-react-native react-native-safe-area-context@^4.2.5 ``` -------------------------------- ### Migrating Amplify Storage Upload: V6 Example Source: https://docs.amplify.aws/gen1/react-native/build-a-backend/storage/storage-v5-to-v6-migration-guide Demonstrates how to perform a file upload using the `uploadData` API in Amplify v6. This example shows importing the function and initiating an upload with a given path and data, awaiting the result. ```javascript import { uploadData } from 'aws-amplify/storage'; const handleUpload = async (path: string, data: string | Blob) => { const operation = uploadData({ path, data }); const result = await operation.result; } ``` -------------------------------- ### Get Customer Orders by Date Range Source: https://docs.amplify.aws/gen1/react-native/build-a-backend/graphqlapi/best-practice/warehouse-management Retrieves all orders for a specific customer within a given date range. ```APIDOC ## GET /graphql ### Description Retrieves orders associated with a specific customer, filtered by a date range. Utilizes a one-to-many relationship and an index on the Order model. ### Method GET (or POST for GraphQL queries) ### Endpoint /graphql ### Parameters #### Query Parameters (for GraphQL request payload) - **query** (string) - Required - The GraphQL query string. - **variables** (object) - Optional - Variables for the query. - **customerID** (ID!) - Required - The unique ID of the customer. - **date** (object) - Required - Predicates for filtering by date. - **between** (array) - Required - An array containing the start and end dates for the range ["YYYY-MM-DD", "YYYY-MM-DD"]. ### Request Example ```json { "query": "query getCustomerWithOrdersByDate($customerID: ID!) { getCustomer(id: $customerID) { ordersByDate(date: { between: [ \"2018-01-22\", \"2020-10-11\" ] }) { items { id amount productID } } } }", "variables": { "customerID": "cust789" } } ``` ### Response #### Success Response (200) - **data.getCustomer.ordersByDate.items** (array) - A list of orders within the specified date range. - **id** (string) - The order ID. - **amount** (float) - The order amount. - **productID** (string) - The ID of the product in the order. #### Response Example ```json { "data": { "getCustomer": { "ordersByDate": { "items": [ { "id": "order001", "amount": 150.75, "productID": "productA" }, { "id": "order002", "amount": 200.00, "productID": "productB" } ] } } } } ``` ``` -------------------------------- ### Initialize Amplify Project Source: https://docs.amplify.aws/gen1/react-native/build-a-backend/more-features/datastore/set-up-datastore Initializes the Amplify project in your local development environment. This command sets up the necessary configuration files and backend resources for Amplify. ```bash amplify init ``` -------------------------------- ### GraphQL Schema Example for Amplify Source: https://docs.amplify.aws/gen1/react-native/tools/cli-legacy/overwrite-customize-resolvers Defines the basic structure for queries, mutations, and subscriptions in an Amplify GraphQL API schema. This serves as a starting point for defining custom operations. ```graphql type Query { # Add all the custom queries here } type Mutation { # Add all the custom mutations here } type Subscription { # Add all the custom subscription here } ``` -------------------------------- ### Set URL Expiration with Get URL (React Native) Source: https://docs.amplify.aws/gen1/react-native/build-a-backend/storage/download Allows limiting the availability of a generated presigned URL using the `expiresIn` option. The example sets the URL to expire in 60 seconds. The maximum expiration is 1 hour. ```javascript import { getUrl } from 'aws-amplify/storage'; await getUrl({ path: 'public/album/2024/1.jpg', // Alternatively, path: ({identityId}) => `protected/${identityId}/album/2024/1.jpg` options: { expiresIn: 60 } }); ``` ```javascript import { getUrl } from 'aws-amplify/storage'; await getUrl({ key: 'album/2024/1.jpg', options: { expiresIn: 60 } }); ``` -------------------------------- ### Initialize Expo Project with Amplify and SQLite (Expo CLI) Source: https://docs.amplify.aws/gen1/react-native/prev/build-a-backend/more-features/datastore/set-up-datastore Initializes an Expo project with Amplify and installs dependencies for SQLite integration with DataStore. This includes the Expo-specific SQLite storage adapter. ```bash npx create-expo-app AmplifyDataStoreExpo cd AmplifyDataStoreExpo npx amplify-app@latest expo install aws-amplify amazon-cognito-identity-js @aws-amplify/datastore-storage-adapter expo-sqlite expo-file-system @react-native-community/netinfo @react-native-async-storage/async-storage @azure/core-asynciterator-polyfill ``` -------------------------------- ### API Gateway Test Response Body Example Source: https://docs.amplify.aws/gen1/react-native/build-a-backend/restapi/test-api This example demonstrates a typical JSON response body from a successful GET request to the /todos endpoint, as seen when testing via the API Gateway console. It confirms the success of the operation and echoes the requested URL. ```JSON { "success": "get call succeed!", "url": "/todos?limit=10" } ``` -------------------------------- ### Start Multi-Container Application Locally with Docker Compose Source: https://docs.amplify.aws/gen1/react-native/tools/cli/usage/containers This command initiates the build process and starts all services defined in the `docker-compose.yml` file. It's used for local testing of multi-container applications, allowing developers to verify functionality before deployment. After starting, the application can be accessed via localhost. ```shell cd ./amplify/backend/api//src docker-compose up curl -i localhost:8080 ## Alternatively open in a web browser ``` -------------------------------- ### Start Amplify App Source: https://docs.amplify.aws/gen1/react-native/build-a-backend/existing-resources/cli This command initiates the development server for the React Native application, allowing you to view and test your changes in real-time. It is a standard command for Node.js projects managed with npm. ```bash npm start ``` -------------------------------- ### List All Inventories Source: https://docs.amplify.aws/gen1/react-native/build-a-backend/graphqlapi/best-practice/warehouse-management Retrieves a list of all inventory records across all products and warehouses. This query is useful for getting a comprehensive overview of all inventory data. ```graphql query listInventorys { listInventorys { items { productID warehouseID inventoryAmount } } } ``` -------------------------------- ### Get Orders for a Product Source: https://docs.amplify.aws/gen1/react-native/build-a-backend/graphqlapi/best-practice/warehouse-management Retrieves all orders associated with a specific product using its ID. This query leverages a one-to-many relationship between products and orders. ```graphql query getProductOrders($productID: ID!) { getProduct(id: $productID) { id orders { items { id status amount date } } } } ``` -------------------------------- ### Install Amplify CLI (curl - Windows) Source: https://docs.amplify.aws/gen1/react-native/build-a-backend/more-features/datastore/set-up-datastore Installs the Amplify CLI using curl for Windows environments. This command downloads an installation script and executes it. ```bash curl -sL https://aws-amplify.github.io/amplify-cli/install-win -o install.cmd && install.cmd ``` -------------------------------- ### Query Recently Hired Employees Source: https://docs.amplify.aws/gen1/react-native/build-a-backend/graphqlapi/best-practice/warehouse-management Query to retrieve employees who have been recently hired, using the `@index` 'newHire'. Results can be further sorted by start date. ```graphql query employeesNewHire { employeesNewHire(newHire: "true") { items { id name phoneNumber startDate jobTitle } } } ``` ```graphql query employeesNewHireByDate { employeesNewHireByStartDate(newHire: "true") { items { id name phoneNumber startDate jobTitle } } } ```