### Clone and Install Project Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/start/quickstart/index.md Use these terminal commands to clone the Amplify Vite React template and install its dependencies. ```bash git clone https://github.com//amplify-vite-react-template.git cd amplify-vite-react-template && npm install ``` -------------------------------- ### Create Amplify Project Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/start/manual-installation/index.md Run this command to start a new Amplify project. ```bash npm create amplify@latest ``` -------------------------------- ### Start Another Sandbox Environment Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/deploy-and-host/sandbox-environments/features/index.md Start a new sandbox environment, specifying a different identifier. ```bash npx ampx sandbox --identifier feature2sandbox ``` -------------------------------- ### Example User Email Input Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/start/account-setup/index.md This shows an example of the expected input for the user's email address. ```text Enter email address: ``` -------------------------------- ### Run Development Server Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/start/quickstart/index.md Execute this command in your terminal to start the development server for your React application. ```bash npm run dev ``` -------------------------------- ### PostgreSQL Connection URI Example Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/build-a-backend/data/connect-to-existing-data-sources/connect-postgres-mysql-database/index.md An example of a connection URI for a PostgreSQL database. Replace placeholders with your actual database credentials and host information. ```text postgres://user:password@hostname:port/db-name ``` -------------------------------- ### Install Amplify Packages Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/build-a-backend/server-side-rendering/index.md Install the necessary AWS Amplify packages for your Next.js project. ```bash npm add aws-amplify @aws-amplify/adapter-nextjs ``` -------------------------------- ### Install TanStack Query Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/build-a-backend/data/optimistic-ui/index.md Install the necessary packages for TanStack Query, which is used for managing server state and implementing optimistic UI. ```bash # Install TanStack Query npm i @tanstack/react-query @tanstack/react-query-devtools ``` -------------------------------- ### Initialize Amplify Sandbox Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/build-a-backend/data/connect-to-existing-data-sources/connect-postgres-mysql-database/index.md Start your Amplify sandbox environment. This command is essential for managing your backend resources locally and testing changes. ```bash npx ampx sandbox ``` -------------------------------- ### Start Amplify Sandbox Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/build-a-backend/data/set-up-data/index.md Use the Amplify Sandbox to locally test your backend resources and data models before deploying. ```bash npx ampx sandbox ``` -------------------------------- ### Start Sandbox Environment with Identifier Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/deploy-and-host/sandbox-environments/features/index.md Initiate a sandbox environment with a custom identifier. This allows for managing multiple sandbox environments distinctly. ```bash npx ampx sandbox --identifier feature1sandbox ``` -------------------------------- ### MySQL Connection URI Example Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/build-a-backend/data/connect-to-existing-data-sources/connect-postgres-mysql-database/index.md An example of a connection URI for a MySQL database. Replace placeholders with your actual database credentials and host information. ```text mysql://user:password@hostname:port/db-name ``` -------------------------------- ### Create Amplify Project Source: https://github.com/aws-amplify/amplify-data/blob/main/README.md Use this command to create a new AWS Amplify project. This is the starting point for setting up Amplify. ```bash npm create amplify@latest ``` -------------------------------- ### Get Post Query in React App Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/build-a-backend/data/connect-to-existing-data-sources/connect-external-ddb-table/index.md Example of calling the `getPost` query from a React application using the Amplify client. This shows how to pass the `id` of the post to retrieve. ```typescript const { data, errors } = await client.queries.getPost({ id: "", }); ``` -------------------------------- ### Add AWS Amplify to Project Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/build-a-backend/data/set-up-data/index.md Install the AWS Amplify library into your project using npm. ```bash npm add aws-amplify ``` -------------------------------- ### Install Amplify Backend Dependencies Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/start/manual-installation/index.md Add the necessary Amplify backend packages and TypeScript as development dependencies. ```bash npm add --save-dev @aws-amplify/backend@latest @aws-amplify/backend-cli@latest typescript ``` -------------------------------- ### Prompt for User Email Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/start/account-setup/index.md This snippet prompts the user to enter their email address for account setup. ```bash read -p "Enter email address: " user_email # hit enter ``` -------------------------------- ### Display Session Start URL and Credentials Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/start/account-setup/index.md This snippet prints the session start URL, AWS region, and username for accessing the AWS console. ```bash printf "\n\nStart session url: https://$ssoId.awsapps.com/start\nRegion: $AWS_REGION\nUsername: amplify-admin\n\n" # you should see Start session url: https://d-XXXXXXXXXX.awsapps.com/start Region: us-east-1 Username: amplify-admin ``` -------------------------------- ### Install AWS CLI v2 Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/start/account-setup/index.md This snippet downloads, unzips, and installs the AWS CLI version 2 on a Linux system. ```bash curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip" unzip awscliv2.zip ./aws/install -i /usr/local/aws-cli -b /usr/local/bin ``` -------------------------------- ### Amplify Data and React Query Setup Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/build-a-backend/data/optimistic-ui/index.md Configures Amplify with provided outputs and sets up React Query for data fetching and state management. Includes React Query Devtools for debugging. ```jsx import React from "react"; import ReactDOM from "react-dom/client"; import App from "./App.tsx"; import "./index.css"; import { Amplify } from "aws-amplify"; import outputs from "../amplify_outputs.json"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { ReactQueryDevtools } from "@tanstack/react-query-devtools"; Amplify.configure(outputs); export const queryClient = new QueryClient(); ReactDOM.createRoot(document.getElementById("root")!).render( , ); ``` -------------------------------- ### Amplify Client Initialization and Auth Setup Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/start/quickstart/index.md This React code snippet shows how to configure Amplify with backend outputs and wrap the App component with an Authenticator for authentication. ```tsx import React from "react"; import ReactDOM from "react-dom/client"; import { Authenticator } from "@aws-amplify/ui-react"; import { Amplify } from "aws-amplify"; import App from "./App.tsx"; import outputs from "../amplify_outputs.json"; import "./index.css"; import "@aws-amplify/ui-react/styles.css"; Amplify.configure(outputs); ReactDOM.createRoot(document.getElementById("root")!).render( , ); ``` -------------------------------- ### Client-side Like Post Mutation Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/build-a-backend/data/custom-business-logic/index.md Example of invoking the 'likePost' mutation from the client. This shows how to pass arguments to a custom mutation and handle the response. ```javascript const { data, errors } = await client.mutations.likePost({ postId: "hello", }); ``` -------------------------------- ### List and Get Items with Amplify Data Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/build-a-backend/data/query-data/index.md Use `client.models.Todo.list()` to retrieve all items and `client.models.Todo.get()` to fetch a specific item by its ID. Ensure you have initialized the Amplify client with your schema. ```javascript import { generateClient } from "aws-amplify/data"; import { type Schema } from "@/amplify/data/resource"; const client = generateClient(); // list all items const { data: todos, errors } = await client.models.Todo.list(); // get a specific item const { data: todo, errors } = await client.models.Todo.get({ id: "...", }); ``` -------------------------------- ### Client-side Mutation Call Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/build-a-backend/data/custom-business-logic/index.md Example of how to call the `likePost` mutation from the Amplify client. ```APIDOC ## Client-side Mutation Call This snippet demonstrates how to invoke the `likePost` mutation using the Amplify client. ```javascript const { data, errors } = await client.mutations.likePost({ postId: "hello", }); ``` ``` -------------------------------- ### Client-side Echo Query Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/build-a-backend/data/custom-business-logic/index.md Example of making an 'echo' query to the Amplify backend using the client library. This demonstrates how to call a query defined in the schema. ```javascript const { data, errors } = await client.queries.echo({ content: "hello world!!!", }); ``` -------------------------------- ### Amplify Gen 2 CI/CD Pipeline Commands Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/deploy-and-host/fullstack-branching/cross-account-deployments/index.md Set the CI environment variable, install dependencies, deploy the backend, and trigger frontend builds for Amplify Gen 2 applications. ```bash export CI=1 ``` ```bash npm ci ``` ```bash npx ampx pipeline-deploy --branch $AWS_BRANCH --app-id $AWS_APP_ID ``` ```bash if [ $AWS_BRANCH = "main" ]; then curl -X POST -d {} "`webhookUrl`&operation=startbuild" -H "Content-Type:application/json"; fi ``` -------------------------------- ### Create a Todo item with API Key authentication Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/build-a-backend/data/mutate-data/index.md When creating or mutating data, you can specify the `authMode` option. This example uses `apiKey` for authentication. ```javascript import { generateClient } from "aws-amplify/data"; import { type Schema } from "../amplify/data/resource"; const client = generateClient(); const { errors, data: newTodo } = await client.models.Todo.create( { content: "My new todo", isDone: true, }, { authMode: "apiKey", }, ); ``` -------------------------------- ### Bash Script for Running E2E Tests Source: https://github.com/aws-amplify/amplify-data/blob/main/packages/e2e-tests/README.md Use these scripts to install dependencies and run the E2E tests, ensuring that a package-lock file is not generated. ```bash npm run e2e ``` -------------------------------- ### Create Next.js App for Multi-Repo Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/deploy-and-host/fullstack-branching/mono-and-multi-repos/index.md Use this command to create a new Next.js application configured for a multi-repo setup. It disables certain default configurations like app directory and source directory. ```bash npm create next-app@14 -- multi-repo-example --typescript --eslint --no-app --no-src-dir --no-tailwind --import-alias '@/*' ``` -------------------------------- ### Fetch Image URL on Server for Static Rendering Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/build-a-backend/server-side-rendering/index.md Use `getUrl` from `aws-amplify/storage/server` to fetch a file's URL on the server. This example is suitable for pages that can be statically rendered with revalidation. ```typescript import { getUrl } from "aws-amplify/storage/server"; import Image from "next/image"; import { runWithAmplifyServerContext } from "@/utils/amplifyServerUtils"; // Re-render this page every 60 minutes export const revalidate = 60 * 60; // in seconds export default async function StaticallyRenderedPage() { try { const splashUrl = await runWithAmplifyServerContext({ nextServerContext: null, operation: (contextSpec) => getUrl(contextSpec, { key: "splash.png", }), }); return ( Splash Image ); } catch (error) { console.error(error); return

Something went wrong...

; } } ``` -------------------------------- ### Amplify CI/CD Pipeline Configuration Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/deploy-and-host/fullstack-branching/mono-and-multi-repos/index.md This `amplify.yml` file configures the CI/CD pipeline for Amplify, specifying build commands for the backend and frontend, including a webhook for starting builds. ```yaml version: 1 backend: phases: build: commands: - npm ci --cache .npm --prefer-offline - npx ampx pipeline-deploy --branch $AWS_BRANCH --app-id $AWS_APP_ID frontend: phases: build: commands: - mkdir ./dist && touch ./dist/index.html - curl -X POST -d {} "https://webhooks.amplify.ca-central-1.amazonaws.com/prod/webhooks?id=WEBHOOK-ID&token=TOKEN&operation=startbuild" -H "Content-Type:application/json" artifacts: baseDirectory: dist files: - '**/*' cache: paths: - node_modules/**/* ``` -------------------------------- ### Example Schema and Inferred Enum Client Type Source: https://github.com/aws-amplify/amplify-data/blob/main/packages/data-schema-types/docs/data-schema-types.enumtypes.md Illustrates a sample schema defining a 'TodoStatus' enum and the corresponding inferred interface for the `client.enums` property, showing how to access enum values. ```typescript // The schema: { TodoStatus: a.enum(['Planned' | 'InProgress' | 'Completed']), } // The inferred interface of the `client.enums`: { TodoStatus: { values: () => Array<'Planned' | 'InProgress' | 'Completed'>; } } ``` -------------------------------- ### Get Current User in Next.js API Route Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/build-a-backend/server-side-rendering/index.md Fetch the current authenticated user within a Next.js API route using `getCurrentUser` from `aws-amplify/auth/server`. This example utilizes server context with cookies for authentication. ```typescript 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 }); } ``` -------------------------------- ### Get Current User in Nuxt API Route Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/build-a-backend/data/connect-from-server-runtime/nuxtjs-server-runtime/index.md An example of an API route in Nuxt.js that retrieves the current authenticated user using Amplify's server-side capabilities. It utilizes the `runAmplifyApi` utility to establish the server context and then calls `getCurrentUser`. ```typescript import { getCurrentUser } from "aws-amplify/auth/server"; import { runAmplifyApi } from "~/server/utils/amplifyUtils"; export default defineEventHandler(async (event) => { const user = await runAmplifyApi(event, (contextSpec) => getCurrentUser(contextSpec), ); return user; }); ``` -------------------------------- ### Define a Custom Subscription Source: https://github.com/aws-amplify/amplify-data/blob/main/packages/data-schema/docs/data-schema.a.subscription.md Use `a.subscription()` to create a custom subscription. Specify the mutation to subscribe to using `.for()`, define custom event handling with `.handler()`, and set access controls with `.authorization()`. This example shows subscribing to a 'publish' mutation with public API key authorization. ```typescript a.subscription() // subscribes to the 'publish' mutation .for(a.ref('publish')) // subscription handler to set custom filters .handler(a.handler.custom({ entry: './receive.js' })) // authorization rules as to who can subscribe to the data .authorization(allow => [ allow.publicApiKey() ]), ``` -------------------------------- ### Create Todo with Amplify Data Client Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/deploy-and-host/fullstack-branching/monorepos/index.md Example of creating a new Todo item using the Amplify Data client in a React application. Ensure the Schema type is imported and the client is generated with the correct schema. ```typescript import { generateClient } from "aws-amplify/data"; import type { Schema } from "@/data-schema"; const client = generateClient(); const createTodo = async () => { await client.models.Todo.create({ content: window.prompt("Todo content?"), isDone: false, }); }; ``` -------------------------------- ### Configure AWS SSO via CLI Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/start/account-setup/index.md This interactive terminal session demonstrates how to configure AWS Single Sign-On (SSO) using the AWS CLI, including setting the SSO session name, start URL, and region. ```bash aws configure sso | SSO session name (Recommended): amplify-admin | SSO start URL: | SSO region: | SSO registration scopes [sso:account:access]: | Attempting to automatically open the SSO authorization page in your default browser. | If the browser does not open or you wish to use a different device to authorize this request, open the following URL: | | https://device.sso.us-east-2.amazonaws.com/ | | Then enter the code: | | SOME-CODE ## browser opens ``` -------------------------------- ### Amplify Sandbox with Profile Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/start/account-setup/index.md Launch the Amplify sandbox, explicitly providing the profile name to use for the operation. ```bash npx ampx sandbox --profile ``` -------------------------------- ### Enum Value Assignment Example Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/build-a-backend/data/data-modeling/add-fields/index.md Demonstrates assigning a valid enum value ('PRIVATE') to the `privacySetting` field during model creation. Includes a commented-out example of an invalid assignment ('NOT_PUBLIC') that would result in a type error. ```javascript client.models.Post.create({ content: "hello", // WORKS - value auto-completed privacySetting: "PRIVATE", // DOES NOT WORK - TYPE ERROR privacySetting: "NOT_PUBLIC", }); ``` -------------------------------- ### Run Individual Bench File Source: https://github.com/aws-amplify/amplify-data/blob/main/packages/benches/README.md Builds the data-schema and data-schema-types packages, then executes a specified bench file. ```bash yarn bench:file file_name ``` -------------------------------- ### Get Post Handler for External Table Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/build-a-backend/data/connect-to-existing-data-sources/connect-external-ddb-table/index.md Implement the `request` and `response` functions for retrieving a post from an external DynamoDB table. The `request` function performs a DynamoDB `get` operation using the provided `id`. The `response` function returns the retrieved item. ```javascript import * as ddb from "@aws-appsync/utils/dynamodb"; export function request(ctx) { return ddb.get({ key: { id: ctx.args.id } }); } export const response = (ctx) => ctx.result; ``` -------------------------------- ### Confirm Project Creation Location Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/start/manual-installation/index.md Press Enter to confirm the current directory for project creation. ```bash ? Where should we create your project? (.) # press enter ``` -------------------------------- ### Configure amplify.yml for PR Previews Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/deploy-and-host/fullstack-branching/pr-previews/index.md This `amplify.yml` configuration defines build and deployment phases. It includes logic to deploy different branches (main, dev, PRs, staging) using `ampx` commands. PR branches trigger `ampx generate outputs` to prepare for preview. ```yaml version: 1 backend: phases: build: commands: - 'npm ci --cache .npm --prefer-offline' - 'echo $AWS_BRANCH' - | case "${AWS_BRANCH}" in main) echo "Deploying main branch..." npx ampx pipeline-deploy --branch $AWS_BRANCH --app-id $AWS_APP_ID ;; dev) echo "Deploying dev branch..." npx ampx pipeline-deploy --branch $AWS_BRANCH --app-id $AWS_APP_ID ;; pr-*) echo "Deploying pull request branch..." npx ampx generate outputs --branch dev --app-id $AWS_APP_ID ;; *) echo "Deploying to staging branch..." npx ampx generate outputs --branch staging --app-id $AWS_APP_ID ;; esac frontend: phases: build: commands: - 'npm run build' artifacts: baseDirectory: .amplify-hosting files: - '**/*' cache: paths: - .next/cache/**/* - .npm/**/* - node_modules/**/* ``` -------------------------------- ### Interact with Data Models using Amplify Client Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/how-amplify-works/concepts/index.md Demonstrates how to generate a data client and perform operations like listing and creating messages. ```javascript // generate your data client using the Schema from your backend const client = generateClient(); // list all messages const { data } = await client.models.Message.list(); // create a new message const { errors, data: newMessage } = await client.models.Message.create({ text: "My message text", }); ``` -------------------------------- ### Configure Sandbox Outputs Directory and Format Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/deploy-and-host/sandbox-environments/features/index.md Specify the output directory and desired formats (e.g., JSON, Dart) for sandbox environment configurations. ```bash npx ampx sandbox --outputs-out-dir ./path/to/config --outputs-format ["json", "dart"] ``` -------------------------------- ### Launch Amplify Sandbox Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/start/account-setup/index.md Initiate the Amplify sandbox environment. You can specify a particular AWS profile if you have multiple configured. ```bash npx ampx sandbox ``` ```bash npx ampx sandbox --profile ``` -------------------------------- ### ExcludeEmpty Type Example Source: https://github.com/aws-amplify/amplify-data/blob/main/packages/data-schema-types/docs/data-schema-types.excludeempty.md Demonstrates how ExcludeEmpty filters out an empty object type from a union of object types. ```typescript ExcludeEmpty<{a: 1} | {} | {b: 2}> = {a: 1} | {b: 2} ``` -------------------------------- ### DefineFunction Type Source: https://github.com/aws-amplify/amplify-data/blob/main/packages/data-schema-types/docs/data-schema-types.definefunction.md Defines the structure for a serverless function, including its optional provider and a method to get its instance. ```APIDOC ## DefineFunction Type ### Description Represents a serverless function definition. It can optionally specify a provider and includes a method to retrieve its instance. ### Type Definition ```typescript export type DefineFunction = { readonly provides?: string | undefined; getInstance: (props: any) => any; }; ``` ### Properties * **provides** (string | undefined) - Optional. Specifies the provider for the function. * **getInstance** ((props: any) => any) - Required. A function that takes properties and returns the function instance. ``` -------------------------------- ### Get Cart and Associated Customer Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/build-a-backend/data/data-modeling/relationships/index.md Retrieves a cart by its ID and then accesses the associated customer data through a relationship field. ```javascript const { data: cart } = await client.models.Cart.get({ id: "MY_CART_ID" }); const { data: customer } = await cart.customer(); ``` -------------------------------- ### Initialize Amplify Backend Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/start/manual-installation/index.md Import and call defineBackend to initialize the Amplify backend configuration. ```typescript import { defineBackend } from "@aws-amplify/backend"; defineBackend({}); ``` -------------------------------- ### Get Post and Associated Author/Editor Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/build-a-backend/data/data-modeling/relationships/index.md Retrieves a post by its ID and then accesses its associated author and editor data through relationship fields. ```javascript const client = generateClient(); const { data: post } = await client.models.Post.get({ id: "SOME_POST_ID" }); const { data: author } = await post?.author(); const { data: editor } = await post?.editor(); ``` -------------------------------- ### List Todos with API Key Authentication Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/build-a-backend/data/connect-to-API/index.md Use `client.models.Todo.list` with `authMode: "apiKey"` to fetch data when using API key authentication. ```javascript const { data: todos, errors } = await client.models.Todo.list({ authMode: "apiKey", }); ``` -------------------------------- ### UnionToIntersection Example Source: https://github.com/aws-amplify/amplify-data/blob/main/packages/data-schema-types/docs/data-schema-types.uniontointersection.md Demonstrates how UnionToIntersection transforms a union of object types into an intersection. This results in a type that has all properties from all types in the original union. ```typescript UnionToIntersection<{a: 1} | {b: 2}> = {a: 1} & {b: 2} ``` -------------------------------- ### SetTypeSubArg Example Source: https://github.com/aws-amplify/amplify-data/blob/main/packages/data-schema-types/docs/data-schema-types.settypesubarg.md Illustrates how to use SetTypeSubArg to modify a type by replacing the type of the 'identifier' key from an array of strings to a specific string. ```APIDOC ## Example T = { fields: {}, identifier: "id"[] } type Modified = SetTypeSubArg // Modified = { fields: {}, identifier: "customId"[] } ``` -------------------------------- ### List Todos with Lambda Authentication Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/build-a-backend/data/connect-to-API/index.md Use `client.models.Todo.list` with `authMode: "lambda"` and provide a `authToken` for authentication via a Lambda authorizer. ```javascript const getAuthToken = () => "myAuthToken"; const lambdaAuthToken = getAuthToken(); const { data: todos, errors } = await client.models.Todo.list({ authMode: "lambda", authToken: lambdaAuthToken, }); ``` -------------------------------- ### Project Structure Overview Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/start/quickstart/index.md This snippet illustrates the typical file and folder structure for an Amplify project with a React frontend. ```tree ├── amplify/ # Folder containing your Amplify backend configuration │ ├── auth/ # Definition for your auth backend │ │ └── resource.tsx │ ├── data/ # Definition for your data backend │ │ └── resource.ts │ ├── backend.ts │ └── tsconfig.json ├── src/ # React UI code │ ├── App.tsx # UI code to sync todos in real-time │ ├── index.css # Styling for your app │ └── main.tsx # Entrypoint of the Amplify client library ├── package.json └── tsconfig.json ``` -------------------------------- ### Integrate Data into React App Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/start/quickstart/index.md Example of how to use the `useAuthenticator` hook in a React component to display user information and integrate with Amplify Data. ```typescript // ... imports function App() { const { user, signOut } = useAuthenticator(); // ... return (

{user?.signInDetails?.loginId}'s todos

{/* ... */}
); } ``` -------------------------------- ### Configure Amplify with Outputs Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/reference/amplify_outputs/index.md Configure the Amplify client in your application's entry point using the generated outputs. This step is essential for connecting your frontend to your backend resources. ```typescript import { Amplify } from "aws-amplify"; import outputs from "@/amplify_outputs.json"; Amplify.configure(outputs); ``` -------------------------------- ### Basic Amplify Project Structure Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/reference/project-structure/index.md This snippet illustrates the fundamental directory structure of an Amplify project, including the amplify/ directory for backend configurations. ```tree ├── amplify/ │ ├── auth/ │ │ └── resource.ts │ ├── data/ │ │ └── resource.ts │ ├── backend.ts │ └── package.json ├── node_modules/ ├── .gitignore ├── package-lock.json ├── package.json └── tsconfig.json ``` -------------------------------- ### ModelPath Example Usage Source: https://github.com/aws-amplify/amplify-data/blob/main/packages/data-schema-types/docs/data-schema-types.modelpath.md Illustrates how the ModelPath type can be used to define a selection set for a given flat model structure, including nested arrays. ```typescript FlatModel = { id: string title: string comments: { id:: string content: string }[] } // Result // 'id' | 'title' | 'comments.*' | 'comments.id' | 'comments.content' ``` -------------------------------- ### Define a hasOne Relationship Source: https://github.com/aws-amplify/amplify-data/blob/main/packages/data-schema/docs/data-schema.a.hasone.md Use `a.hasOne()` to create a one-to-one relationship. This example shows a `Customer` model having one `Cart`, referencing the `customerId` field. ```typescript const schema = a.schema({ Cart: a.model({ items: a.string().required().array(), // 1. Create reference field customerId: a.id(), // 2. Create relationship field with the reference field customer: a.belongsTo('Customer', 'customerId'), }), Customer: a.model({ name: a.string(), // 3. Create relationship field with the reference field // from the Cart model activeCart: a.hasOne('Cart', 'customerId') }), }); ``` -------------------------------- ### Generate Client with Custom Static Headers Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/build-a-backend/data/connect-to-API/index.md Initialize the Amplify Data client with custom static headers by providing a `headers` object during `generateClient` configuration. ```javascript import type { Schema } from "../amplify/data/resource"; import { generateClient } from "aws-amplify/data"; const client = generateClient({ headers: { "My-Custom-Header": "my value", }, }); ``` -------------------------------- ### Connect with Custom SSL Certificate Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/build-a-backend/data/connect-to-existing-data-sources/connect-postgres-mysql-database/index.md This command sequence demonstrates how to set a custom SSL certificate secret and then generate the schema using that secret for a secure connection. ```bash npx ampx sandbox secret set CUSTOM_SSL_CERT < /path/to/custom/ssl/public-ca-cert.pem npx ampx generate schema-from-database --connection-uri-secret SQL_CONNECTION_STRING --ssl-cert-secret CUSTOM_SSL_CERT --out amplify/data/schema.sql.ts ``` -------------------------------- ### Get Image for Current Song Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/build-a-backend/data/working-with-files/index.md Retrieves and displays the image associated with the current song. This function requires a selected song and a current image URL. ```typescript async function getImageForCurrentSong() { if (!currentSong || !currentImageUrl) return; try { // Get the signed URL for the image const imageURL = await Storage.get(currentImageUrl); setCurrentImageUrl(imageURL); } catch (error) { console.error("Error getting image for current song: ", error); } } ``` -------------------------------- ### Bootstrap CDK with AWS CLI Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/build-a-backend/troubleshooting/stack-cdktoolkit-already-exists/index.md Use this command to bootstrap the AWS CDK, specifying your AWS account ID and region. This is useful when the CDKToolkit stack already exists in your current environment. ```bash cdk bootstrap aws://$(aws sts get-caller-identity --query Account --output text)/$AWS_REGION ``` -------------------------------- ### Bootstrap CDK with npx Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/build-a-backend/troubleshooting/stack-cdktoolkit-already-exists/index.md Execute this command using npx to bootstrap the AWS CDK. Replace placeholders with your actual AWS account ID and region. This command is an alternative to using the AWS CLI directly for bootstrapping. ```bash npx aws-cdk@latest bootstrap aws:/// ``` -------------------------------- ### Define Amplify Data Schema Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/start/quickstart/index.md Define your data models and authorization rules in the `resource.ts` file. This example shows a simple 'Todo' model with owner authorization. ```typescript import { type ClientSchema, a, defineData } from "@aws-amplify/backend"; const schema = a.schema({ Todo: a .model({ content: a.string(), }) .authorization((allow) => [allow.owner()]) }); export type Schema = ClientSchema; export const data = defineData({ schema, authorizationModes: { // This tells the data client in your app (generateClient()) // to sign API requests with the user authentication token. defaultAuthorizationMode: "userPool", }, }); ``` -------------------------------- ### Initialize Amplify Backend with Auth, Data, and Location Resources Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/how-amplify-works/concepts/index.md Initializes the Amplify backend configuration, integrating defined authentication, data, and location map resources. ```typescript import { Backend } from "@aws-amplify/backend"; import { auth } from "./auth/resource"; import { data } from "./data/resource"; import { LocationMapStack } from "./locationMapStack/resource"; const backend = new Backend({ auth, data, }); new LocationMapStack( backend.getStack("LocationMapStack"), "myLocationResource", {}, ); ``` -------------------------------- ### Run Groups of Benches Source: https://github.com/aws-amplify/amplify-data/blob/main/packages/benches/README.md Builds the library packages and runs all bench files within a specified directory. ```bash yarn bench:basic ``` ```bash yarn bench:p50 ``` ```bash yarn bench:p99 ``` ```bash yarn bench:all ``` -------------------------------- ### Publish a Message via Custom Subscription Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/build-a-backend/data/custom-subscription/index.md Publishes a message to the 'world' channel using the 'publish' mutation. This demonstrates how to send data through the custom subscription setup. ```javascript client.mutations.publish({ channelName: "world", content: "My first message!", }); ``` -------------------------------- ### Define a Custom Mutation Source: https://github.com/aws-amplify/amplify-data/blob/main/packages/data-schema/docs/data-schema.a.mutation.md Use `a.mutation()` to start defining a custom mutation. Configure arguments, return types, authorization, and handlers to specify the mutation's behavior. ```typescript likePost: a.mutation() .arguments({ postId: a.string() }) .returns(a.ref('Post')) .authorization(allow => [ allow.publicApiKey() ]) .handler(a.handler.function(echoHandler)) ``` -------------------------------- ### Configure Amplify with Guest Access Enabled Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/build-a-backend/data/customize-authz/public-data-access/index.md Configure Amplify in your application to allow guest access. This is necessary when using authorization rules like `allow.guest()` in your data models. ```typescript import { Amplify } from "aws-amplify"; import outputs from "../amplify_outputs.json"; Amplify.configure({ ...outputs, Auth: { Cognito: { identityPoolId: config.aws_cognito_identity_pool_id, userPoolClientId: config.aws_user_pools_web_client_id, userPoolId: config.aws_user_pools_id, allowGuestAccess: true, }, }, }); ``` -------------------------------- ### Define Auth with Secrets Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/deploy-and-host/fullstack-branching/secrets-and-vars/index.md Integrate secrets into your Amplify backend definition, for example, to configure external authentication providers. Ensure secrets are defined using the `secret()` function. ```typescript import { defineAuth, secret } from "@aws-amplify/backend"; export const auth = defineAuth({ loginWith: { email: true, externalProviders: { facebook: { clientId: secret("foo"), clientSecret: secret("bar"), }, }, }, }); ``` -------------------------------- ### Amplify Project File Structure Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/start/quickstart/index.md This snippet shows the essential files and directories in an Amplify project, including the backend outputs. ```tree ├── amplify ├── src ├── amplify_outputs.json <== backend outputs file ├── package.json └── tsconfig.json ``` -------------------------------- ### Filter List Items with OR Condition Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/build-a-backend/data/query-data/index.md Combine multiple filter conditions using the `or` operator. This example fetches items that match either priority '1' or priority '2'. ```javascript import { generateClient } from "aws-amplify/data"; import { type Schema } from "@/amplify/data/resource"; const client = generateClient(); const { data: todos, errors } = await client.models.Todo.list({ filter: { or: [ { priority: { eq: "1" }, }, { priority: { eq: "2" }, }, ], }, }); ``` -------------------------------- ### Fetch Blog with Custom Static Headers Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/build-a-backend/data/connect-to-API/index.md Include custom static headers in a specific model operation like `client.models.Blog.get` by passing them in the options object. ```javascript // same way for all CRUDL: .create, .get, .update, .delete, .list, .observeQuery const { data: blog, errors } = await client.models.Blog.get( { id: "myBlogId" }, { headers: { "My-Custom-Header": "my value", }, }, ); ``` -------------------------------- ### Delete Post Mutation in React App Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/build-a-backend/data/connect-to-existing-data-sources/connect-external-ddb-table/index.md Example of calling the `deletePost` mutation from a React application using the Amplify client. This shows how to pass the `id` of the post to delete. ```typescript const { data, errors } = await client.mutations.deletePost({ id: "", }); ``` -------------------------------- ### Add Post to Blog and Notify Subscribers Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/build-a-backend/data/subscribe-data/index.md This function demonstrates how to create a new post and then 'touch' the associated blog to notify subscribers of changes. It's crucial to include the correct `selectionSet` in the blog update if your subscriptions are looking for related-model fields. ```javascript async function addPostToBlog( post: Schema["Post"]["createType"], blog: Schema["Blog"]["type"], ) { // Create the post first. await client.models.Post.create({ ...post, blogId: blog.id, }); // "Touch" the blog, notifying subscribers to re-render. await client.models.Blog.update( { id: blog.id, }, { // Remember to include the selection set if the subscription // is looking for related-model fields! selectionSet: [...selectionSet], }, ); } ``` -------------------------------- ### Cancel a promise-based API call Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/build-a-backend/data/mutate-data/index.md This example shows how to cancel a promise returned from an async function. Note that calling `client.cancel` on a promise that has already resolved or rejected will have no effect. ```javascript async function makeAPICall() { return client.models.Todo.create({ content: "New Todo" }); } const promise = makeAPICall(); // The following will NOT cancel the request. client.cancel(promise, "my error message"); ``` -------------------------------- ### Get Cart with Customer Selection Set Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/build-a-backend/data/data-modeling/relationships/index.md Retrieves a cart by its ID, specifically selecting the customer's ID. It then logs the customer's ID from the cart object. ```javascript const { data: cart } = await client.models.Cart.get( { id: "MY_CART_ID" }, { selectionSet: ["id", "customer.*"] }, ); console.log(cart.customer.id); ``` -------------------------------- ### Fetch Blog with Dynamic Headers Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/build-a-backend/data/connect-to-API/index.md Dynamically generate headers for a specific model operation like `client.models.Blog.get` by providing an async function to the `headers` option within the operation's options. ```javascript // same way for all CRUDL: .create, .get, .update, .delete, .list, .observeQuery const res = await client.models.Blog.get( { id: "myBlogId" }, { headers: async (requestOptions) => { console.log(requestOptions); /* The request options allow you to customize your headers based on the request options such as http method, headers, request URI, and query string. These options are typically used to create a request signature. { method: '...', headers: { }, uri: '/', queryString: "" } */ return { "My-Custom-Header": "my value", }; }, }, ); ``` -------------------------------- ### Filter List Items by Content Prefix Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/build-a-backend/data/query-data/index.md Filter query results using the `filter` option. This example shows how to retrieve items where the `content` field begins with a specific string. ```javascript import { generateClient } from "aws-amplify/data"; import { type Schema } from "@/amplify/data/resource"; const client = generateClient(); const { data: todos, errors } = await client.models.Todo.list({ filter: { content: { beginsWith: "hello", }, }, }); ``` -------------------------------- ### Create Amplify Server Runner Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/build-a-backend/server-side-rendering/index.md Initialize the Amplify server runner with your Amplify configuration outputs. This is essential for server-side operations. ```typescript import { createServerRunner } from "@aws-amplify/adapter-nextjs"; import outputs from "@/amplify_outputs.json"; export const { runWithAmplifyServerContext } = createServerRunner({ config: outputs, }); ``` -------------------------------- ### Add Post Mutation in React App Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/build-a-backend/data/connect-to-existing-data-sources/connect-external-ddb-table/index.md Example of calling the `addPost` mutation from a React application using the Amplify client. This demonstrates how to pass arguments for title, content, and author. ```typescript const { data, errors } = await client.mutations.addPost({ title: "My Post", content: "My Content", author: "Chris", }); ``` -------------------------------- ### Get Sandbox Secret Value Source: https://github.com/aws-amplify/amplify-data/blob/main/coverages/docs-site/docs-page/react/deploy-and-host/sandbox-environments/features/index.md Retrieve the value of a specific secret from the sandbox environment. The output includes the secret's name, version, value, and last updated timestamp. ```bash npx ampx sandbox secret get foo name: foo version: 1 value: abc123 lastUpdated: Mon Nov 13 2023 22:19:12 GMT-0800 (Pacific Standard Time) ```