Deno is the new competitor of Node.js in the JavaScript runtime environment category. I developed a Deno REST API based app to test it.

Deno has undoubtedly been quite a hot topic in the JavaScript and Node communities in the past few months. Safe environment, no Node modules, built-in support for TypeScript – these are only some of the benefits of this runtime. But is it ready to be used in the development of REST APIs? Perhaps, writing a simple Deno-based app will help answer that question.

I’m going to use Deno to write a simple app for user management. The app is going to include features such as logging in, registrations and token generation with native Deno libraries. If you are not familiar with what Deno is, start by reading this Deno vs Node comparison article.

If you’re good to go, let’s get started!

HTTP server for Deno application

I’m going to use the Oak middleware as my HTTP server, but to give it a more modern feel, I’m also going to take advantage of the Oak-based Dactyl framework.I need to create my first controller. It’s called UserController.ts and it’s located in the controllers directory. It returns a list of users.

import {
  Controller,
  Get,
  HttpStatus,
} from "https://deno.land/x/dactyl/mod.ts";

@Controller("/users")
export default class User {
  @Get("/")
  getUsers() {
    return [
      { email: "email@tsh.io" },
    ];
  }
}

I used the decorators made available in Dactyl:

@Controller(“/users”) – routing prefix is set in the argument

@Get(“/”) – with this, I configured routing for the method

import { Application } from "https://deno.land/x/dactyl/mod.ts";
import UserController from "./controllers/UserControllers.ts";

const app: Application = new Application({
  controllers: [UserController],
});

Now I need to import the controller, add it to the application generated by Dactyl and set port 8000.

I’m almost ready to launch the REST API. All that’s left for me is to add a file with TypeScript configuration since I’m using experimental decorators.

This is what the tsconfig.json file looks like:

{ 
  "compilerOptions": { 
    "strict": true,
    "esModuleInterop": true,
    "experimentalDecorators": true, 
  }
}

To launch the application, I’m using the command:

deno run –allow-net -c tsconfig.json index.ts

If you follow my directions, you should now see this:

A little explanation about the flags I used here. By default, Deno doesn’t provide access to the network, files etc. for security reasons. In order to be able to launch our app on port 8000, I have to explicitly enable it, using the –allow-net flag and then supply the path to my TypeScript configuration (along with the decorators) with -c tsconfig.json.

I can now get the list of users:

curl http://localhost:8000/users/

#deno #node #javascript #api #programming

Deno REST API – Making a Simple Deno Application
4.50 GEEK