Separate routes & actions, add tests for GET /v2/local/device-info

Signed-off-by: Christina Ying Wang <christina@balena.io>
This commit is contained in:
Christina Ying Wang 2023-12-06 14:15:34 -08:00
parent e9535cd0ff
commit 8112e51f4e
4 changed files with 70 additions and 7 deletions

View File

@ -518,3 +518,12 @@ export const getContainerIds = async (
throw new Error(`Could not find service with name '${serviceName}'`);
}
};
/**
* Get device type & arch
* Used by:
* - GET /v2/local/device-info
*/
export const getDeviceInfo = async () => {
return await config.getMany(['deviceType', 'deviceArch']);
};

View File

@ -330,10 +330,7 @@ router.post('/v2/local/target-state', async (req, res) => {
router.get('/v2/local/device-info', async (_req, res) => {
try {
const { deviceType, deviceArch } = await config.getMany([
'deviceType',
'deviceArch',
]);
const { deviceType, deviceArch } = await actions.getDeviceInfo();
return res.status(200).json({
status: 'success',
@ -342,10 +339,10 @@ router.get('/v2/local/device-info', async (_req, res) => {
deviceType,
},
});
} catch (e: any) {
res.status(500).json({
} catch (e: unknown) {
return res.status(500).json({
status: 'failed',
message: e.message,
message: (e as Error).message ?? e,
});
}
});

View File

@ -992,3 +992,25 @@ describe('gets service container ids', () => {
}
});
});
describe('gets device type and arch', () => {
let configGetManyStub: SinonStub;
before(() => {
// @ts-expect-error
configGetManyStub = stub(config, 'getMany').resolves({
deviceType: 'test-type',
deviceArch: 'test-arch',
});
});
after(() => {
configGetManyStub.restore();
});
it('returns device type and arch', async () => {
expect(await actions.getDeviceInfo()).to.deep.equal({
deviceType: 'test-type',
deviceArch: 'test-arch',
});
});
});

View File

@ -896,4 +896,39 @@ describe('device-api/v2', () => {
.expect(503);
});
});
describe('GET /v2/local/device-info', () => {
let getDeviceInfoStub: SinonStub;
beforeEach(() => {
getDeviceInfoStub = stub(actions, 'getDeviceInfo');
});
afterEach(() => {
getDeviceInfoStub.restore();
});
it('responds with 200 and device info', async () => {
getDeviceInfoStub.resolves({
deviceArch: 'aarch64',
deviceType: 'raspberrypi4-64',
});
await request(api)
.get('/v2/local/device-info')
.set('Authorization', `Bearer ${await deviceApi.getGlobalApiKey()}`)
.expect(200, {
status: 'success',
info: {
arch: 'aarch64',
deviceType: 'raspberrypi4-64',
},
});
});
it('responds with 500 if an error occurred', async () => {
getDeviceInfoStub.throws(new Error());
await request(api)
.get('/v2/local/device-info')
.set('Authorization', `Bearer ${await deviceApi.getGlobalApiKey()}`)
.expect(500);
});
});
});