ExpressJs

⌘K
  1. Home
  2. Docs
  3. ExpressJs
  4. Role And Permission
  5. Entities Definition
  6. 5.UserRole(কোন ইউজারের কোন রোল )

5.UserRole(কোন ইউজারের কোন রোল )

userRole.entity.js

// entities/userRole.entity.js
const { EntitySchema } = require('typeorm');

module.exports = new EntitySchema({
    name: 'UserRole',
    tableName: 'user_roles',
    columns: {
        userId: {
            type: 'int',
            primary: true,
        },
        roleId: {
            type: 'int',
            primary: true,
        },
    },
    relations: {
        user: {
            target: 'User',
            type: 'many-to-one',
            joinColumn: { name: 'userId' },
        },
        role: {
            target: 'Role',
            type: 'many-to-one',
            joinColumn: { name: 'roleId' },
        },
    },
});

userRole.service.js

// services/userRole.service.js
const AppDataSource = require('../config/database');
const User = require('../entities/User'); // Import User entity
const Role = require('../entities/Role'); // Import Role entity
const UserRole = require('../entities/UserRole'); // Import UserRole entity

/**
 * Assigns a role to a specific user.
 * @function assignRoleToUser
 * @param {object} data - Object containing userId and roleId.
 * @returns {Promise<object>} - Returns a success message or an error.
 */
const assignRoleToUser = async (data) => {
    const { userId, roleId } = data;

    try {
        // Fetch user and role repositories
        const userRepository = AppDataSource.getRepository(User);
        const roleRepository = AppDataSource.getRepository(Role);
        const userRoleRepository = AppDataSource.getRepository(UserRole);

        // Find user and role by their IDs
        const user = await userRepository.findOne({ where: { id: userId } });
        const role = await roleRepository.findOne({ where: { id: roleId } });

        if (!user) {
            throw new Error('User not found');
        }

        if (!role) {
            throw new Error('Role not found');
        }

        // Check if the role is already assigned to the user
        const existingUserRole = await userRoleRepository.findOne({
            where: { user: { id: userId }, role: { id: roleId } },
        });

        if (existingUserRole) {
            throw new Error('Role is already assigned to this user');
        }

        // Create and save a new UserRole entity
        const userRole = new UserRole();
        userRole.user = user;
        userRole.role = role;
        await userRoleRepository.save(userRole);

        return { message: 'Role successfully assigned to the user' };
    } catch (error) {
        // Return an error message in case of failure
        return { message: 'Failed to assign role', error: error.message };
    }
};

module.exports = {
    assignRoleToUser,
};

How can we help?