Files
dkala-api/src/modules/auth/transformers/admin-login.transformer.ts
T
2026-02-08 09:18:20 +03:30

94 lines
2.3 KiB
TypeScript

import type { Admin } from '../../../admin/entities/admin.entity';
import type { Shop } from ../../..shops/entities/shop.entity';
export interface AdminLoginResponse {
id: string;
firstName?: string;
lastName?: string;
phone: string;
role: string;
permissions: string[];
shop?: {
id: string;
name: string;
slug: string;
};
}
export class AdminLoginTransformer {
static async transform(admin: Admin, shop?: Shop): Promise<AdminLoginResponse> {
// Find the AdminRole that matches the shop (or get the first one)
let adminRole = admin.roles.getItems().find(r => (shop ? r.shop?.id === shop.id : true));
// If no match found, get the first one
if (!adminRole && admin.roles.getItems().length > 0) {
adminRole = admin.roles.getItems()[0];
}
if (!adminRole) {
return {
id: admin.id,
firstName: admin.firstName,
lastName: admin.lastName,
phone: admin.phone,
role: '',
permissions: [],
shop: shop
? {
id: shop.id,
name: shop.name,
slug: shop.slug,
}
: undefined,
};
}
// Get the role from AdminRole
const role = adminRole.role;
if (!role) {
return {
id: admin.id,
firstName: admin.firstName,
lastName: admin.lastName,
phone: admin.phone,
role: '',
permissions: [],
shop: shop
? {
id: shop.id,
name: shop.name,
slug: shop.slug,
}
: undefined,
};
}
// Extract permissions - ensure collection is loaded if needed
let permissions: string[] = [];
if (role.permissions) {
if (role.permissions.isInitialized()) {
permissions = role.permissions.getItems().map(p => p.name);
} else {
await role.permissions.loadItems();
permissions = role.permissions.getItems().map(p => p.name);
}
}
return {
id: admin.id,
firstName: admin.firstName,
lastName: admin.lastName,
phone: admin.phone,
role: role.name,
permissions,
shop: shop
? {
id: shop.id,
name: shop.name,
slug: shop.slug,
}
: undefined,
};
}
}