74 lines
1.6 KiB
TypeScript
74 lines
1.6 KiB
TypeScript
import {
|
|
DataTypes,
|
|
Model,
|
|
ModelStatic,
|
|
Sequelize
|
|
} from 'sequelize';
|
|
|
|
export class DatabaseManager {
|
|
private readonly db: Sequelize;
|
|
|
|
public guildData: ModelStatic<Model> | null = null;
|
|
public userData: ModelStatic<Model> | null = null;
|
|
|
|
private constructor() {
|
|
this.db = new Sequelize('db', 'luma', '', {
|
|
host: 'localhost',
|
|
dialect: 'sqlite',
|
|
storage: 'db.sqlite',
|
|
logging: false
|
|
});
|
|
|
|
this.db.sync();
|
|
}
|
|
|
|
public async init(userKeys: object, guildKeys: object) {
|
|
this.userData = this.db.define('user_data', {
|
|
user_id: { type: DataTypes.STRING, unique: true, primaryKey: true },
|
|
...userKeys
|
|
});
|
|
|
|
this.guildData = this.db.define('guild_data', {
|
|
guild_id: { type: DataTypes.STRING, unique: true, primaryKey: true },
|
|
...guildKeys
|
|
});
|
|
|
|
await this.db.sync({ alter: true });
|
|
}
|
|
|
|
public sync(): void {
|
|
this.db.sync();
|
|
}
|
|
|
|
public async getUser(userId: string) {
|
|
if (!this.userData) throw new Error('Database not initialized');
|
|
|
|
const [user] = await this.userData.findOrCreate({
|
|
where: { user_id: userId },
|
|
defaults: { user_id: userId }
|
|
});
|
|
return user;
|
|
}
|
|
|
|
public async getGuild(guildId: string) {
|
|
if (!this.guildData) throw new Error('Database not initialized');
|
|
|
|
const [guild] = await this.guildData.findOrCreate({
|
|
where: { guild_id: guildId },
|
|
defaults: { guild_id: guildId }
|
|
});
|
|
return guild;
|
|
}
|
|
|
|
/*
|
|
singleton logic
|
|
*/
|
|
static #instance: DatabaseManager | null = null;
|
|
|
|
public static get get(): DatabaseManager {
|
|
if (!DatabaseManager.#instance)
|
|
DatabaseManager.#instance = new DatabaseManager();
|
|
return DatabaseManager.#instance;
|
|
}
|
|
}
|