2022-06-27 19:25:26 +02:00
|
|
|
import { NextApiRequest, NextApiResponse } from 'next';
|
|
|
|
|
import Docker from 'dockerode';
|
|
|
|
|
|
|
|
|
|
const docker = new Docker();
|
|
|
|
|
|
|
|
|
|
async function Get(req: NextApiRequest, res: NextApiResponse) {
|
|
|
|
|
// Get the slug of the request
|
|
|
|
|
const { id } = req.query as { id: string };
|
|
|
|
|
const { action } = req.query;
|
|
|
|
|
// Get the action on the request (start, stop, restart)
|
2022-07-06 18:08:39 +02:00
|
|
|
if (action !== 'start' && action !== 'stop' && action !== 'restart' && action !== 'remove') {
|
2022-06-27 19:25:26 +02:00
|
|
|
return res.status(400).json({
|
|
|
|
|
statusCode: 400,
|
|
|
|
|
message: 'Invalid action',
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
if (!id) {
|
|
|
|
|
return res.status(400).json({
|
|
|
|
|
message: 'Missing ID',
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
// Get the container with the ID
|
|
|
|
|
const container = docker.getContainer(id);
|
2022-07-22 16:19:28 +02:00
|
|
|
const startAction = async () => {
|
2022-07-06 18:08:39 +02:00
|
|
|
switch (action) {
|
|
|
|
|
case 'remove':
|
2022-07-22 16:19:28 +02:00
|
|
|
return container.remove();
|
2022-07-06 18:08:39 +02:00
|
|
|
case 'start':
|
2022-07-22 16:19:28 +02:00
|
|
|
return container.start();
|
2022-07-06 18:08:39 +02:00
|
|
|
case 'stop':
|
2022-07-22 16:19:28 +02:00
|
|
|
return container.stop();
|
2022-07-06 18:08:39 +02:00
|
|
|
case 'restart':
|
2022-07-22 16:19:28 +02:00
|
|
|
return container.restart();
|
|
|
|
|
default:
|
|
|
|
|
return Promise;
|
2022-07-06 18:08:39 +02:00
|
|
|
}
|
2022-07-22 16:19:28 +02:00
|
|
|
};
|
|
|
|
|
try {
|
|
|
|
|
await startAction();
|
|
|
|
|
return res.status(200).json({
|
|
|
|
|
statusCode: 200,
|
|
|
|
|
message: `Container ${id} ${action}ed`,
|
2022-07-06 18:08:39 +02:00
|
|
|
});
|
2022-07-22 16:19:28 +02:00
|
|
|
} catch (err) {
|
2022-07-23 22:22:55 +02:00
|
|
|
return res.status(500).json(err);
|
2022-06-27 19:25:26 +02:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export default async (req: NextApiRequest, res: NextApiResponse) => {
|
|
|
|
|
// Filter out if the reuqest is a Put or a GET
|
|
|
|
|
if (req.method === 'GET') {
|
|
|
|
|
return Get(req, res);
|
|
|
|
|
}
|
|
|
|
|
return res.status(405).json({
|
|
|
|
|
statusCode: 405,
|
|
|
|
|
message: 'Method not allowed',
|
|
|
|
|
});
|
|
|
|
|
};
|