devices: Use a single request when providing the --fleet parameter

Reduces the response time when using
--fleet from 1.5s to 1s.

Change-type: patch
This commit is contained in:
Thodoris Greasidis 2023-05-23 19:42:27 +03:00
parent 861d4f33b7
commit 2b58143164

View File

@ -22,13 +22,7 @@ import { expandForAppName } from '../../utils/helpers';
import { getBalenaSdk, getVisuals, stripIndent } from '../../utils/lazy'; import { getBalenaSdk, getVisuals, stripIndent } from '../../utils/lazy';
import { applicationIdInfo, jsonInfo } from '../../utils/messages'; import { applicationIdInfo, jsonInfo } from '../../utils/messages';
import type { Application, Device, PineOptions } from 'balena-sdk'; import type { Device, PineOptions } from 'balena-sdk';
interface ExtendedDevice extends DeviceWithDeviceType {
dashboard_url?: string;
fleet?: string | null; // 'org/name' slug
device_type?: string | null;
}
interface FlagsDef { interface FlagsDef {
fleet?: string; fleet?: string;
@ -88,38 +82,33 @@ export default class DevicesCmd extends Command {
$orderby: { device_name: 'asc' }, $orderby: { device_name: 'asc' },
} satisfies PineOptions<Device>; } satisfies PineOptions<Device>;
let devices; const devices = (
await (async () => {
if (options.fleet != null) {
const { getApplication } = await import('../../utils/sdk');
const application = await getApplication(balena, options.fleet, {
$select: 'slug',
$expand: {
owns__device: devicesOptions,
},
});
return application.owns__device;
}
if (options.fleet != null) { return await balena.pine.get({
const { getApplication } = await import('../../utils/sdk'); resource: 'device',
const application = await getApplication(balena, options.fleet, { options: devicesOptions,
$select: 'id', });
}); })()
devices = (await balena.models.device.getAllByApplication( ).map((device) => ({
application.id, ...device,
devicesOptions, dashboard_url: balena.models.device.getDashboardUrl(device.uuid),
)) as ExtendedDevice[]; fleet: device.belongs_to__application?.[0]?.slug || null,
} else { uuid: options.json ? device.uuid : device.uuid.slice(0, 7),
devices = (await balena.pine.get({ device_type: device.is_of__device_type?.[0]?.slug || null,
resource: 'device', }));
options: devicesOptions,
})) as ExtendedDevice[];
}
devices = devices.map(function (device) { const fields: Array<keyof (typeof devices)[number]> = [
device.dashboard_url = balena.models.device.getDashboardUrl(device.uuid);
const belongsToApplication =
device.belongs_to__application as Application[];
device.fleet = belongsToApplication?.[0]?.slug || null;
device.uuid = options.json ? device.uuid : device.uuid.slice(0, 7);
device.device_type = device.is_of__device_type?.[0]?.slug || null;
return device;
});
const fields = [
'id', 'id',
'uuid', 'uuid',
'device_name', 'device_name',