deno

How to Build REST API with Deno, MySQL

By Rasyue | On June 26, 2020

Hi folks! In this tutorial we are going to build a REST API with Deno. We will be writing code for Deno server that can connect to MySQL.

Introduction

Deno is a runtime for JavaScript and TypeScript that is based on the V8 JavaScript engine and the Rust programming language. Since its release in 2018, Deno has been gaining popularity over the last couple of years. It might be a good idea for programmers to learn a bit or two about Deno. Let’s dive in!

Typescript or Javascript?

Well, since Deno is a runtime for Javascript and Typescript, we can write in either Javascript or Typescript to create our application. You may also write in both language if you feel like so. However, being a Typescript fan, I am going to write this in Typescript.

Deno Server with Attain

Deno comes with a LOT of modules that can help you create you server. You can check out my other post, How to Build a Back-end Server with Deno to see how to start your server with Reno and Denotrain. In this tutorial, I will be using abc.

Now, let’s create a file and name it app.ts. Open up the file, copy the code below and paste into your file.

import { App, Request, Response } from "https://deno.land/x/attain/mod.ts";

const app = new App();

const sampleMiddleware = (req: Request, res: Response) => {
  console.log("before send")
};

app.get("/:id", (req, res) => {
  console.log(req.params);
  res.status(200).send(`id: ${req.params.id}`);
})

app.use(sampleMiddleware, (req, res) => {
  res.status(200).send({status: "Welcome to rasyue.com"});
});

app.listen({ port: 3500 });

console.log("http://localhost:3500");

Okay, what we did above is pretty basic things, similar to Express in NodeJs, we are defining our server. To run the script above, make sure you use the --allow-net flag. Now, let’s create routes to fetch user data and create user and also create our typescript for database.

First, let’s create a file to connect to MySQL database. Make sure you have your MySQL database running. I am using XAMPP in this tutorial. Create mysql_db.ts. Open it and copy the code below into it.

//mysql_db.ts

import Dex from "https://deno.land/x/dex/mod.ts";
import Dexecutor from "https://deno.land/x/dexecutor/mod.ts";





export class MySQL {
    client = "mysql";
    dexecutor = new Dexecutor({
        client: this.client,
        connection: {
            host: "localhost",
            user: "root",
            password: "",
            port: 3306,
            database: "rasyue_mysql",
        }   
    });

    dex = new Dex({
        client: this.client
    });

    constructor(){

    }


    async fetchUsers(){
        await this.dexecutor.connect();

        const result = await this.dexecutor.execute("SELECT * FROM users")
      
        await this.dexecutor.close();

        return result;
        
    }

    async createUser(username: string, email: string, age: number){

        await this.dexecutor.connect();

        //const sql = "INSERT INTO users (username, email, age) VALUES ('')";       
        const sqlQuery = this.dex.queryBuilder()
            .insert([
                {username: username, email: email, age: age}
            ])
            .into("users")
            .toString();

        const result = await this.dexecutor.execute(sqlQuery);

        await this.dexecutor.close();

        return result;
    }
}

Open app.ts and replace the whole content with below.

import { App, Request, Response, parser } from "https://deno.land/x/attain/mod.ts";
import { MySQL } from './mysql_db.ts';

const app = new App();
app.use(parser);
const sampleMiddleware = (req: Request, res: Response) => {
 
};



app.get("/fetch-users", async (req: Request, res: Response) => {
 
  const abc = new MySQL();
  const result = await abc.fetchUsers().then(resp => {    
    console.log(JSON.stringify(resp))
    return res.send({
      status: 200,    
      data : resp
    });
  })
})


app.post("/create-user", (req, res) => {
  const { username, email, age } = req.params
  const abc = new MySQL();
  const result = abc.createUser(username, email, age);
  res.status(200).send(`Successful`);
})

app.use(sampleMiddleware, (req, res) => {
  res.status(200).send({status: "Welcome to rasyue"});
});



app.listen({ port: 3500 });

console.log("http://localhost:3500");

Run the above with deno run --allow-net app.ts. You can use Postman to add your user through the /create-user POST endpoint.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

*
*