Conceptos de Arquitectura

LET'S BUILD IT

¿Quién soy?

Full-stack LeanMind

Ex-alumno César Manrique

 

Adrián Ferrera

@AdrianFerrera91

adrian-afergon

@afergon

Una de las cosas que más nos gusta

Sentarnos a programar

Y hacer que las cosas funcionen

Pero no siempre es así...

La realidad es

LEER

DIÁLOGO

TRABAJO

Gran parte del día entendiendo código

Debatiendo, convenciendo y escuchando 

Las aplicaciones deben mantenerse a lo largo del tiempo

ESTO NO ES MALO

La realidad es

LEER

DIÁLOGO

TRABAJO

Estaremos en contacto con la arquitectura

¿Qué es la arquitectura?

Estructura

Comunicación

¿Para que?

  • Entender

  • Mantener

  • Dialogar

  • Evolucionar

¿Cómo?

Separando funciones distintas

Delegando responsabilidades

Haciendo que no sepan unas de otras

¿Dónde?

¿Como alumno que me aporta?

Es una puerta necesaria para crecer profesionalmente

¿Cuál es la diferencia?

¿Cuál es la diferencia?

const postSection = document.getElementById('posts-section');
const http = new XMLHttpRequest();
const url = 'https://jsonplaceholder.typicode.com/posts';
let posts = [];
http.open('GET', url);
http.send();

http.onreadystatechange = (e) => {
    posts = JSON.parse(http.responseText);
    postSection.innerHTML = '';
    posts.map((post) => {
        const newPost = document.createElement('div');
        newPost.innerHTML = `
            <div id="post-${post.id}" class="post-item">
                <h3>${post.title}</h3>
                <p>${post.body}</p>
            </div>
        `;
        postSection.appendChild(newPost);
    })
}

¿Qué pasaría si filtramos?

¿Qué pasaría si filtramos?

function filter(value) {
  postSection.innerHTML = '';
  posts
    .filter((post) => 
      post.title.includes(value) || post.body.includes(value))
    .map((post) => {
      const newPost = document.createElement('div');
      newPost.innerHTML = `
        <div id="post-${post.id}" class="post-item">
          <h3>${post.title}</h3>
          <p>${post.body}</p>
        </div>
      `;
      postSection.appendChild(newPost);
    });
}

Vamos a limpiarlo

function renderPosts(posts) {
  posts.map((post) => {
    const newPost = document.createElement('div');
    newPost.innerHTML = `
      <div id="post-${post.id}" class="post-item">
        <h3>${post.title}</h3>
        <p>${post.body}</p>
      </div>
    `;
    postSection.appendChild(newPost);
  });
}

function filter(value) {
  postSection.innerHTML = '';
  const filteredPosts = posts
    .filter((post) => 
      post.title.includes(value) || post.body.includes(value));
  renderPosts(filteredPosts);
}

http.onreadystatechange = (e) => {
  posts = JSON.parse(http.responseText);
  postSection.innerHTML = '';
  renderPosts(posts);
}

MEDITEMOS UN POCO

¿QUÉ HACEMOS?

 

Recuperar datos

Filtrar la información

Pintar en pantalla

¿Por que está en el mismo fichero?

¿Cómo podríamos agruparlo?

Acceso a datos

Cálculos y operaciones

Representación

Recibe los siguientes términos

Acceso a datos

Cálculos y operaciones

Representación

Repository

Service

View

Veámoslo en código

Repository

const PostRepository = function () {

  const http = new XMLHttpRequest();
  const url = 'https://jsonplaceholder.typicode.com/posts';

  function getPosts() {
    http.open('GET', url);
    http.send();
    return new Promise((resolve, rejected) => {
      http.onreadystatechange = (e) => {
        if (http.status >= 200 && http.status < 300) {
          // If successful
          resolve(JSON.parse(http.responseText));
        } else {
          // If failed
          reject({
            status: http.status,
            statusText: http.statusText
        });
      } 
    }
    })
  }

  return {
    getPosts
  }
}

Service

const PostService = function () {

  const postRepository = new PostRepository();
    
  async function getPosts() {
    return postRepository.getPosts()
  }

  function filterBy(text, posts) {
    return posts
      .filter((post) => 
         post.title.includes(text) || 
         post.body.includes(text))
  }

  return {
    getPosts,
    filterBy
  }
}

View

const PostView = function() {

  let posts = [];
  const postSection = document.getElementById('posts-section');
  const postService = new PostService();

  function render (post) {
    const newPost = document.createElement('div');
    newPost.innerHTML = `
      <div id="post-${post.id}" class="post-item">
        <h3>${post.title}</h3>
        <p>${post.body}</p>
      </div>
    `;
    postSection.appendChild(newPost);
  }

  async function mount () {
    posts = await postService.getPosts();
    posts.map(render);
  }

  function filter(value) {
    postSection.innerHTML = '';
    const filteredPosts = postService.filterBy(value, posts);
    filteredPosts.map(render);
  }

  return { mount, filter }

}

App

// App.js
PostView().mount();
<!DOCTYPE html>
<html>
    <head>
        <title>Post examples</title>
        <meta name="viewport" content="width=device-width, user-scalable=no">
        <link href="https://fonts.googleapis.com/css?family=Roboto&display=swap" rel="stylesheet">
        <link rel="stylesheet" type="text/css" href="style.css">
    </head>
    <body>
        <h1>Post list</h1>
        <section id="filter-section group">
            <input type="text" placeholder="Filter" onkeyup="postView.filter(this.value)"/>
        </section>
        <section id="posts-section"></section>
        <script src="post-reposioty.js" type="text/javascript"></script>
        <script src="post-service.js" type="text/javascript"></script>
        <script src="post-view.js" type="text/javascript"></script>
        <script src="app.js" type="text/javascript"></script>
    </body>
</html>

Las capas conforman un puzle

- ¿Y si leemos los datos de una BD?

+ Solo tenemos que crear un nuevo Repository

- ¿Y si cambian las reglas de filtrado?

+ Podemos actualizar la lógica sin que la vista se entere del cambio

- ¿Y si no me resulta sencillo pintar la vista de esta forma?

+ Simplemente puedes visualizarlo de otra forma: React, Vue, Angular, ember, jQuery...

Ya que la lógica no va en esta capa

ESTA ES LA BASE

PERO EXISTEN MUCHOS OTROS CONCEPTOS

Es la puerta para entender

otras tecnologías más complejas

y mejorar cada día en nuestro trabajo

CONCLUSIÓN

LA ARQUITECTURA NOS AYUDA A:

Comunicarnos con el equipo

Tener un código homogéneo

Simplificarnos el trabajo

Garantizar la calidad

¿Preguntas?

GRACIAS

Adrián Ferrera

@AdrianFerrera91

César Manrique 2k19 Arquitectura

By afergon

César Manrique 2k19 Arquitectura

  • 319