一起來(lái)完成以下步驟:
- Window上安裝deno
- 運(yùn)行第一個(gè)Hello World 應(yīng)用
- 增加Router功能
- 新增實(shí)體類Employee
- 對(duì)實(shí)體類進(jìn)行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
}
}
//獲取一個(gè)員工
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;
}
完