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