refactor: Adjust getConnectedApps graphql query

This commit is contained in:
Faruk AYDIN
2022-08-08 19:39:11 +03:00
parent 533d73d718
commit 8c5d95796f

View File

@@ -1,4 +1,3 @@
import { raw } from 'objection';
import App from '../../models/app'; import App from '../../models/app';
import Context from '../../types/express/context'; import Context from '../../types/express/context';
import { IApp, IConnection } from '@automatisch/types'; import { IApp, IConnection } from '@automatisch/types';
@@ -21,34 +20,21 @@ const getConnectedApps = async (
.count('connections.id as count') .count('connections.id as count')
.groupBy('connections.key'); .groupBy('connections.key');
const connectionKeys = connections.map((connection) => connection.key);
const flows = await context.currentUser const flows = await context.currentUser
.$relatedQuery('steps') .$relatedQuery('flows')
.select('flow_id', raw('ARRAY_AGG(app_key)').as('apps')) .withGraphJoined('steps')
.groupBy('flow_id') as unknown as { flow_id: string; apps: string[] }[]; .orderBy('created_at', 'desc');
const appFlowCounts = flows.reduce((counts, flow) => { const duplicatedUsedApps = flows
const apps = flow.apps; .map((flow) => flow.steps.map((step) => step.appKey))
const unifiedApps = Array.from(new Set(apps)) .flat()
.filter(Boolean);
for (const app of unifiedApps) { const usedApps = [...new Set(duplicatedUsedApps)];
if (!counts[app]) {
counts[app] = 0;
}
counts[app] += 1;
}
return counts;
}, {} as { [key: string]: number });
apps = apps apps = apps
.filter((app: IApp) => { .filter((app: IApp) => {
const hasConnections = connectionKeys.includes(app.key); return usedApps.includes(app.key);
const hasFlows = flows.find((flow) => flow.apps.includes(app.key));
return hasFlows || hasConnections;
}) })
.map((app: IApp) => { .map((app: IApp) => {
const connection = connections.find( const connection = connections.find(
@@ -56,8 +42,15 @@ const getConnectedApps = async (
); );
app.connectionCount = connection?.count || 0; app.connectionCount = connection?.count || 0;
app.flowCount = 0;
app.flowCount = appFlowCounts[app.key]; flows.forEach((flow) => {
const usedFlow = flow.steps.find((step) => step.appKey === app.key);
if (usedFlow) {
app.flowCount += 1;
}
});
return app; return app;
}); });