MariaDB connection using ORM in Deno


Let’s move into another interesting sections, the database where we store information processed. In this post we are connecting MariaDB local database using ORM , denodb.

We can use the same MySQL connector for MariaDB with almost no change

Denodb-ORM

This is a third party ORM module for deno which will help us to MariaDB in Deno. The ORM module work through Model, so we can perform operations using Model, no worry about confusing, queries and statements.

APP

Our app is a simple Todo application, which store Todo’s in a MariaDB database.

  • create a configuration
  • Create Models
  • Link Model and Sync

Configuration

Usually we kept the database file under a config folder, the name of our file will database.ts and content s follows. In the final steps of the configuration we export the model.

import { Model, Database, MySQLConnector, DataTypes } from 'https://deno.land/x/denodb/mod.ts';
//config for MariaDB using MySQKConnector
const connector = new MySQLConnector({
  database: 'todo_collections',
  host: '127.0.0.1',
  username: 'root',
  password: '123',
  port: 3306, // optional
});


const db = new Database(connector)

// NOTE Models 
class Todo extends Model {
    static table = 'todos';
    static fields = {
        id: {
            type: DataTypes.INTEGER,
            autoIncrement: true,
            primaryKey: true,
        },
        item: {
            type: DataTypes.STRING,
        }
        ,
        description: {
            type: DataTypes.STRING,
        }
    };
}
// NOTE Linking Model with DB
db.link([Todo])
await db.sync()

 export default Todo;

You have to specify the host which is localhost, user and password, database name (you should create them first) and we are ready for the controllers.

Sync () – will create the tables for you. You have to create the database which in not created by the sync. Optionally you can use {drop:true} for deleting table every time, the app runs

SQLite app using denodb in Deno


Let’s move into another interesting sections, the database where we store information processed. In this post we are store data into local SQLite database/

Denodb-ORM

This is a third party ORM module for deno which will help us to connect MySQL, MariaDB, SQLite and Postgres databases. The ORM module work through Model, so we can perform operations using Model, no worry about confusing, queries and statements.

APP

Our app is a simple Todo application, which store Todo’s in a MySQL database.

  • create a configuration
  • Create a SQLite file
  • Create Models
  • Link Model and Sync

Configuration

Usually we kept the database file under a config folder, the name of our file will database.ts and content s follows. In the final steps of the configuration we export the model.

import { Model, Database, SQLite3Connector, DataTypes } from "../deps.ts";

const connector = new SQLite3Connector({
    filepath: './database.sqlite',
});

const db = new Database(connector)

// NOTE Models 
class Todo extends Model {
    static table = 'todos';
    static fields = {
        id: {
            type: DataTypes.INTEGER,
            primaryKey: true,
        },
        item: {
            type: DataTypes.STRING,
        }
        ,
        description: {
            type: DataTypes.STRING,
        }
    };
}
// NOTE Linking Model with DB
db.link([Todo])
await db.sync()

 export default Todo;

Sync () – will create the tables for you. You have to create the database which in not created by the sync.

MySQL connection using ORM in Deno


Let’s move into another interesting sections, the database where we store information processed. In this post we are connecting MySQL local database using ORM , denodb.

Denodb-ORM

This is a third party ORM module for deno which will help us to connectMySQL db in Deno. The ORM module work through Model, so we can perform operations using Model, no worry about confusing, queries and statements.

APP

Our app is a simple Todo application, which store Todo’s in a MySQL database.

  • create a configuration
  • Create Models
  • Link Model and Sync

Configuration

Usually we kept the database file under a config folder, the name of our file will database.ts and content s follows. In the final steps of the configuration we export the model.

import { Model, Database, MySQLConnector, DataTypes } from 'https://deno.land/x/denodb/mod.ts';

const connector = new MySQLConnector({
  database: 'todo_collections',
  host: '127.0.0.1',
  username: 'root',
  password: '123',
  port: 3306, // optional
});


const db = new Database(connector)

// NOTE Models 
class Todo extends Model {
    static table = 'todos';
    static fields = {
        id: {
            type: DataTypes.INTEGER,
            autoIncrement: true,
            primaryKey: true,
        },
        item: {
            type: DataTypes.STRING,
        }
        ,
        description: {
            type: DataTypes.STRING,
        }
    };
}
// NOTE Linking Model with DB
db.link([Todo])
await db.sync()

 export default Todo;

You have to specify the host which is localhost, user and password, database name (you should create them first) and we are ready for the controllers. I use the default port for MySQL.

Sync () – will create the tables for you. You have to create the database which in not created by the sync. Optionally you can use {drop:true} for deleting table every time, the app runs

MySQL connection in Deno


Let’s move into another interesting sections, the database where we store information processed. In this post we are connecting MySQL local database using denodrivers.

APP

Our app is a simple Todo application, which store Todo’s in a MySQL database.

Denodrivers

This is a third party module for deno which will help us to build a connection to MySQL db. We are going todo the following

  • create a configuration
  • Insert,Update,Delete
  • Querying database

Configuration

Usually we kept the database file under a config folder, the name of our file will database.ts and content s follows

import { Client } from "https://deno.land/x/mysql/mod.ts";
const client = await new Client().connect({
  hostname: "127.0.0.1",
  username: "root",
  db: "todo_collections",
  poolSize: 3, // connection limit
  password: "123",
});

export default  { client }

You have to specify the host which is localhost, user and password, database name (you should create them first) and we are ready for the controllers.

How to create CLI scripts in Deno Part II:cliffy


If you miss the first part here is the links

cliffy

This is a third party CLI framework for deno which will help you to build command line application using,

  • options
  • commands
  • event handlers
  • sub commands

For more info and example visit the official repository. To explore the frame work go through the example. The repo lack documentation, I know but the developer provide a good set of examples.

Greet CLI

Here is a quick example.

 import { Command } from "https://deno.land/x/cliffy@v0.17.0/command/mod.ts";

new Command()
    .name('Greet')
    .version('0.0.1')
    .description('Greet')
    .example('Greeting people',"greet -g good-night")  
    .option("-g --msg <msg:string>","Greeting with no space",{
        default:'Good morning' ,               
        action:async({msg})=>{
            console.log(msg);
        }
    })
    .parse(Deno.args)

The above is simple greet program with Cliffy framework, which use option for -g for message, also have default value for the option

Run the script in deno

//run the script
deno run app.ts -g good-evening
//output 
good-evening
//bring help
deno run app.ts -h

Install the script locally

We can install our script locally using the deno install command so that can run without a deno command along shell.

deno install --unstable -f -n greet app.ts

Here -f is used to overwrite the existing file which is optional , -n is used to specify the name of the command which also optional (it will take the name of the .ts file instead, if no name is specified). The install command will place the file in your deno home directory.

Run the command

Running the command is as simple as running dir in shell.

greet -g Good-evening
//try bring some help
greet -h
greet -anything

A complete CLI project for Deno users is hosted at GitHub, have a look.

You may love to read these Deno posts

How to host deno modules in GitHub


Deno uses URL for dependency management and don’t have dependency module folder like Node has.

We can use GitHub to host our modules , if you wish. For that

  • Need to create a repository
  • Push the changes with Tag

Go to the repository and find module file / mod.ts and open it as raw , copy the url in to your project and use it as

import mod from 'https://raw.githubusercontent.com/manojap/Deno-CLI-create-app-master/master/src/deps.ts'

All of my Deno projects will be published on my GitHub Repo, so keep watching.

Use dotenv in Deno


Deno is asynchronous JavaScript/TypeScript runtime. If you are not sure how and what’s of Deno, here is the links

Dotenv

dontenv is a musch familiar module for Node users, it is used to create environment variables to store secrets, Uri, port etc.

Deno have two types of module system standard and third party modules. Third party modules are from the opensource community. dontenv is one of them. You can also contribute modules to the third party library.

setup .env

Create a .env file and place the APP_PORT=3002 in the file where main.ts located.

  • import the module
  • create env constant
  • access the values through constant
import { Application }  from 'https://deno.land/x/oak@v6.0.1/mod.ts'; 
import { config } from 'https://deno.land/x/dotenv/mod.ts';
 
const env = config()
const app = new Application();
const PORT = +env.PORT || 3000 //+convert it number  
app.use( ()=>{
    console.log('Hello world');    
});
app.listen({ port:PORT });
console.log(`Server running on port ${PORT}`);

Everything in .env file is string, it is ideal for placing API, urls, dblinks et. We used + to convert the port string to number because deno port should be anumber

To run the app we need two permission one for url and other for reading .env file.

deno run --allow-net --allow-read main.ts

Now jump into the browser access your route http://127.0.0.1/.

To stop the running server use Ctrl+C

All of my Deno projects will be published on my GitHub Repo, so keep watching.

How to create routes in Deno


In our base app tutorial we have seen how to create default page for our app. It is not a route, it’s middle-ware. In this example we create some basic routes using oak Router and add it as middle ware using the use method.

routes are the pages/links in a site, such as index page, about page, contact page etc

Create routes

We can create Oak router for our app in the same file. But as the application develop, the code become large, so in order to make it simple and easy to handle we keep routes in separate file and later include them as middle-ware to the main application.

In a folder called routes create a file route.ts

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

const router = new Router()

router.get('/', (ctx) => {
  ctx.response.body = 'Home Page'
  ctx.response.status = 200
  
})

router.get('/about', (ctx) => {
  ctx.response.body = 'About Page'
  ctx.response.status = 200
  
})

router.get('/products', (ctx) => {
  ctx.response.body = 'Products Page'
  ctx.response.status = 200
  
})

export default router;

In the first line we import the Router from the Oak module, which is used to create our basic site routes. Then we export the router and will call the routers in the main.ts as follows.

Here ‘/’ route is the default page / index page of our app.

Arrow function

Every routes carry a function (ctx) =>, which is arrow function (feature of js and ts) having a context argument.

In bigger applications the functions are separated from routes and placed under folder controllers.

Each route can send message as response , also send a status code (which can be seen using developer tools) .

//main.ts
import { Application } from "https://deno.land/x/oak/mod.ts";
import router from './routes/route.ts'
const app = new Application();

app.use(router.routes())
app.use((ctx) => {
    ctx.response.body = "Not found";
});

app.listen({ port: 8000 });
console.log('Server running on port 8000')

In the main.ts we added the route as middle ware, lets run the app with net permission.

deno run --allow-net main.ts

Now jump into the browser access your route http://127.0.0.1/.

To stop the running server use Ctrl+C

All of my Deno projects will be published on my GitHub Repo, so keep watching.

How to read a text file in Deno


Deno is asynchronous JavaScript/TypeScript runtime. If you are not sure how and what’s of Deno, here is the links

Read a text file

Deno API allows developers to read files using readTextFile() which return a promise. A promise is similar to future in flutter, the result of the job will come in as a future.

You know that Deno is async by default, in the async world program continue working without interrupting other jobs.

const text = Deno.readTextFile("./data.json");
text.then((response) => console.log(response));

Here the text constant will return the resulted content in this operation.

To run this script yo may allow deno to use –allow-read permission.

deno run --allow-read maint.ts

All of my Deno projects will be published on my GitHub Repo, so keep watching.

How to create a text file in Deno


Deno is asynchronous JavaScript/TypeScript runtime. If you are not sure how and what’s of Deno, here is the links

Create a textfile

Deno API allows developers to write files using writeTextFile() which return a promise. A promise is similar to future in flutter, the result of the job will come in future.

You know that Deno is async by default, in the async world program continue working without interrupting other jobs.

const write = Deno.writeTextFile("./hello.txt", "Hello World!");
write.then(() => console.log("File written to ./hello.txt"));

Here the write constant will return result / only if the operation is succeeded.

To run this script yo may allow deno to use –allow-write permission.

deno run --allow-write maint.ts

All of my Deno projects will be published on my GitHub Repo, so keep watching.