kodex-music-catalog/database.js
Nikiroy78 f6275b0998 .
2023-10-03 02:50:16 +03:00

165 lines
3.2 KiB
JavaScript

const { Sequelize, DataTypes } = require("sequelize");
const config = require('./config-handler');
/*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.authors = 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.music = this.sequelize.define(
"music",
{
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 = new Database(
config().database.address,
config().database.port,
config().database.username,
config().database.password,
config().database.database
);