jeudi 6 juillet 2023

Feature grouping with NestJS

We are developing a multi-tenant application but I'm running into a situation where I need to use forwardRef quite often which would indicate a code smell as mentioned in the docs of NestJS. Example of modules in this applications are: app, auth, company, paymet, projectc, survey, search, tenant and user (there are more in reality).

Each module has their own service (aka provider), model, etc. We are using Prisma so we don't have a separate file for the typical crud methods and they are located inside the service itself.

Example of why forward ref is needed

Tenant module

@Module({
    imports: [PaymentModule],
    providers: [TenantService],
})
export class TenantModule {}

Tenant service

@Injectable()
export class TenantService {
    async get(tenantId: number) {
        return prisma.tenant.findFirst({ where: { id: tenantId } });
    }

    async create(data) {
        // ... logic
        const tenantId = generateId();
        await PaymentService.createCustomer(tenantId)
        // ... logic
    }
}

Payment module

@Module({
    imports: [TenantModule],
    providers: [PaymentService],
})
export class PaymentModule {}

Payment service

@Injectable()
export class PaymentService {
    async createCustomer(tenantId) {
        // ... logic
    }

    async charge(tenantId: number) {
        const tenant = await this.tenantService.get(tenantId);
        // ... logic
    }
}

Question

My question is how should we adjust our structure to be more "feature grouping". Currently for example we are using the tenant service in a lot of the other modules and I don't see how it would be a "feature". Any guidance, tips, links, documents that would help are highly welcome. I don't really see another way of doing this and can't find good examples either.

Aucun commentaire:

Enregistrer un commentaire