A lot of people are paying attention to Deno, and I’m no exception. After all, it’s another masterpiece from the father of NodeJS. This article will use Deno to write a simple TodoList RestApi for a taste.

What is Deno?

Deno is a Javascript/Typescript runtime environment written in Rust based on the V8 engine.

Deno Features

  • Use TypeScript or JavaScript
  • ES Modules
  • Secure by Default
  • Top Level / First Class Await
  • De-centralized Packages
  • Built In Testing
  • Standard Library
  • Browser Compatible API
  • Modern JS

Project to write

The directory structure

  • controller
    • Tasks. ts defines the controller
  • Router. ts defines the project route
  • Server. ts project main entry, create HTTP server
  • The tasks. HTTP test API
  • Types. Ts defines the interface

The data is static, and no service is written without connecting to the database.

The main logic

Server.ts

import { Application } from 'https://deno.land/x/oak/mod.ts'
import router from './router.ts'
const port = 5000

const app = new Application()

app.use(router.routes())
app.use(router.allowedMethods())

console.log(`Server running on port ${port}`)

await app.listen({ port })
Copy the code

router.ts

import { Router } from 'https://deno.land/x/oak/mod.ts'
import { getTasks, getTask, updateTask, deleteTask, addTask } from './controller/tasks.ts'
const router = new Router()


router.get('/api/v1/tasks', getTasks)
      .get('/api/v1/tasks/:id', getTask)
      .post('/api/v1/tasks', addTask)
      .put('/api/v1/tasks/:id', updateTask)
      .delete('/api/v1/tasks/:id', deleteTask)

export default router
Copy the code

/contraller/tasks.ts

import { v4 } from 'https://deno.land/std/uuid/mod.ts'
import { Task } from '.. /types.ts'

let tasks: Task[] = [
    {
        id: "1",
        name: "Learning Deno",
        description: "Write a short example using Deno.",
        completed: false
    },
    {
        id: "2",
        name: "Studying Nodejs",
        description: "Write a short example using Nodejs.",
        completed: false
    },
    {
        id: "3",
        name: "Learning Vue",
        description: "Write a short example using Vue.",
        completed: false
    },
    {
        id: "4",
        name: "Learning the React",
        description: "Let's write a quick example using React.",
        completed: false
    },
    {
        id: "5",
        name: "Learning presents",
        description: "Write a short example using Angular",
        completed: false}]/** @desc get all tasks * @route GET /api/v1/tasks */
const getTasks = ({ response }: { response: any }) = > {
    response.body = {
        success: true,
        data: tasks
    }
}

/** @desc get single task * @route GET /api/v1/tasks/:id */
const getTask = ({ params, response }: { params: {id: string} ,response: any }) = > {
    const task: Task | undefined = tasks.find(t= > t.id === params.id)
    if(task) {
        response.status = 200
        response.body = {
            success: true,
            data: task
        }
    } else {
        response.status = 404
        response.body = {
            success: false,
            message: 'No task found'}}}/** @desc add task * @route POST /api/v1/tasks */
const addTask = async ({ request, response }: { request: any,response: any= > {})const body = await request.body()
    if(! request.hasBody){ response.status =400
        response.body = {
            success: false,
            message: 'No data'}}else {
        const task: Task = body.value
        task.id = v4.generate()
        tasks.push(task)
        response.status = 201
        response.body = {
            success: true,
            data: task
        }
    }
}

/** @desc update task by id * @route PUT /api/v1/tasks/:id */
const updateTask = async ({ params, request, response }: {  request: any, params: {id: string}, response: any= > {})const index: number = tasks.findIndex(t= > t.id === params.id)
    if(index ! = =- 1) {
        const body = await request.body()

        constupdateData: {name? :string, description? :string, completed? :boolean} = body.value tasks[index] = {... tasks[index], ... updateData} response.status =200
        response.body = {
            success: true,
            data: tasks[index]
        }
    } else {
        response.status = 404
        response.body = {
            success: false,
            message: 'No task found'}}}/** @desc Delete task by id * @route DELETE /api/v1/tasks/:id */
const deleteTask = ({ params, response }: {  params: {id: string},response: any }) = > {
    const index: number = tasks.findIndex(t= > t.id === params.id)
    if(index ! = =- 1) {
        tasks.splice(index,1)
        response.status = 200
        response.body = {
            success: true,
            message: 'Task Removed'}}else {
        response.status = 404
        response.body = {
            success: false,
            message: 'No task found'}}}export { getTasks, getTask, addTask, updateTask, deleteTask }
Copy the code

It can be seen that the difference between express and KOA is not particularly large.

The API test

@ host = http://localhost:5000/api/v1 # # # GET ALl the tasks the GET {{host}} / tasks HTTP / 1.1 # # # GET single task a GET {{host}}/tasks/1 HTTP/1.1 ### add task POST {{host}}/tasks HTTP/1.1 Content-type: application/json {"name": "Study Electron", "description":" Write a short case using Electron", "completed": False} ### update task PUT {{host}}/tasks/1 HTTP/1.1 Content-Type: Application /json {"name": "test ", "description": "Test update interface ", "completed": true} ### delete task delete {{host}}/tasks/1 HTTP/1.1Copy the code

conclusion

We are constantly optimizing the performance of Deno’s HTTP server. For the ‘Hello World’ example, the DenoHTTP server processes approximately 25,000 requests per second with a maximum latency of 1.3ms. The Node server processes 34,000 requests per second with a maximum latency between 2 and 300ms.

This quote is from the Deno website. According to the official website, deno’s HTTP performance is much better than Node’s, but it’s still hard to replace Node at this point. Node’s ecology is too rich. Personally, what I like about deno is:

  • The built-in TypeScript compiler is fun to write
  • The package.json management dependency pattern has been removed and no longer relies on NPM. (One of my biggest headaches with NPM is that the package download sometimes fails, and there is a node_modules for every project I write)
  • There is an official standard library, according to the official standard library to develop their own things. I think it’s good that the standard library will always follow the version, and there will be no third party libraries that will not be updated when they are published. And third party development library, there are always some hidden dangers.
  • HTTP server performance is high!!

In short, we can look forward to Deno, and we can try to transfer Deno when the ecology is enriched.

Welcome to exchange 👏.