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