device-api: Also support serviceName in v2 service endpoints

Now you can either pass a serviceName or imageId to restart a specific
service, which is much easier from a device container.

Change-type: minor
Signed-off-by: Cameron Diver <cameron@balena.io>
This commit is contained in:
Cameron Diver 2018-11-02 14:50:43 +00:00
parent 9963d24675
commit dfdc371a9c
No known key found for this signature in database
GPG Key ID: 69264F9C923F55C1
2 changed files with 26 additions and 3 deletions

View File

@ -5,7 +5,11 @@ import { fs } from 'mz';
import { ApplicationManager } from '../application-manager';
import { Service } from '../compose/service';
import { appNotFoundMessage, serviceNotFoundMessage } from '../lib/messages';
import {
appNotFoundMessage,
serviceNotFoundMessage,
v2ServiceEndpointInputErrorMessage,
} from '../lib/messages';
import { checkTruthy } from '../lib/validation';
import { doPurge, doRestart, serviceAction } from './common';
@ -31,7 +35,7 @@ export function createV2Api(router: Router, applications: ApplicationManager) {
res: Response,
action: any,
): Bluebird<void> => {
const { imageId, force } = req.body;
const { imageId, serviceName, force } = req.body;
const { appId } = req.params;
return _lockingIfNecessary(appId, { force }, () => {
@ -42,7 +46,23 @@ export function createV2Api(router: Router, applications: ApplicationManager) {
res.status(404).send(appNotFoundMessage);
return;
}
const service = _.find(app.services, { imageId }) as Service | null;
// Work if we have a service name or an image id
if (imageId == null) {
if (serviceName == null) {
throw new Error(v2ServiceEndpointInputErrorMessage);
}
}
let service: Service | undefined;
if (imageId != null) {
service = _.find(app.services, svc => svc.imageId === imageId);
} else {
service = _.find(
app.services,
svc => svc.serviceName === serviceName,
);
}
if (service == null) {
res.status(404).send(serviceNotFoundMessage);
return;

View File

@ -4,3 +4,6 @@ export const appNotFoundMessage = `App not found: an app needs to be installed f
export const serviceNotFoundMessage =
'Service not found, a container must exist for this endpoint to work';
export const v2ServiceEndpointInputErrorMessage =
'This endpoint requires one of imageId or serviceName';