kodex-music-catalog/database.js
2023-10-01 22:31:26 +03:00

137 lines
2.6 KiB
JavaScript

const { Sequelize, DataTypes } = require("sequelize");
class Table {
constructor(model) {
this.model = model;
}
promiseMode() {
return new TablePromise(this.model);
}
get(cb, condition = null) {
this.model
.findAll({ ...(!condition ? {} : condition), raw: true })
.then((data) => cb(null, data))
.catch((err) => cb(err, null));
}
add(item, cb) {
this.model
.create(item)
.then((i) => cb(null, i))
.catch((err) => cb(err, null));
}
remove(condition, cb) {
this.model
.destroy(condition)
.then((i) => cb(null, i))
.catch((err) => cb(err, null));
}
edit(data, condition, cb) {
this.model
.update(data, condition)
.then((i) => cb(null, i))
.catch((err) => cb(err, null));
}
}
class TablePromise extends Table {
async get(condition) {
return await this.model.findAll({
...(!condition ? {} : condition),
raw: true,
});
}
async add(item) {
//setTimeout(() => this.model.findAll(), 0);
return await this.model.create(item);
}
async remove(condition) {
return await this.model.destroy(condition);
}
async edit(data, condition) {
return await this.model.update(data, condition);
}
}
class Database {
constructor(address, port, username, password, database) {
this.sequelize = new Sequelize(
`postgres://${username}:${password}@${address}:${port}/${database}`,
);
this.sequelize.authenticate().then(
() => {
this.authors = new Table(
this.sequelize.define(
"authors",
{
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
allowNull: false,
},
name: {
type: DataTypes.TEXT,
allowNull: false,
},
time: {
type: DataTypes.INTEGER,
allowNull: false,
},
},
{
freezeTableName: true,
timestamps: false,
},
),
);
this.muzic = new Table(
this.sequelize.define(
"muzic",
{
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
allowNull: false,
},
name: {
type: DataTypes.TEXT,
allowNull: false,
},
author_id: {
type: DataTypes.INTEGER,
allowNull: false,
},
data: {
type: DataTypes.BLOB("long"),
},
time: {
type: DataTypes.INTEGER,
allowNull: false,
},
},
{
freezeTableName: true,
timestamps: false,
},
),
);
console.log("Database successful connected!");
},
(err) => {
throw err;
},
);
}
}
module.exports = { Database };