56 lines
1.5 KiB
TypeScript
56 lines
1.5 KiB
TypeScript
import { applySchema } from '../../lib/appwrite.js';
|
|
import { loadTenants, saveTenants } from '../tenants/tenants.store.js';
|
|
import type { AppwriteProject } from '../tenants/tenants.types.js';
|
|
import { logger } from '../../lib/logger.js';
|
|
|
|
export const resolveProject = async (tenantId: string, projectRef?: string): Promise<AppwriteProject> => {
|
|
const tenants = await loadTenants();
|
|
const tenant = tenants.find((item) => item.id === tenantId);
|
|
|
|
if (!tenant) {
|
|
throw new Error('Tenant not found');
|
|
}
|
|
|
|
if (!projectRef) {
|
|
if (tenant.appwriteProjects.length === 1) {
|
|
return tenant.appwriteProjects[0];
|
|
}
|
|
throw new Error('Multiple projects found. Provide projectRef.');
|
|
}
|
|
|
|
const project = tenant.appwriteProjects.find(
|
|
(item) => item.id === projectRef || item.projectId === projectRef
|
|
);
|
|
|
|
if (!project) {
|
|
throw new Error('Project not found');
|
|
}
|
|
|
|
return project;
|
|
};
|
|
|
|
export const syncSchemaForProject = async (tenantId: string, projectRef?: string) => {
|
|
const project = await resolveProject(tenantId, projectRef);
|
|
|
|
const result = await applySchema({
|
|
endpoint: project.endpoint,
|
|
projectId: project.projectId,
|
|
apiKey: project.apiKey,
|
|
});
|
|
|
|
project.updatedAt = new Date().toISOString();
|
|
|
|
const tenants = await loadTenants();
|
|
const tenant = tenants.find((item) => item.id === tenantId);
|
|
if (tenant) {
|
|
tenant.updatedAt = project.updatedAt;
|
|
await saveTenants(tenants);
|
|
}
|
|
|
|
logger.info('Schema synced for project', {
|
|
tenantId,
|
|
projectId: project.projectId,
|
|
});
|
|
|
|
return result;
|
|
};
|