Getting started with Deno (Spanish)

riviergrullon

Rivier Grullon

Posted on May 28, 2020

Getting started with Deno (Spanish)

Este es el segundo post ya sobre Deno en español, la primera parte esta en este enlace: First look with deno(Spanish).

Configurando el entorno de trabajo.

Pasando a la instalación de Deno, abriendo la terminal digitan el siguiente comando:

Shell (macOS, Linux):

curl -fsSL https://deno.land/x/install/install.sh | sh

PowerShell (Windows):

iwr https://deno.land/x/install/install.ps1 -useb | iex

ya instalado Deno en el editor de código asumiendo que es Visual Studio Code pasamos a instalar la extensión que soporta a deno de justjack

Alt Text

ya instalada, en la carpeta .vscode se crea el archivo settings.json. Dentro del archivo se pone

//settings.json
{ "deno.enable": true, }
Enter fullscreen mode Exit fullscreen mode

Comencemos a construir la Rest API

la estructura del proyecto será

.
├── mod.ts
├── controllers
│   └── handlers.ts
└── routes
    └── routes.ts
Enter fullscreen mode Exit fullscreen mode

usaremos el framework Oak.

Comencemos por crear el archivo mod.ts importando Application de https://deno.land/x/oak/mod.ts y el enrutador de './routes/routes.ts'

import { Application } from 'https://deno.land/x/oak/mod.ts'
import router from './routes.ts'
Enter fullscreen mode Exit fullscreen mode

despues se crea el setup del entorno ya sea para poner en deploy o hacerlo local

const env = Deno.env.toObject();

const PORT = env.PORT || 3000;

const HOST = env.HOST || 'localhost';
Enter fullscreen mode Exit fullscreen mode

Ahora creamos el archivo routes.ts:

import { Router } from 'https://deno.land/x/oak@v4.0.0/mod.ts';
import { getDog,deleteDog,updateDog,addDog,getDogs } from '../controllers/handlers.ts';


const router = new Router()
router.get('/dogs', getDogs)
.get('/dogs/:id', getDog)
.post('/dogs', addDog)
.put('/dogs/:id', updateDog)
.delete('/dogs/:id', deleteDog)

export default router
Enter fullscreen mode Exit fullscreen mode

(Las funciones implementadas en estas rutas se crean en el archivo handlers.ts)

ya con esto terminamos nuestro mod.ts

const app = new Application();

console.log(`App is listening in ${HOST} in port ${PORT}`);
app.use(router.routes());
app.use(router.allowedMethods());
await app.listen(`${HOST}:${PORT}`);
Enter fullscreen mode Exit fullscreen mode

Ahora creamos nuestro handlers.ts primero declarando la interfaz para el arreglo de perros

interface Dogs {
  id : string,
  name: string,
  age: number
};

let dogs:Array <Dogs> = [
  {
    id: "1",
    name: 'Pepe',
    age: 2
  },
  {
    id: "2",
    name: 'ajio',
    age: 3
  }
];
Enter fullscreen mode Exit fullscreen mode

creamos el metodo getDogs:

const getDogs = ({ response }: { response: any }) => {
    response.body = dogs
}
Enter fullscreen mode Exit fullscreen mode

Alt Text

getDog: retorna un solo perro

const getDog = ({ params, response }: { params: { id: string }; response: any }) => {
    const dog: Dogs | undefined = searchDogById(params.id)
    if (dog) {
      response.status = 200
      response.body = dogs[0]
    } else {
      response.status = 404
      response.body = { message: `dog not found.` }
    }
  }
Enter fullscreen mode Exit fullscreen mode

Alt Text

addDog: crea un nuevo perro

  const addDog = async ({ request, response }: { request: any; response: any }) => {
    const body = await request.body()
    const dog: Dogs = body.value
    dogs.push(dog);
    response.body = { message: 'OK' }
    response.status = 200
  }
Enter fullscreen mode Exit fullscreen mode

Alt Text
Alt Text

updateDog: actualizar algun dato del perro

  const updateDog = async ({ params, request, response }: { params: { id: string }; request: any; response: any }) => {
    let dog: Dogs | undefined = searchDogById(params.id)
    if (dog) {
      const body = await request.body()
      const updateInfos: { id?: string; name?: string; age?:number} = body.value
      dog = { ...dog, ...updateInfos}
      dogs = [...dogs.filter(dog => dog.id !== params.id), dog]
      response.status = 200
      response.body = { message: 'OK' }
    } else {
      response.status = 404
      response.body = { message: `Dog not found` }
    } 
  }
Enter fullscreen mode Exit fullscreen mode

Alt Text
Alt Text

delete: para eliminar un perro especifico buscando por su id

  const deleteDog = ({ params, response }: { params: { id: string }; response: any }) => {
    dogs = dogs.filter(dog => dog.id !== params.id)
    response.body = { message: 'OK' }
    response.status = 200
  }
const searchDogById= (id: string): ( Dogs | undefined ) => dogs.filter(dog => dog.id === id )[0]

  export{
  getDogs,
  getDog,
  updateDog,
  deleteDog,
  addDog
  }
Enter fullscreen mode Exit fullscreen mode

Alt Text

Fin

💖 💪 🙅 🚩
riviergrullon
Rivier Grullon

Posted on May 28, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related