Skip to content
English
On this page

Ejercicio: Aplicación Web Full-Stack con AWS Amplify, AppSync y X-Ray

Objetivo

Crear una aplicación de notas que permita:

  • CRUD de notas
  • Autenticación de usuarios
  • Monitoreo de rendimiento
  • Trazabilidad de solicitudes

Parte 1: Configuración Inicial

1. Preparar Ambiente de Desarrollo

bash
# Instalar Amplify CLI
npm install -g @aws-amplify/cli

# Configurar Amplify
amplify configure
# Seguir pasos de configuración de usuario IAM

# Crear proyecto React
npx create-react-app notes-app
cd notes-app

# Instalar dependencias
npm install aws-amplify @aws-amplify/ui-react

2. Inicializar Amplify en el Proyecto

bash
# Inicializar Amplify
amplify init

? Enter a name for the project: notesapp
? Enter a name for the environment: dev
? Choose your default editor: Visual Studio Code
? Choose the type of app that you're building: javascript
? What javascript framework are you using: react
? Source Directory Path: src
? Distribution Directory Path: build
? Build Command: npm run build
? Start Command: npm start

Parte 2: Configurar Authentication y API

1. Añadir Autenticación

bash
amplify add auth

? Do you want to use the default authentication and security configuration? Default configuration
? How do you want users to be able to sign in? Username
? Do you want to configure advanced settings? No

2. Añadir API GraphQL con AppSync

bash
amplify add api

? Please select from one of the below mentioned services: GraphQL
? Provide API name: NotesAPI
? Choose the default authorization type for the API: Amazon Cognito User Pool
? Do you want to configure advanced settings for the GraphQL API: Yes
? Configure additional auth types? No
? Enable conflict detection? Yes
? Select the default resolution strategy: Auto Merge
? Do you want to enable X-Ray tracing on the API? Yes

3. Definir Schema GraphQL

graphql
# schema.graphql
type Note @model @auth(rules: [{ allow: owner }]) {
  id: ID!
  title: String!
  content: String!
  createdAt: AWSDateTime!
  updatedAt: AWSDateTime!
  owner: String
}

Parte 3: Desarrollo de la Aplicación

1. Configurar Amplify en la Aplicación (src/index.js)

javascript
import { Amplify } from 'aws-amplify';
import awsconfig from './aws-exports';
import { AmplifyProvider } from '@aws-amplify/ui-react';
import '@aws-amplify/ui-react/styles.css';

Amplify.configure(awsconfig);

2. Crear Componente Principal (src/App.js)

javascript
import React, { useState, useEffect } from 'react';
import { 
  withAuthenticator,
  Button,
  Heading,
  View,
  TextField 
} from '@aws-amplify/ui-react';
import { API, graphqlOperation } from 'aws-amplify';
import { createNote, deleteNote, updateNote } from './graphql/mutations';
import { listNotes } from './graphql/queries';
import { onCreateNote, onDeleteNote, onUpdateNote } from './graphql/subscriptions';

function App({ signOut }) {
  const [notes, setNotes] = useState([]);
  const [formData, setFormData] = useState({ title: '', content: '' });

  useEffect(() => {
    fetchNotes();
    subscribeToNotes();
  }, []);

  async function fetchNotes() {
    try {
      const noteData = await API.graphql(graphqlOperation(listNotes));
      setNotes(noteData.data.listNotes.items);
    } catch (err) {
      console.error('Error fetching notes:', err);
    }
  }

  function subscribeToNotes() {
    API.graphql(graphqlOperation(onCreateNote)).subscribe({
      next: ({ value }) => {
        setNotes(notes => [...notes, value.data.onCreateNote]);
      }
    });

    API.graphql(graphqlOperation(onDeleteNote)).subscribe({
      next: ({ value }) => {
        setNotes(notes => notes.filter(note => 
          note.id !== value.data.onDeleteNote.id
        ));
      }
    });

    API.graphql(graphqlOperation(onUpdateNote)).subscribe({
      next: ({ value }) => {
        setNotes(notes => notes.map(note =>
          note.id === value.data.onUpdateNote.id
            ? value.data.onUpdateNote
            : note
        ));
      }
    });
  }

  async function handleSubmit(e) {
    e.preventDefault();
    try {
      await API.graphql(graphqlOperation(createNote, { input: formData }));
      setFormData({ title: '', content: '' });
    } catch (err) {
      console.error('Error creating note:', err);
    }
  }

  return (
    <View padding="1rem">
      <Heading level={1}>My Notes App</Heading>
      <Button onClick={signOut}>Sign Out</Button>

      <form onSubmit={handleSubmit}>
        <TextField
          label="Title"
          value={formData.title}
          onChange={e => setFormData({ ...formData, title: e.target.value })}
        />
        <TextField
          label="Content"
          value={formData.content}
          onChange={e => setFormData({ ...formData, content: e.target.value })}
        />
        <Button type="submit">Add Note</Button>
      </form>

      <View margin="1rem 0">
        {notes.map(note => (
          <View key={note.id} padding="1rem" borderRadius="medium">
            <Heading level={2}>{note.title}</Heading>
            <p>{note.content}</p>
            <Button onClick={() => API.graphql(
              graphqlOperation(deleteNote, { input: { id: note.id }})
            )}>
              Delete
            </Button>
          </View>
        ))}
      </View>
    </View>
  );
}

export default withAuthenticator(App);

Parte 4: Configurar X-Ray

1. Habilitar X-Ray en AppSync

bash
amplify update api

? Please select from one of the below mentioned services: GraphQL
? Select from the options below: Update X-Ray tracing configuration
? Do you want to enable X-Ray tracing? Yes

2. Configurar Grupos de Trazas

  1. En la consola AWS:
    X-Ray > Groups
    Create group
    
    Name: notes-app-traces
    Filter expression: service("NotesAPI")

3. Crear Reglas de Muestreo

  1. En X-Ray:
    Sampling rules
    Create rule
    
    Name: notes-app-sampling
    Reservoir size: 1
    Rate: 0.1

Parte 5: Desplegar y Monitorear

1. Desplegar la Aplicación

bash
# Publicar cambios
amplify push

# Desplegar frontend
amplify publish

2. Configurar Monitoreo en X-Ray

  1. En la consola de X-Ray:
    • Verificar Service Map
    • Revisar Traces
    • Analizar Latencias

3. Crear Dashboard de Monitoreo

  1. En CloudWatch:
    Create dashboard
    Name: notes-app-dashboard
    
    Añadir widgets:
    - X-Ray traces
    - AppSync latency
    - API errors

Verificación

1. Funcionalidad

  • [ ] Autenticación funciona
  • [ ] CRUD de notas funciona
  • [ ] Subscripciones en tiempo real funcionan

2. Monitoreo

  • [ ] X-Ray muestra trazas
  • [ ] Service map es visible
  • [ ] Dashboard muestra métricas

3. Rendimiento

  • [ ] Latencia dentro de límites
  • [ ] Sin errores de timeout
  • [ ] Trazas completas disponibles

Solución de Problemas Comunes

Error de Autenticación

  1. Verificar configuración de Cognito
  2. Revisar permisos IAM
  3. Validar tokens

Error de API

  1. Verificar schema GraphQL
  2. Revisar resolvers
  3. Verificar permisos

Error de X-Ray

  1. Verificar habilitación
  2. Revisar reglas de muestreo
  3. Verificar roles IAM

Limpieza

bash
# Eliminar recursos
amplify delete

# Verificar eliminación en consola AWS:
- AppSync API
- Cognito User Pool
- X-Ray traces
- CloudWatch logs

Conceptos Clave para el Examen

  • Amplify y su ecosistema
  • AppSync y GraphQL
  • X-Ray y monitoreo
  • Seguridad y autenticación

Puntos importantes a recordar:

  1. Amplify simplifica la creación de aplicaciones full-stack
  2. AppSync proporciona API GraphQL gestionada
  3. X-Ray ayuda a detectar y solucionar problemas de rendimiento
  4. La autenticación se maneja con Cognito

Para el examen Cloud Practitioner, enfócate en:

  • Propósito de cada servicio
  • Integración entre servicios
  • Capacidades de monitoreo
  • Aspectos de seguridad