Deno增删查改(CRUD)应用

Deno Router基本应用

一起来完成以下步骤:

  1. Window上安装deno
  2. 运行第一个Hello World 应用
  3. 增加Router功能
  4. 新增实体类Employee
  5. 对实体类进行CRUD

#main.ts

import { Application } from "https://deno.land/x/oak/mod.ts";
import router  from "./router.ts";

const app = new Application();

app.use(router.routes()); app.use(router.allowedMethods());  await app.listen({ port: 8000 }); 

#router.ts

import { Router,Context } from "https://deno.land/x/oak/mod.ts";
import { getEmployees,getEmployee,addEmployee,updateEmployee,deleteEmployee } from "./employees.ts";

const router = new Router();

router.get("/hello",(context : Context) =>{  context.response.body="Hello World"; }); router.get("/employees",getEmployees); router.get("/employee/:id",getEmployee); router.post("/employee",addEmployee); router.put("/employee",updateEmployee); router.delete("/employee/:id",deleteEmployee);  export default router; 

#employees.ts


import { Employee } from "./types.ts";
import ShortUniqueId from 'https://cdn.jsdelivr.net/npm/short-unique-id@latest/short_uuid/mod.ts';

let employees :Employee [] =[
 {  id:"1",  name:"michael",  age:24  },  {  id:"2",  name:"alex",  age:25  },  {  id:"3",  name:"deny",  age:26  } ];  //获取所有员工 const getEmployees = ({response}:{response:any}) =>{  response.body = {  success : true,  data : employees  } }  //获取一个员工 const getEmployee = ({params,response}:{params:{id:string},response:any}) =>{  const hadEmployee = employees.find(employee => employee.id === params.id);  if(hadEmployee){  response.body={  success:true,  data:hadEmployee  }  }else{  response.body={  success:false,  data:"No employee found"  }  } }  //新增 const addEmployee = async ({ request,response }:{request:any,response:any}) =>{  const body = await request.body();  const newEmployee = body.value;  const uid = new ShortUniqueId();  newEmployee.id = uid();  employees.push(newEmployee);  response.body = {  success : true,  msg :newEmployee  } }  //修改 const updateEmployee = async ( {request,response }:{request:any,response:any}) =>{   const body = await request.body();  const updateEmployee = body.value;  if(updateEmployee.id){  const index = employees.findIndex(e=>e.id === updateEmployee.id);  if(index !== -1){ //如果员工存在  console.log("idnex: "+ index);  employees[index] = updateEmployee;  response.body = {  success : true,  data :updateEmployee  }  }else{  response.body = {  success : false,  data :"No Employee found"  }  }  } }  //删除 const deleteEmployee = ({params,response}:{params:{id:string}, response:any}) =>{  employees= employees.filter(e => e.id ! === params.id);  response.body = {  success : true,  msg:"Employee "+ params.id + " was deleted"  } }  export { getEmployees,getEmployee,addEmployee,updateEmployee,deleteEmployee}  

#types.ts

export interface Employee{
    id:string;
    name:string;
    age:number;
}

你可能感兴趣的:(Deno)