import { RequestTenantLoader as Abstraction, RawTenantId } from "./abstractions.js"; import type { IRawTenantId } from "./abstractions.js"; import { GetTenantByIdUseCase } from "~/features/tenancy/GetTenantById/index.js"; import { RootTenantId } from "~/features/tenancy/TenantStorages/RootTenantId.js"; import type { IGetTenantByIdUseCase } from "~/features/tenancy/GetTenantById/abstractions.js"; import { createBootstrapRootTenant } from "~/features/tenancy/shared/bootstrapRootTenant.js"; import type { Tenant } from "~/types/tenancy.js"; import { TenantNotFoundError } from "./TenantNotFoundError.js"; /** * The LOAD step of a container that holds the whole API for one tenant (a test harness that builds * no tenant scopes): it reads the tenant from the container's own registry. */ export class SingleContainerRequestTenantLoaderImpl implements Abstraction.Interface { constructor( private getTenantById: IGetTenantByIdUseCase, private rawTenantId: IRawTenantId ) {} async establish(): Promise { const resolvedId = RootTenantId.orRoot(this.rawTenantId.get()); const result = await this.getTenantById.execute(resolvedId); if (result.isOk()) { return result.value; } // Fresh, not-yet-installed environment: the root tenant record doesn't exist yet. Establish a // bootstrap root so the request pipeline + GraphQL schema build work and the install mutation // can create the real root tenant. Only ever taken for the root tenant pre-install. if (RootTenantId.isRoot(resolvedId)) { return createBootstrapRootTenant(); } /* Any other unknown tenant fails the request here. Carrying on with no tenant only moved the failure to whatever read the tenant next, and the admin login relies on this code to fall back to root when the tenant it remembered was deleted. */ throw new TenantNotFoundError(resolvedId); } } export const SingleContainerRequestTenantLoader = Abstraction.createImplementation({ implementation: SingleContainerRequestTenantLoaderImpl, dependencies: [GetTenantByIdUseCase, RawTenantId] });