const DbService = require("moleculer-db"); const SQLAdapter = require("moleculer-db-adapter-sequelize"); const Sequelize = require("sequelize"); const { MoleculerError } = require("moleculer").Errors; module.exports = { name: "database", mixins: [DbService], adapter: new SQLAdapter("postgres://postgres:postgres@localhost:5432/doors_db"), model: { name: "users", define: { user_id: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true }, email: { type: Sequelize.STRING, unique: true, allowNull: false }, password_hash: { type: Sequelize.STRING, allowNull: false }, create_date: { type: Sequelize.DATE, defaultValue: Sequelize.NOW }, kyc_status: { type: Sequelize.BOOLEAN, defaultValue: false }, status_id: { type: Sequelize.INTEGER } }, options: { timestamps: false } }, actions: { emailExists: { params: { email: "string" }, async handler(ctx) { try { const count = await this.adapter.count({ where: { email: ctx.params.email } }); return count > 0; } catch (e) { console.error(e); throw new MoleculerError("Database operation failed", 500, "DATABASE_ERROR", { code: "DATABASE_ERROR", message: e.message }); } } }, createUser: { params: { email: { type: "string", min: 1 }, password_hash: { type: "string", min: 1 } }, async handler(ctx) { try { const userExists = await this.actions.emailExists({ email: ctx.params.email }); if (userExists) { throw new MoleculerError("Email already exists", 400, "EMAIL_EXISTS", { email: ctx.params.email }); } return await this.adapter.insert(ctx.params); } catch (e) { console.error(e); throw new MoleculerError("Database operation failed", 500, "DATABASE_ERROR", { code: "DATABASE_ERROR", message: e.message }); } } } } };