Skip to content

MySQL Integration

DolphJS provides first-class support for MySQL databases. While you can use any ORM you prefer, the framework is heavily optimized for seamless integration with Sequelize through the auto-initialization sequence and the @InjectMySQL decorator.

To connect to MySQL, you define the connection parameters in your dolph_config.yaml. The framework will read this file and attempt to establish a connection before starting the server.

dolph_config.yaml
database:
mysql:
host: localhost
user: root
password: my_secure_password
database: dolph_db

Let’s create a Sequelize model for a User.

src/user/user.model.ts
import { DataTypes, Model } from 'sequelize';
// Note: Assuming you export the sequelize instance from a central db file
// or DolphJS provides it. In standard DolphJS, you often define models
// and let the framework or your db initializer sync them.
import { sequelize } from '../db';
export class UserModel extends Model {
public id!: number;
public username!: string;
public email!: string;
}
UserModel.init(
{
id: {
type: DataTypes.INTEGER.UNSIGNED,
autoIncrement: true,
primaryKey: true,
},
username: {
type: new DataTypes.STRING(128),
allowNull: false,
},
email: {
type: new DataTypes.STRING(128),
allowNull: false,
unique: true,
},
},
{
tableName: 'users',
sequelize, // Pass the connection instance
}
);

To keep your business logic clean, use Dependency Injection to provide the model to your Service.

src/user/user.service.ts
import { DolphServiceHandler } from '@dolphjs/dolph/classes';
import { Dolph } from '@dolphjs/dolph/common';
import { InjectMySQL } from '@dolphjs/dolph/decorators';
import { ModelStatic, Model as SqlModel } from 'sequelize';
import { UserModel } from './user.model';
@InjectMySQL('userModel', UserModel)
export class UserService extends DolphServiceHandler<Dolph> {
// TypeScript declaration matching the string in @InjectMySQL
userModel!: ModelStatic<SqlModel<any, any>>;
constructor() {
super('userService');
}
async createUser(data: { username: string; email: string }) {
// We now have full access to Sequelize methods on this.userModel
const user = await this.userModel.create(data);
return user;
}
async findByEmail(email: string) {
return await this.userModel.findOne({ where: { email } });
}
}