
Spanish: 
¿Cómo están? En este video vamos a aplicar los principios de
Clean Architecture de (Uncle) Bob Martin
en nuestra API en Golang pero primero hagamos un
resumen rápido de esos principios...para implementar una arquitectura "limpia" (Clean Architecture)
en nuestra aplicación la
la aplicación debe ser independiente de
frameworks para que no estemos atados a un
framework específico nuestra aplicación
debería poder reemplazar el framework HTTP, por ejemplo, nuestra aplicación
debe ser testeable para que podamos probar la
lógica de negocios sin la base de datos o
la interfaz de usuario necesitamos ser independientes de la
UI en nuestro caso estamos trabajando en un
una API REST, así que no nos importa si el
el cliente es un navegador web o un dispositivo móvil
aplicación o un dispositivo IOT nuestra
aplicación también debe ser independiente
de la base de datos, por lo que deberíamos poder
cambiar la capa de persistencia que podamos

English: 
what's going on guys in this video we're
going to apply the principles of the
clean architecture by (Uncle ) Bob Martin
in our Golang API but first let's do a
quick overview of those principles so in
order to follow a clean architecture
approach in our application the
application should be independent of
frameworks so we are not tied to a
specific framework our application
should be able to replace the HTTP
framework for example our application
should be testable so we can test the
business logic without the database or
the UI we need to be independent of the
UI in our case we are working on a
restful api so we don't care if the
client is a web browser or a mobile
application or an IOT device our
application should be also independent
of the database so we should be able to
change the persistence layer we can

English: 
what's going on guys in this video we're
going to apply the principles of the
clean architecture by (Uncle ) Bob Martin
in our Golang API but first let's do a
quick overview of those principles so in
order to follow a clean architecture
approach in our application the
application should be independent of
frameworks so we are not tied to a
specific framework our application
should be able to replace the HTTP
framework for example our application
should be testable so we can test the
business logic without the database or
the UI we need to be independent of the
UI in our case we are working on a
restful api so we don't care if the
client is a web browser or a mobile
application or an IOT device our
application should be also independent
of the database so we should be able to
change the persistence layer we can

English: 
start using Firestore and then we can
replace it by MySQL or MongoDB for
example and our application should be
also independent of any external agency
so our business rules don't know
anything about any external factors okay
remember to share like and subscribe
let's make Uncle Bob proud :-) and let's get
started... in a previous video we created a
repository to connect our application to
the firestore database and let's go
there so this is our repository we
created an interface and we created a
couple of methods one (function) to save the posts
and another one to get all the existing
posts from the firestore database so
having this interface will allow us to
keep independent the concrete

Spanish: 
comenzando a usar Firestore y luego podemos
reemplazarlo por MySQL o MongoDB por
ejemplo y nuestra aplicación debe ser
también independiente de cualquier agente externa
entonces nuestras reglas de negocios no saben
nada sobre cualquier factor externo...
Recuerda Compartir, Dar "me gusta" y Suscribirte....hagamos que el tío Bob se sienta orgulloso :-) y comencemos
... en un video anterior creamos un
repositorio para conectar nuestra aplicación a
la base de datos de Firestore y vámonos
allí, así que este es nuestro repositorio nosotros
creamos una interfaz y creamos un
par de métodos uno (función) para guardar las publicaciones
y otro para obtener todas las publicaciones de la base de datos
tener esta interfaz nos permitirá
mantener independiente la

English: 
start using Firestore and then we can
replace it by MySQL or MongoDB for
example and our application should be
also independent of any external agency
so our business rules don't know
anything about any external factors okay
remember to share like and subscribe
let's make Uncle Bob proud :-) and let's get
started... in a previous video we created a
repository to connect our application to
the firestore database and let's go
there so this is our repository we
created an interface and we created a
couple of methods one (function) to save the posts
and another one to get all the existing
posts from the firestore database so
having this interface will allow us to
keep independent the concrete

English: 
implementation from the rest of the
application so the rest of application
like in this case this route is just
accessing this interface this one
actually the post repository interface
and here we can change
the concrete implementation so we're
going to make some changes in the
structure but having an interface is a
good first step I'm going to copy this
and I'm going to create a new file and
this file is going to be the concrete
implementation for the firestore
database so this is going to be
firestore-repo.go I'm going to paste this here
and I'm going to remove the interface
and here I'm going to remove everything
but the interface so this is going to be

English: 
implementation from the rest of the
application so the rest of application
like in this case this route is just
accessing this interface this one
actually the post repository interface
and here we can change
the concrete implementation so we're
going to make some changes in the
structure but having an interface is a
good first step I'm going to copy this
and I'm going to create a new file and
this file is going to be the concrete
implementation for the firestore
database so this is going to be
firestore-repo.go I'm going to paste this here
and I'm going to remove the interface
and here I'm going to remove everything
but the interface so this is going to be

Spanish: 
implementación del resto de la
aplicación por lo que el resto de la aplicación
como en este caso esta ruta es solo
accediendo a esta interfaz esta
en realidad la interfaz del repositorio de publicaciones
y aquí podemos cambiar
la implementación concreta por lo que estamos
va a hacer algunos cambios en el
estructura pero tener una interfaz es un
buen primer paso voy a copiar esto
y voy a crear un nuevo archivo y
este archivo va a ser la
implementación para Firestore por lo que esto va a ser
firestore-repo.go voy a pegar esto aquí
y voy a eliminar la interfaz
y aquí voy a quitar todo
menos la interfaz así que esta va a ser

Spanish: 
nuestra interfaz ahora solo tenemos esto
implementación que es Firestore
como implementación para esa interfaz pero nosotros
también podríamos tener un repositorio MySQL por
ejemplo o también podemos tener un repo MongoDB implementando esa interfaz está bien así
otros cambios que necesitamos hacer aquí
por ejemplo este constructor esto necesita
ser NewFirestoreRepository porque
Esta es una implementación específica para
esa base de datos en el caso de MongoDB
vamos a tener otro constructor
otra función que será NewMongoRepository y la misma para

English: 
our interface now we only have this
implementation that is the firestore
implementation for that interface but we
may also have a MySQL repo for
example or we can also have a MongoDB
repo implementing that interface okay so
other changes that we need to do here
for example this constructor this needs
to be NewFirestoreRepository because
this is an a specific implementation for
that database in the case of MongoDB
we're gonna have another constructor
another function that is gonna be NewMongoRepository and the same for

English: 
our interface now we only have this
implementation that is the firestore
implementation for that interface but we
may also have a MySQL repo for
example or we can also have a MongoDB
repo implementing that interface okay so
other changes that we need to do here
for example this constructor this needs
to be NewFirestoreRepository because
this is an a specific implementation for
that database in the case of MongoDB
we're gonna have another constructor
another function that is gonna be NewMongoRepository and the same for

English: 
MySQL: NewMySQLRepository so here I'm
going to add the package so we don't get
any of these errors and the same here
now we are independent of the database
so we can use Firestore, Mongo, MySQL, 
Postgres, Oracle or
whatever you want to use (as the database) if we go to
routes.go we're gonna see that we
have mixed up some business logic like
this with code that is specific for a
controller like setting the content type
of a header or writing the response or
encoding a specific object so we're
going to need to split this in a service
layer the service layer is going to be
the use case or the business logic and

English: 
MySQL: NewMySQLRepository so here I'm
going to add the package so we don't get
any of these errors and the same here
now we are independent of the database
so we can use Firestore, Mongo, MySQL, 
Postgres, Oracle or
whatever you want to use (as the database) if we go to
routes.go we're gonna see that we
have mixed up some business logic like
this with code that is specific for a
controller like setting the content type
of a header or writing the response or
encoding a specific object so we're
going to need to split this in a service
layer the service layer is going to be
the use case or the business logic and

Spanish: 
MySQL: NewMySQLRepository así que aquí estoy
vamos a agregar el paquete para que no obtengamos
tengamos estos errores y lo mismo aquí
ahora nuestra aplicación es independiente de la base de datos
para que podamos usar Firestore, Mongo, MySQL, 
Postgres, Oracle o
lo cualquier otra base de datos / soporte de persistencia... si vamos a
routes.go vamos a ver que nosotros
hemos mezclado algo de lógica de negocios con código que es específico para un
controlador como establecer el tipo de contenido
de un encabezado o escribir la respuesta (HTTP) o
realizar el encoding de un objeto por lo que 
deberiamos dividir esto en un servicio
...esta capa de servicios va a implementar
los casos de uso / lógica de negocios y

English: 
then the controller the controller is
going to be the the code that is going
to be responsible of interacting with
the API layer so I'm going to create a
new folder that's gonna be service and
another one that is gonna be controller
and our service is going to be called
from the controller and the service is
going to call the repository to add new
posts and get existing posts from the
database so I'm going to create a new
file here so this is gonna be post-service.go
and here this is gonna be post-controller.go  okay let's create

English: 
then the controller the controller is
going to be the the code that is going
to be responsible of interacting with
the API layer so I'm going to create a
new folder that's gonna be service and
another one that is gonna be controller
and our service is going to be called
from the controller and the service is
going to call the repository to add new
posts and get existing posts from the
database so I'm going to create a new
file here so this is gonna be post-service.go
and here this is gonna be post-controller.go  okay let's create

Spanish: 
entonces el controlador es
el componente que
será responsable de interactuar con
la capa de la API, así que voy a crear una
nueva carpeta que será "service" y
otro que va a ser "controller"
Nuestro servicio será utilizado
desde el controlador y el servicio
utilizará al repositorio para agregar nuevas
publicaciones y obtener publicaciones existentes desde la
base de datos, así que voy a crear un nuevo archivo aquí, así que esto será post-service.go
y aqui dentro de la carpeta controller será post-controller.go. Bien, vamos a crear

English: 
the service first so the package is
gonna be service and this is going to be
the interface for the service type PostService interface and we gonna have
three methods we're gonna have a
validate method that's going to receive
a post
actually the reference to the post
*entity.Post we need to import that
package and this is going to throw
an error if there are any errors the
other method is going to be the create

Spanish: 
el servicio primero, entonces el paquete será "service" y esta será
la interfaz para el servicio: ... type PostService interface y tendremos
tres métodos vamos a tener un
método "Validate" que va a recibir
una publicación (post entity.Post)
en realidad la referencia a la publicación (post *entity.Post)
Debemos importar ese paquete ("entity") y esto va a retornar
un error si hay algún error... El
otro método va a ser el

English: 
the service first so the package is
gonna be service and this is going to be
the interface for the service type PostService interface and we gonna have
three methods we're gonna have a
validate method that's going to receive
a post
actually the reference to the post
*entity.Post we need to import that
package and this is going to throw
an error if there are any errors the
other method is going to be the create

English: 
method that's going to receive a post
I'm going to copy this and it's going to
return either a post or an error and the
last one is going to be a FindAll method
that is going to return either an array
of posts or an error like that okay okay
so in order to implement this interface
we are going to create a struct that's

Spanish: 
método "Create" que va a recibir una publicación
Voy a copiar esto y va a
devolver una publicación o un error y el
el último será un método "FindAll"
eso va a devolver un array
de publicaciones o un error...bien...
para implementar esta interfaz
vamos a crear una estructura que

English: 
method that's going to receive a post
I'm going to copy this and it's going to
return either a post or an error and the
last one is going to be a FindAll method
that is going to return either an array
of posts or an error like that okay okay
so in order to implement this interface
we are going to create a struct that's

English: 
going to be service and we're going to
create a function that is going to be a
constructor function we're going to call
it NewPostService that's going to
return a PostService
it's going to return a struct... this
struct that is going to implement this
PostService interface like this
okay and now let's implement these three
functions so.... func and it's gonna
be service this is the way that we have
to use to specify that this struct is
going to implement that function the
same for the create function and the

Spanish: 
será llamada "service" y vamos a
crear una función que va a ser una
función constructor que vamos a llamar
"NewPostService" que va a
devolver un PostService
va a devolver la estructura ... esta
estructura que va a implementar esta
Interfaz PostService...
... bien y ahora vamos a implementar estas tres funciones ... func y vamos a indicar
el servicio... esta es la forma que debemos
utilizar para especificar que esta estructura
va a implementar esa función... la
lo mismo para la función de creación (Create) y

English: 
going to be service and we're going to
create a function that is going to be a
constructor function we're going to call
it NewPostService that's going to
return a PostService
it's going to return a struct... this
struct that is going to implement this
PostService interface like this
okay and now let's implement these three
functions so.... func and it's gonna
be service this is the way that we have
to use to specify that this struct is
going to implement that function the
same for the create function and the

English: 
same for the FindAll function okay and
here what we're going to validate is if
we receive an empty post or a nil value
as a post and in that case we are
going to return an error we can use this
method from the errors package this
should import the errors package yes
here and here we can pass the message
the error message actually we can say
the post is empty okay and some other

Spanish: 
lo mismo para la función FindAll bien y
aquí lo que vamos a validar es si
recibimos una publicación vacía o un valor nulo
como una publicación y en ese caso estamos
vamos a devolver un error podemos usar esta función (New) del paquete de errores esto
debe importar el paquete de errores (de manera automática, gracias al IDE / Intellisense) sí
aquí y aquí podemos pasar el mensaje
el mensaje de error en realidad podemos indicar "la publicación está vacía".... bien y otras

English: 
same for the FindAll function okay and
here what we're going to validate is if
we receive an empty post or a nil value
as a post and in that case we are
going to return an error we can use this
method from the errors package this
should import the errors package yes
here and here we can pass the message
the error message actually we can say
the post is empty okay and some other

English: 
conditions that we can do here is the
title if post that tile is empty like
this and here I forgot to return the error
okay and we can do something
similar here we can say that the post
title is empty and if we don't get any
errors we'll return nil and here what
we need to do is we need to grab the logic
to create a new post from here we were
using here the rand library to generate a

English: 
conditions that we can do here is the
title if post that tile is empty like
this and here I forgot to return the error
okay and we can do something
similar here we can say that the post
title is empty and if we don't get any
errors we'll return nil and here what
we need to do is we need to grab the logic
to create a new post from here we were
using here the rand library to generate a

Spanish: 
condiciones que podemos chequear aquí son si el título del post está vacío como
esto y aquí olvidé devolver el error
bien y podemos hacer algo
similar aquí podemos indicar que el título publicación está vacío y si no tenemos
errores devolveremos nulo y aquí lo
lo que necesitamos hacer es tomar la lógica
para crear una nueva publicación desde aquí estábamos
usando aquí la biblioteca rand para generar un

English: 
random identifier so I'm going to copy
this from here sorry here and we need to
add the repo so we can access it from
here and I'm going to grab that from the
routes file from here okay let's go back
to the service and I'm going to add that here
I need to import that package okay here
I already have the reference so I just

Spanish: 
identificador aleatorio, así que voy a copiar
esto desde aquí......... y necesitamos
agregar el repositorio para que podamos acceder a él desde aquí y voy a tomar eso desde el
archivo routes.go.... desde aquí.... bien volvamos al servicio y voy a agregar eso aquí
Necesito importar ese paquete (repository) bien aquí ya tengo la referencia, así que solo

English: 
random identifier so I'm going to copy
this from here sorry here and we need to
add the repo so we can access it from
here and I'm going to grab that from the
routes file from here okay let's go back
to the service and I'm going to add that here
I need to import that package okay here
I already have the reference so I just

English: 
need to do that
and you need to return this okay that's
it for the create method of our service and
now I need to return repo.FindAll()
I forgot to add this
okay and that's it for the service and I
don't know why is showing an error here
what is the problem....oh yeah
because this is not NewPostRepository
this is NewFirestoreRepository we changed
the name okay
and now let's move on to the controller
so I'm going to grab.... first I'm going
to add the package controller

Spanish: 
necesito hacer eso
y deberia devolver esto.... bien, eso es
todo para el método de creación de nuestro servicio y
ahora necesito devolver repo.FindAll ()
Olvidé agregar esto ( "{}" at the end of the struct name )
bien y eso es todo (para la codificación) del servicio... no sé por qué está mostrando un error aquí
cual es el problema ... oh si
porque esto no es NewPostRepository
este es NewFirestoreRepository... ya cambiamos
el nombre... y ahora pasemos al controlador
... primero voy
a agregar al controlador el nombre del

English: 
need to do that
and you need to return this okay that's
it for the create method of our service and
now I need to return repo.FindAll()
I forgot to add this
okay and that's it for the service and I
don't know why is showing an error here
what is the problem....oh yeah
because this is not NewPostRepository
this is NewFirestoreRepository we changed
the name okay
and now let's move on to the controller
so I'm going to grab.... first I'm going
to add the package controller

English: 
and now I'm going to grab pretty much
all the code from here and here we need
to use the service so I'm going to
import the service okay I'm going to use
service.PostService
and this is gonna be NewPostService
yeah that's the right path okay and here
instead of using the repo I'm going to

English: 
and now I'm going to grab pretty much
all the code from here and here we need
to use the service so I'm going to
import the service okay I'm going to use
service.PostService
and this is gonna be NewPostService
yeah that's the right path okay and here
instead of using the repo I'm going to

Spanish: 
paquete que será "controller" y ahora voy a tomar gran parte del código de aquí y desde aquí necesitamos
usar el servicio, así que voy a
importar el servicio bien voy a usar
service.PostService
y esto va a ser NewPostService
si ese es el "path" correcto bien y aquí
en lugar de usar el repositorio voy a

English: 
use this service so I'm going to rename
as service and I'm going to rename this
to avoid this issue it's a naming issue so I'm going to use PostService
(In don't know why the package was removed...)
okay and now from the controller we are
using the service here and I need to add
the same here so I'm
going to remove these two lines and I'm
going to use create and I'm going to
pass the post as a parameter I need to also

Spanish: 
usar este servicio, así que voy a cambiar el nombre
como servicio y voy a renombrar esto
para evitar este problema es un problema de nomenclatura, así que voy a usar PostService
(No sé por qué se eliminó el paquete ...)
bien y ahora desde el controlador estamos
usando el servicio aquí y necesito agregar
lo mismo aquí, así que voy a eliminar estas dos líneas y voy
a usar "Create" y voy a
pasar la publicación como argumento... necesito también

English: 
use this service so I'm going to rename
as service and I'm going to rename this
to avoid this issue it's a naming issue so I'm going to use PostService
(In don't know why the package was removed...)
okay and now from the controller we are
using the service here and I need to add
the same here so I'm
going to remove these two lines and I'm
going to use create and I'm going to
pass the post as a parameter I need to also

English: 
validate that the post contains the
information that we need so I'm going to
call the validate method from the post
service: postService.Validate and I'm
going to pass a reference to the post and I
need to assign the error in case we get
any errors and then I'm going to add
this code to handle that error and here
I created a class to avoid hardcoding 
this JSON and this is errors.ServiceError

Spanish: 
validar que la publicación contiene el
información que necesitamos, así que voy a
llamar al método "validate" desde el 
servicio: postService.Validate() y
voy a pasar una referencia a la publicación y necesito asignar el error en caso de que tengamos
algún error y luego voy a agregar
este código para manejar ese error y aquí
Creé una clase para evitar hardcoding 
este JSON y esta clase es errors.ServiceError

English: 
validate that the post contains the
information that we need so I'm going to
call the validate method from the post
service: postService.Validate and I'm
going to pass a reference to the post and I
need to assign the error in case we get
any errors and then I'm going to add
this code to handle that error and here
I created a class to avoid hardcoding 
this JSON and this is errors.ServiceError

Spanish: 
... y aquí necesito
pasa el mensaje
y necesito importar ese paquete (errors) bien
si vamos alli... básicamente una estructura
que tiene un mensaje que es la única
propiedad... bien volvamos al
controlador y hagamos lo mismo para el
resto de los errores primero necesito usar
... el "Encoder" y necesitamos
para "encodear" ese error y sí, esto es

English: 
... and here I need to
pass the message
and I need to import that package okay
if we go there is basically a struct
that has a message that's the only
attribute okay let's go back to the
controller and let's do the same for the
rest of the errors first I need to use
this I need to use the encoder and we need
to encode that error and yeah this is

English: 
... and here I need to
pass the message
and I need to import that package okay
if we go there is basically a struct
that has a message that's the only
attribute okay let's go back to the
controller and let's do the same for the
rest of the errors first I need to use
this I need to use the encoder and we need
to encode that error and yeah this is

English: 
one we need to pass this as the message
of the struct... like that and I'm
going to do the same for the rest of the
error messages and the same here okay
I'm going to use a different name for
this variable in this case the message
is going to be the message that we are
setting here in the validate method it's
going to be or the post is empty or the
post title is empty so let's go back and
the way we have to access to that
message is by using the error function

Spanish: 
.... tenemos que pasar esto como mensaje
de la estructura ... así y debo
hacer lo mismo para el resto de los
mensajes de error y lo mismo aquí bien
Voy a usar un nombre diferente para
esta variable en este caso el mensaje
va a ser el mensaje que hemos configurando aquí en el método de validación...
va a ser o la publicación está vacía o el
el título de la publicación está vacío, así que regresemos y
la forma en que tenemos que acceder a eso
mensaje es mediante la función de error:

English: 
one we need to pass this as the message
of the struct... like that and I'm
going to do the same for the rest of the
error messages and the same here okay
I'm going to use a different name for
this variable in this case the message
is going to be the message that we are
setting here in the validate method it's
going to be or the post is empty or the
post title is empty so let's go back and
the way we have to access to that
message is by using the error function

Spanish: 
err1.Error() y esta función va a devolver un string (cadena)
ese será el mensaje de error
bien y aquí me olvidé de manejar el
error, así que... aqui recibo la publicación y un error y necesito
manejar ese error nuevamente... y aquí necesito usar

English: 
err1.Error() and this error
function is going to return a string
that's going to be the error message
okay and here I forgot to handle the
error so I'm going to here I'm going to
receive the post and an error and I need
to handle that error again result here
is two and here I need to use here

English: 
err1.Error() and this error
function is going to return a string
that's going to be the error message
okay and here I forgot to handle the
error so I'm going to here I'm going to
receive the post and an error and I need
to handle that error again result here
is two and here I need to use here

English: 
result okay and here we are going to set
a message error saving the post okay in
that's that for the AddPost function so
we have our controller ready and the
controller is using the PostService and
the PostService is using the FirestoreRepository
but we can also change this
if we create a specific implementation
for Mongo we can create a function that
is going to be the constructor to access
this Mongo repository and the same for MySQL or any other database and here
I'm going to remove this file completely
and I need to add an interface for this

Spanish: 
"result" bien y aquí vamos a establecer
un mensaje de error al guardar la publicación....
eso es todo por la función AddPost
tenemos nuestro controlador listo y el
el controlador está utilizando PostService y
PostService está utilizando el FirestoreRepository
pero también podemos cambiar esto
si creamos una implementación específica
para Mongo podemos crear una función que
va a ser el constructor para acceder
este repositorio de Mongo y lo mismo para MySQL o cualquier otra base de datos y aquí
Voy a eliminar este archivo (routes.go) completamente
y necesito agregar una interfaz para este

English: 
result okay and here we are going to set
a message error saving the post okay in
that's that for the AddPost function so
we have our controller ready and the
controller is using the PostService and
the PostService is using the FirestoreRepository
but we can also change this
if we create a specific implementation
for Mongo we can create a function that
is going to be the constructor to access
this Mongo repository and the same for MySQL or any other database and here
I'm going to remove this file completely
and I need to add an interface for this

English: 
controller I forgot to add that so I'm
going to do that right now type
PostController interface and it's going to
declare these two methods the GetPosts
method that's going to receive the HTTP
response writer and the HTTP request
and the AddPost method here I'm going to
capitalize the first letter just to keep
the convention okay
okay and another thing that we need to
change in order to be independent of
frameworks here we depend on Mux so
the implementation of our API depends on Mux so
we need to create a layer if tomorrow we

English: 
controller I forgot to add that so I'm
going to do that right now type
PostController interface and it's going to
declare these two methods the GetPosts
method that's going to receive the HTTP
response writer and the HTTP request
and the AddPost method here I'm going to
capitalize the first letter just to keep
the convention okay
okay and another thing that we need to
change in order to be independent of
frameworks here we depend on Mux so
the implementation of our API depends on Mux so
we need to create a layer if tomorrow we

Spanish: 
controlador olvidé agregar eso, así que 
va a hacer eso en este momento:
...type PostController interface... y va a
declarar estos dos métodos: GetPosts
que va a recibir el HTTP response writer
y la solicitud HTTP (http.Request)
y el método AddPost aquí voy a
escribe con mayúscula la primera letra solo para mantener
la convención.... está bien
bien y otra cosa que necesitamos
cambiar para que nuestra aplicación sea independiente de frameworks aquí dependemos de Mux por lo
que la implementación de nuestra API depende de Mux (valga la redundancia), así que
necesitamos crear una capa (de abstracción) si mañana tenemos

Spanish: 
deseamos usar un servidor HTTP específico (otro framework) o si
nosotros o si queremos implementar nuestro propio
otro framework para implementar nuestra API usando HTTP ... deberíamos poder hacerlo sin mayores cambios...
así que vamos a hacer algunos cambios
aquí nuestro enrutador está implementando esta función "HandleFunc" y eso es...
...lo único que está haciendo...
estamos pasando aquí los métodos post, get...
método así que lo que vamos a hacer es crear una interfaz de enrutador.....
para implementar el método get (http GET) y el método post (http POST)
si agregamos nuevas operaciones a nuestra
API para manejar todos los verbos HTTP vamos a necesitar agregar PUT,
...DELETE, PATCH, etc así que hagamos eso que voy a crear

English: 
want to use a specific HTTP server or if
we or if we want to implement our own
HTTP framework we should be able to do
it so we're going to make a few changes
here our router is implementing this
handle func function and that's pretty
much the only thing that is doing but we
are passing here the get method the post
method so what are going to do is we are going to create a router interface that is going
to implement the get method and the post
method if we add new operations in our
API to handle all the HTTP verbs or
methods we're gonna need to add the put
method the delete method the patch method
etc so let's do that I'm going to create

English: 
want to use a specific HTTP server or if
we or if we want to implement our own
HTTP framework we should be able to do
it so we're going to make a few changes
here our router is implementing this
handle func function and that's pretty
much the only thing that is doing but we
are passing here the get method the post
method so what are going to do is we are going to create a router interface that is going
to implement the get method and the post
method if we add new operations in our
API to handle all the HTTP verbs or
methods we're gonna need to add the put
method the delete method the patch method
etc so let's do that I'm going to create

English: 
a new folder that is gonna be http so
I'm going to create a new file and this
is going to be the interface I'm going to call  it router.go and the package it's gonna be
router and I'm going to create the
Router interface...
and here we are going to create the
different methods let's go back to the
server we're going to need something
that receives the uri or the
resource and a function that has two
arguments these two arguments the

Spanish: 
una nueva carpeta que va a ser http
Voy a crear un nuevo archivo y esto
va a ser la interfaz que voy a llamar router.go y el paquete será
"router" y voy a crear la
Interfaz del enrutador (Router) ...
y aquí vamos a crear los
diferentes métodos...volvamos al archivo
server.go...vamos a necesitar algo
que recibe el uri o el
recurso y una función que tiene dos
argumentos estos dos argumentos del

English: 
a new folder that is gonna be http so
I'm going to create a new file and this
is going to be the interface I'm going to call  it router.go and the package it's gonna be
router and I'm going to create the
Router interface...
and here we are going to create the
different methods let's go back to the
server we're going to need something
that receives the uri or the
resource and a function that has two
arguments these two arguments the

English: 
response writer and the request so I'm
going to grab this let's start by adding
the get method and it's going to receive
a URI that is going to be a string and a
function that is going to receive the
response writer and the request and we
also need to implement a post method
like that and I think we should be fine
yeah and the last thing here is the
initialization of the HTTP service we're
going to need to add another function
here that is going to be the serve

English: 
response writer and the request so I'm
going to grab this let's start by adding
the get method and it's going to receive
a URI that is going to be a string and a
function that is going to receive the
response writer and the request and we
also need to implement a post method
like that and I think we should be fine
yeah and the last thing here is the
initialization of the HTTP service we're
going to need to add another function
here that is going to be the serve

Spanish: 
escritor de respuesta y la solicitud, así que 
voy a copiar esto...comencemos agregando
el método get y va a recibir
un URI que va a ser una cadena y una
función que va a recibir el
escritor de respuesta y la solicitud y nosotros
También es necesario implementar un método POST así y creo que deberíamos estar bien
Sí, y lo último aquí es la
inicialización del servicio HTTP vamos
a necesitar agregar otra función
aquí va a ser la función SERVE

English: 
function that's going to receive the
port where the service is going to be
listening okay now that we have our
router interface let's create concrete
implementation for the Mux framework so
I'm going to create a new file here
there's going to be mux-router.go
the package is going to be router and in
order to implement the router interface
I gonna need to declare a struct like this
type muxRouter struct and I also going
to need to implement a function to have
a constructor in order to be able to

English: 
function that's going to receive the
port where the service is going to be
listening okay now that we have our
router interface let's create concrete
implementation for the Mux framework so
I'm going to create a new file here
there's going to be mux-router.go
the package is going to be router and in
order to implement the router interface
I gonna need to declare a struct like this
type muxRouter struct and I also going
to need to implement a function to have
a constructor in order to be able to

Spanish: 
.....que va a recibir el
puerto donde va a estar el servicio
escuchando bien ahora que tenemos nuestro
interfaz del enrutador vamos a crear concreto
la implementación para el framework Mux por lo que voy a crear un nuevo archivo aquí
...será el archivo mux-router.go
el paquete va a ser router y
para implementar la interfaz del enrutador
Voy a necesitar declarar una estructura como esta
"type muxRouter struct..." y también voy
deberia implementar una función para tener un constructor para poder

English: 
access this a specific implementation so
you NewMuxRouter and the return type of
this function is going to be the
interface..Router... and it's going to
return the struct like this I'm going
to grab the signatures from here
and I'm going to start working on the
implementation for the Mux HTTP
framework we'll need to pass the struct

Spanish: 
acceder a esta implementación específica ... NewMuxRouter y el tipo de retorno de
esta función va a ser la
interfaz ... Router ... y va a
devolver la estructura..... voy
a tomar las firmas desde aquí
y voy a comenzar a trabajar en el
implementación para el framework HTTP Mux...
... tendremos que pasar la estructura

English: 
access this a specific implementation so
you NewMuxRouter and the return type of
this function is going to be the
interface..Router... and it's going to
return the struct like this I'm going
to grab the signatures from here
and I'm going to start working on the
implementation for the Mux HTTP
framework we'll need to pass the struct

English: 
the same from the post and the same for
the serve method okay and here I need to
access to the Mux library and I'm going
to create a variable for that and I'm
going to call it muxDispatcher and here
I need to use this mux.NewRouter
.... like that and I need to
import that library here I'm going to

Spanish: 
lo mismo para POST y lo mismo para
SERVE... está bien y aquí necesito
acceso a la libreria "Mux" y voy
a crear una variable para eso y voy
a llamarlo muxDispatcher y aquí
necesito usar mux.NewRouter
... así y necesito
importar esa libreria aquí voy a

English: 
the same from the post and the same for
the serve method okay and here I need to
access to the Mux library and I'm going
to create a variable for that and I'm
going to call it muxDispatcher and here
I need to use this mux.NewRouter
.... like that and I need to
import that library here I'm going to

Spanish: 
tomar la dependencia de aquí....
ese es el paquete así bien
y para GET necesitamos usar
la libreria Mux usando este
muxDispatcher y aquí tenemos que llamar a la función HandleFunc y para esta
función necesitamos pasar el URI y
la función "handler" y tenemos que asignar el método
GET..... y va a ser bastante similar para el
método POST necesitaremos cambiar esto
y aquí vamos a usar esta

English: 
grab the dependency from here oh okay
that's the package like that okay
and for the other operation we need to use
the Mux library by using this mux
dispatcher and here we need to call the
handle func function and to this
function we need to pass the URI and
function and we need to assign the get
method for this like this methods and
it's going to be pretty similar for the
post method we'll need to change this
and here we are going to use this

English: 
grab the dependency from here oh okay
that's the package like that okay
and for the other operation we need to use
the Mux library by using this mux
dispatcher and here we need to call the
handle func function and to this
function we need to pass the URI and
function and we need to assign the get
method for this like this methods and
it's going to be pretty similar for the
post method we'll need to change this
and here we are going to use this

English: 
function let's go back let's paste it
here and the router is gonna be actually
the muxDispatcher and here I'm going to
add a log from the...
fmt, fmt.Printf and the message Mux HTTP
server running on port...
and then we need to pass the port here
okay now we have our first
implementation of the router so we need
to replace this I'm going to create a

Spanish: 
función.... volvamos peguemos
aquí y el enrutador será en realidad
el muxDispatcher y aquí voy a
agregar un log ...
fmt, fmt.Printf y el mensaje será "...Mux HTTP server running on port...." (Mux server ejecutándose en el puerto...)
y luego necesitamos pasar el puerto aquí
bien ahora tenemos nuestra primera
implementación del enrutador (Router interface) por lo que necesitamos reemplazar esto voy a crear una

English: 
function let's go back let's paste it
here and the router is gonna be actually
the muxDispatcher and here I'm going to
add a log from the...
fmt, fmt.Printf and the message Mux HTTP
server running on port...
and then we need to pass the port here
okay now we have our first
implementation of the router so we need
to replace this I'm going to create a

English: 
variable here and it's going to be HTTP
router and we need to import the package
replacing this one it's going to be http
and here we're going to use router.Router
....this is the interface and this is
going to be equals to router.NewMuxRouter
...this is the function that we
are using to create a new instance of
the max router.... okay and I'm going to
remove this we're not going to use it

English: 
variable here and it's going to be HTTP
router and we need to import the package
replacing this one it's going to be http
and here we're going to use router.Router
....this is the interface and this is
going to be equals to router.NewMuxRouter
...this is the function that we
are using to create a new instance of
the max router.... okay and I'm going to
remove this we're not going to use it

Spanish: 
variable aquí y va a ser httpRouter y necesitamos importar el paquete
reemplazando este (el package de Mux...).... va a ser "http" y aquí vamos a usar el enrutador.
.... esta es la interfaz y esto será igual a router.NewMuxRouter
... esta es la función que nosotros
estamos utilizando para crear una "nueva instancia" del
enrutador Mux ... está bien y voy a
eliminar esto no lo vamos a usar

English: 
and here I need to replace this by this
new router that implements the interface
that we created so this is going to be GET and we are
going to pass the URI and we need to do the same here for this operation
it's going to be httpRouter.GET
and we'll remove this and the same for the post method it's going to be POST, let's remove this

English: 
and here I need to replace this by this
new router that implements the interface
that we created so this is going to be GET and we are
going to pass the URI and we need to do the same here for this operation
it's going to be httpRouter.GET
and we'll remove this and the same for the post method it's going to be POST, let's remove this

Spanish: 
y aquí necesito reemplazar esto por este
nuevo enrutador que implementa la interfaz
que creamos (Router), así que esto será GET y...
vamos a pasar el URI y tenemos que hacer lo mismo aquí para esta operación
va a ser httpRouter.GET
y eliminaremos esto y lo mismo para el método POST, eliminemos esto

English: 
and this and we need to use the serve
method httpRouter.SERVE and we
need to pass the port like this okay I'm
going to comment these two lines and
let's test this....
...okay and here we have our Mux HTTP
server running on port 8000 let's go to
postman and let's try the get operation
oh yeah we don't have any handler for
that URL so I'm going to remove this and
I'm going to test just this okay let's

English: 
and this and we need to use the serve
method httpRouter.SERVE and we
need to pass the port like this okay I'm
going to comment these two lines and
let's test this....
...okay and here we have our Mux HTTP
server running on port 8000 let's go to
postman and let's try the get operation
oh yeah we don't have any handler for
that URL so I'm going to remove this and
I'm going to test just this okay let's

Spanish: 
y esto y necesitamos usar el método httpRouter.SERVE y debemos
pasar el puerto de esta manera,...voy a comentar estas dos líneas y
vamos a probar esto ...
... está bien y aquí tenemos nuestro servidor HTTP Mux que se ejecuta en el puerto 8000 vamos a
Postman e intentemos la operación GET
oh sí, no tenemos ningún controlador para
esa URL, así que voy a eliminar esto y
Voy a probar esto bien, vamos a

English: 
try this okay and it's up and running so
we're good great okay and now what I
need to do is I need to use the
controller this one from the server so I
need to import the controller package
here and I need to add the post controller
here
it's going to be controller.PostController
this is the interface that we created and it's going to be controller.NewPostController

Spanish: 
probar esto... bien... está funcionando,
estamos bien...y ahora lo que yo
tengo que hacer es usar el
controlador (PostController) desde el servidor, así que
necesito importar el paquete del controlador
aquí y necesito agregar el controlador
aquí
va a ser controller.PostController
esta es la interfaz que creamos y será controller.NewPostController

English: 
try this okay and it's up and running so
we're good great okay and now what I
need to do is I need to use the
controller this one from the server so I
need to import the controller package
here and I need to add the post controller
here
it's going to be controller.PostController
this is the interface that we created and it's going to be controller.NewPostController

English: 
..... okay I forgot
to add a function and I need to copy this from
here and here I need to also add the
struct so this is going to be type
controller struct and this is going
to return the post controller interface
and it's going to return this controller
and I need to add the controller here to
make it implement each of these methods

English: 
..... okay I forgot
to add a function and I need to copy this from
here and here I need to also add the
struct so this is going to be type
controller struct and this is going
to return the post controller interface
and it's going to return this controller
and I need to add the controller here to
make it implement each of these methods

Spanish: 
..... bueno, olvidé agregar una función y necesito copiar esto desde
aquí y aquí también necesito agregar el
struct por lo que esto va a ser de tipo
estructura del controlador y esto va
a devolver la interfaz PostController
y va a devolver este controlador
y necesito agregar el controlador aquí para
hacer que implemente cada uno de estos métodos

Spanish: 
y lo mismo para la otra función está bien
ahora tenemos nuestro controlador implementando
los dos métodos y deberíamos poder
usarlo desde aquí... está bien, sí, no obtenemos
ningún error aquí, así que aquí tenemos que pasar
la operación en realidad la operación GetPosts
y aquí para el método POST
necesitamos pasar la operación AddPost
(o la función AddPost)
Está bien, vamos a probar de nuevo.... bien...
Voy a detener el servidor voy

English: 
and the same for the other function okay
now we have our controller implementing
the two methods and we should be able to
use it from here okay yes we don't get
any errors here so here we need to pass
the operation actually the GetPosts
operation and here for the POST method
we need to pass the AddPost operation
(or the AddPost function)
okay let's check yes okay... great okay
I'm going to stop the server I'm going

English: 
and the same for the other function okay
now we have our controller implementing
the two methods and we should be able to
use it from here okay yes we don't get
any errors here so here we need to pass
the operation actually the GetPosts
operation and here for the POST method
we need to pass the AddPost operation
(or the AddPost function)
okay let's check yes okay... great okay
I'm going to stop the server I'm going

Spanish: 
a ejecutarlo de nuevo y vamos a Firestore
y no tenemos ningún documento vamos a actualizar
por si acaso pero no tenemos ningún
documento aquí, así que vamos a crear uno bien
vamos a ver en Firebase si tenemos este
nuevo elemento sí tenemos este nuevo
documento aquí y vamos a ejecutar la operación GET la URI es en realidad mensajes ("/posts") y sí
obtenemos el documento que acabamos de crear aquí está bien, pero Mux es solo una posible
implementación de esta interfaz de enrutador (Router)
y también podemos usar cualquier otro HTTP
marco como Chi.....

English: 
to start it again and let's go to firestore
and we don't have any documents let's refresh
this just in case but we don't have any
documents here so let's create one okay
let's check in firebase if we have this
new element yes we have this new
document here and let's run the get
operation is actually posts and yes we
get the document that we just created
here okay but Mux is just one possible
implementation of this router interface
and we can also use any other HTTP
framework such as Chi (I don't
know how to pronounce it) but we are

English: 
to start it again and let's go to firestore
and we don't have any documents let's refresh
this just in case but we don't have any
documents here so let's create one okay
let's check in firebase if we have this
new element yes we have this new
document here and let's run the get
operation is actually posts and yes we
get the document that we just created
here okay but Mux is just one possible
implementation of this router interface
and we can also use any other HTTP
framework such as Chi (I don't
know how to pronounce it) but we are

English: 
going to implement another router using
that specific framework so we'll create a
new file here I'm going to call it chi-router.go and we are going to
implement this router interface but
using this specific framework so package
is gonna be router... and we need to
create a structure type chiRouter struct
.....like that

Spanish: 
vamos a implementar otro enrutador usando ese marco específico (Chi), así que crearemos un
nuevo archivo aquí lo voy a llamar chi-router.go y vamos a
implementar esta interfaz de enrutador pero
utilizando este marco específico de modo paquete
va a ser enrutador ... y necesitamos
crear una estructura....chiRouter...
.....como eso

English: 
going to implement another router using
that specific framework so we'll create a
new file here I'm going to call it chi-router.go and we are going to
implement this router interface but
using this specific framework so package
is gonna be router... and we need to
create a structure type chiRouter struct
.....like that

English: 
and we're going to create a function NewChiRouter and it's going to return the
interface that we have for this HTTP
layer and it's going to return a
reference to the chiRouter like that
.... okay and now we need
to implement all the different functions
that we find here as part of this
interface so let's do that it's going to
be func
and here as a reference to this struct

Spanish: 
y vamos a crear una función NewChiRouter y va a devolver el
interfaz que tenemos para esta capa HTTP
y va a devolver una
referencia al chiRouter así
.... ok y ahora necesitamos implementar todas las diferentes funciones
que encontramos aquí como parte de esta
interfaz.....
...entonces será func.....
y aquí como referencia a esta estructura

English: 
and we're going to create a function NewChiRouter and it's going to return the
interface that we have for this HTTP
layer and it's going to return a
reference to the chiRouter like that
.... okay and now we need
to implement all the different functions
that we find here as part of this
interface so let's do that it's going to
be func
and here as a reference to this struct

English: 
the same for the rest of the functions
and here I need to create a variable here
and I'm going to close this and first I
need to import that library so first I
need to install this Chi library
so go get and the location of the library
is github.com/go-chi/chi okay and i'm
going to grab this URL and i'm going to
import that library here okay and here

Spanish: 
lo mismo para el resto de las funciones
y aquí necesito crear una variable...voy a cerrar esto y primero
necesito importar esa libreria (Chi), así que primero necesito instalar esta libreria Chi
así que ejecuto "go get.." y la ubicación de la biblioteca github.com/go-chi/chi... está bien y...
voy a tomar esta URL y voy a
importar esa libreria aquí está bien y aquí

English: 
the same for the rest of the functions
and here I need to create a variable here
and I'm going to close this and first I
need to import that library so first I
need to install this Chi library
so go get and the location of the library
is github.com/go-chi/chi okay and i'm
going to grab this URL and i'm going to
import that library here okay and here

English: 
i'm going to create a variable that's going to be chiDispatcher
and it's going to be equal to chi.NewRouter this is similar to Mux and
here what I'm going to do is I'm going
to use that dispatcher and I'm going
to use the get method that's the way
that Chi handles the get HTTP requests
and I'm going to add the URI and the
function here and something similar is
gonna be for the post function instead
of get this is gonna be post and I need

Spanish: 
voy a crear una variable que será chiDispatcher
y será igual a chi.NewRouter es similar a Mux y
aquí lo que voy a hacer es que voy
a usar ese despachador y voy
usar el método Get de esa manera
que Chi maneja las solicitudes HTTP GET
y voy a agregar el URI y la
función aquí y algo similar
va a ser para la función POST........ y necesito

English: 
i'm going to create a variable that's going to be chiDispatcher
and it's going to be equal to chi.NewRouter this is similar to Mux and
here what I'm going to do is I'm going
to use that dispatcher and I'm going
to use the get method that's the way
that Chi handles the get HTTP requests
and I'm going to add the URI and the
function here and something similar is
gonna be for the post function instead
of get this is gonna be post and I need

English: 
to pass the URI and the function and
here I'm going to grab this from here
and then I'm going to adapt it sorry here
... for the Chi router and
....and I'm going to change
the message here it's gonna be Chi HTTP
server running on port and whatever port
we are going to pass to this router
okay I think we're good and now let's go
back to the server and instead of using
Mux let's use Chi okay now I'm going
to run this now we can see that the Chi
HTTP server is running so let's try now
just to check that everything is still

English: 
to pass the URI and the function and
here I'm going to grab this from here
and then I'm going to adapt it sorry here
... for the Chi router and
....and I'm going to change
the message here it's gonna be Chi HTTP
server running on port and whatever port
we are going to pass to this router
okay I think we're good and now let's go
back to the server and instead of using
Mux let's use Chi okay now I'm going
to run this now we can see that the Chi
HTTP server is running so let's try now
just to check that everything is still

Spanish: 
pasar el URI y la función y
aquí voy a agarrar esto desde aquí
y luego voy a adaptarlo.....
... para el enrutador Chi y
.... y voy a cambiar
el mensaje aquí va a ser "Chi HTTP
server running on port..." y el puerto
que decidamos a pasar a este enrutador
bien, creo que estamos bien y ahora vamos
de vuelta al servidor y en lugar de usar
Mux vamos a usar Chi bien ahora vamos a ejecutar esto... podemos ver que el
servidor HTTP Chi se está ejecutando, así que probemos ahora
solo para comprobar que todo está

English: 
working as we expect so if we try to get
the posts okay yes we get the post and
let's create a new one just in case to
check that everything still works as we
expect
okay I'm able to create the new document
and yeah and we still can get the
response that we expect from this Chi
server so now we are independent of the
HTTP framework so we can either use Chi
or we can use Mux
so we created this router interface and
we created two implementations one for
Mux and another one for Chi great

English: 
working as we expect so if we try to get
the posts okay yes we get the post and
let's create a new one just in case to
check that everything still works as we
expect
okay I'm able to create the new document
and yeah and we still can get the
response that we expect from this Chi
server so now we are independent of the
HTTP framework so we can either use Chi
or we can use Mux
so we created this router interface and
we created two implementations one for
Mux and another one for Chi great

Spanish: 
funcionando como esperamos, así que si tratamos de conseguir las publicaciones  (GET /posts) bien sí obtenemos la publicación y
creemos uno nuevo por si acaso
para comprobar que todo sigue funcionando como nosotros
esperamos
bien, puedo crear el nuevo documento
y sí, y obtenemos la
respuesta que esperamos desde el servidor Chi
así que ahora somos independientes del
framework HTTP entonces podemos usar Chi
o podemos usar Mux....así que creamos esta interfaz Router y
creamos dos implementaciones una para
Mux y otra para Chi genial

English: 
okay and if we go here to the controller
we're gonna see that we are creating
this service here so something that will
allow us to have a better the testability
is going to be passing this service in
this case we are going to use the
controller....a more efficient way to do this
is going to be using some kind of
dependency injection framework or
mechanism now we are going to do this by
passing this service in here in this
constructor so it's gonna be service and
the service is going to implement this
PostService interface...
... and I'm going to assign this
variable to that argument and here I'm

English: 
okay and if we go here to the controller
we're gonna see that we are creating
this service here so something that will
allow us to have a better the testability
is going to be passing this service in
this case we are going to use the
controller....a more efficient way to do this
is going to be using some kind of
dependency injection framework or
mechanism now we are going to do this by
passing this service in here in this
constructor so it's gonna be service and
the service is going to implement this
PostService interface...
... and I'm going to assign this
variable to that argument and here I'm

Spanish: 
bien y si vamos aquí al controlador
vamos a ver que estamos creando
este servicio aquí, así que algo que
va a permitirnos tener una mejor capacidad de prueba
va a ser pasar este servicio en
en este caso vamos a usar el
controlador ... una forma más eficiente de hacer esto va a ser utilizar algún tipo de
framework de inyección de dependencias (DI) ahora vamos a hacer esto (de forma manual, explícita)
pasando este servicio aquí en este
constructor por lo que va a ser servicio y
el servicio va a implementar esta
Interfaz PostService ...
... y voy a asignar esta
variable a ese argumento y aquí

English: 
going to remove this okay and now what I
need to do is if I go back to the server
I need to import the service package and
I need to pass the service here so I'm
going to create the service postService ....
.....service.NewPostService
this is the constructor and I'm
going to pass this post service here to
the controller so now we assign this
service using this function or this
constructor function okay let's go back

Spanish: 
voy a eliminar esto bien y ahora lo que yo
lo que voy a hacer es si vuelvo al servidor
Necesito importar el paquete de servicio y
Necesito pasar el servicio aquí, así que
voy a crear el servicio postService ....
..... service.NewPostService
este es el constructor y voy
a pasar este servicio aquí al controlador así que ahora asignamos este
servicio utilizando esta esta
función "constructor" bien volvamos

English: 
going to remove this okay and now what I
need to do is if I go back to the server
I need to import the service package and
I need to pass the service here so I'm
going to create the service postService ....
.....service.NewPostService
this is the constructor and I'm
going to pass this post service here to
the controller so now we assign this
service using this function or this
constructor function okay let's go back

English: 
to the server and the same happens here
in the service if we go here we're gonna
see that we are creating the repository
here we're creating a new reference to
the firestore repository and it's going
to be better for a better testability
of this service if we pass the
repository here in the constructor so
let's do that it's going to be repo and
this repo is going to implement this
interface and I'm going to remove this
and I'm going to assign the repo to this
variable and now I'm going to import the
repository package... and I'm
going to create the post repository here

Spanish: 
al servidor y lo mismo sucede aquí
en el servicio si vamos aquí vamos a
ver que estamos creando el repositorio
aquí estamos creando una nueva referencia al
repositorio Firestore y va
a ser mejor para una mejor capacidad de prueba
de este servicio si pasamos el
repositorio aquí en el constructor...
...aqui va a ser repositorio y
este repositorio va a implementar esta
interfaz y voy a eliminar esto
y voy a asignar el repositorio a esta
variable y ahora voy a importar el
paquete de repositorio ... y
vamos a crear el repositorio de publicaciones (PostRepository) aquí

English: 
to the server and the same happens here
in the service if we go here we're gonna
see that we are creating the repository
here we're creating a new reference to
the firestore repository and it's going
to be better for a better testability
of this service if we pass the
repository here in the constructor so
let's do that it's going to be repo and
this repo is going to implement this
interface and I'm going to remove this
and I'm going to assign the repo to this
variable and now I'm going to import the
repository package... and I'm
going to create the post repository here

English: 
it's going to be a repository.PostRepository....
that is the interface the generic
interface and then we have the concrete
implementation that is repository.NewFirestoreRepository
okay and now we need to pass this
repository to the service great if we
go here now we receive the repo in this
function or this constructor and we

Spanish: 
va a ser un repository.PostRepository ...
esa es la interfaz genérica y luego tenemos  la
implementación concreta que es repository.NewFirestoreRepository
bien y ahora tenemos que pasar este
repositorio al servicio...
...aquí ahora recibimos el repositorio en esta función o este "constructor" y

English: 
it's going to be a repository.PostRepository....
that is the interface the generic
interface and then we have the concrete
implementation that is repository.NewFirestoreRepository
okay and now we need to pass this
repository to the service great if we
go here now we receive the repo in this
function or this constructor and we

English: 
assign that value here okay so now we
have the repository in this case is the
Firestore repository but if we want
to integrate our application with MySQL
MongoDB Postgres Oracle SQL Server or whatever we can create a new
class here we implement this post
repository interface and we are good to
go
and here we have this service and we are
passing that repository so this service
is also independent from the
repository so we have a better
separation of concerns on that as well
and also we have the controller and the
controller we are passing the post
service we can create a different
implementation for example of this post
service okay let's try this I'm going to
close this and I'm going to start the
server again
okay and let's run this and yes and we

Spanish: 
asignamos ese valor aquí bien, así que ahora estamos usando el repositorio...en este caso es el
repositorio de Firestore pero si queremos
integrar nuestra aplicación con MySQL
MongoDB, Postgres, Oracle, SQL Server o cualquier otro motor de base de datos
implementamos la interfaz PostRepository y con eso alcanza...
y aquí tenemos este servicio y estamos
pasando ese repositorio para que este servicio
también sea independiente del
repositorio para que tengamos una mejor
"separación de preocupaciones" (separation of concerns, in english) sobre eso también
y además tenemos el controlador y al
controlador le estamos pasando el
servicio de publicación (implementación de PostService) podemos crear una
nueva implementación de este
servicio bien....probemos esto voy a
cerrar esto y voy a iniciar el
servidor de nuevo
bien y vamos a ejecutar esto y sí....

English: 
assign that value here okay so now we
have the repository in this case is the
Firestore repository but if we want
to integrate our application with MySQL
MongoDB Postgres Oracle SQL Server or whatever we can create a new
class here we implement this post
repository interface and we are good to
go
and here we have this service and we are
passing that repository so this service
is also independent from the
repository so we have a better
separation of concerns on that as well
and also we have the controller and the
controller we are passing the post
service we can create a different
implementation for example of this post
service okay let's try this I'm going to
close this and I'm going to start the
server again
okay and let's run this and yes and we

English: 
still get the data and let's create a
new post let's say "Title 3" and "Text 3" yeah
we get a successful response and if
we go again we get all the
posts we get title 2, title 3 and title 1 ...great.... if we go to the
(firestore) database yes we have the title 1 the title 2 and title 3 okay now
we have our application that is
independent of frameworks that is
independent from databases that is
independent from the UI because it's a
restful api so we don't care if we get
requests from a mobile application or
from a web browser for example and we have a testable
application because we have different
implementations from an interface so we
can mock that interface and we can test
using that mock implementation or we can

Spanish: 
todavía obtenemos los datos y vamos a crear una nueva publicación digamos "Título 3" y "Texto 3" sí
obtenemos una respuesta exitosa y si
vamos de nuevo tenemos todas las
las publicaciones: "título 2", "título 3" y "título 1" ... genial ... si vamos a la
base de datos (Firestore)...sí tenemos el "título 1", el "título 2" y el "título 3" bien ahora
tenemos nuestra aplicación que es
independiente de frameworks, es
independiente del motor de base de datos,  es independiente de la interfaz de usuario porque es una
API REST, así que no nos importa si 
tenemos solicitudes (HTTP requests) desde una aplicación móvil o
desde un navegador web.... y también tenemos una aplicación
testeable porque tenemos diferentes
implementaciones de una interfaz por lo que
podemos utilizar Mocking de esa interfaz y podemos probar
utilizando esa implementación simulada o podemos

English: 
still get the data and let's create a
new post let's say "Title 3" and "Text 3" yeah
we get a successful response and if
we go again we get all the
posts we get title 2, title 3 and title 1 ...great.... if we go to the
(firestore) database yes we have the title 1 the title 2 and title 3 okay now
we have our application that is
independent of frameworks that is
independent from databases that is
independent from the UI because it's a
restful api so we don't care if we get
requests from a mobile application or
from a web browser for example and we have a testable
application because we have different
implementations from an interface so we
can mock that interface and we can test
using that mock implementation or we can

English: 
also test our repo using an "in-memory"
database and the same for the controller
and we can mock the service and we can
unit test our controller and the same
for the service right we can mock the
repository and we can unit test our
service we can test our business logic
for example the service is the place
where we have our use case or our
business logic so the idea here is in
order to test this business logic
without depending on any external
libraries or any external dependencies
we can mock this repository and we can
make that mock implement this post
repository interface and we can isolate
this service and unit test it okay
that's all I have for today hopefully
Uncle Bob is proud :-)... thank you for
watching, remember to share like and

English: 
also test our repo using an "in-memory"
database and the same for the controller
and we can mock the service and we can
unit test our controller and the same
for the service right we can mock the
repository and we can unit test our
service we can test our business logic
for example the service is the place
where we have our use case or our
business logic so the idea here is in
order to test this business logic
without depending on any external
libraries or any external dependencies
we can mock this repository and we can
make that mock implement this post
repository interface and we can isolate
this service and unit test it okay
that's all I have for today hopefully
Uncle Bob is proud :-)... thank you for
watching, remember to share like and

Spanish: 
también probar nuestro repositorio usando una base de datos "en memoria" y lo mismo para el controlador
y podemos usar un Mock del servicio y podemos hacer una prueba de unidad de nuestro controlador y lo mismo
para el servicio correcto podemos usar un mock del repositorio y podemos probar unitariamente el servicio...
...podemos probar nuestra lógica de negocio..el servicio es el lugar
donde tenemos nuestros caso de usos o nuestra lógica de negocios por lo que la idea aquí es...
probar esta lógica de negocios
sin depender de ninguna librería, framework
o dependencias externas
podemos usar un mock de este repositorio y podemos
hacer que ese mock implemente la interfaz PostRepository y podemos aislar
este servicio y e implementar unit testing (testing unitario del servicio)...
Eso es todo lo que tengo para hoy con suerte
El tío Bob está orgulloso : -) ... gracias por
estar allí, recuerden compartir, dar "me gusta" y

Spanish: 
suscribirse al canal (muy agradecido por eso, en serio) y te veo
en el siguiente video, cuídate, Gracias!

English: 
subscribe to the channel (really appreciated) and I see you
in the next video, take care, bye!

English: 
subscribe to the channel (really appreciated) and I see you
in the next video, take care, bye!
