Tools/routes/applications.update.ts
2024-03-10 10:17:28 +01:00

119 lines
3.2 KiB
TypeScript

import AppQueries from "../domain/AppQueries";
import { UpdateDefinition } from "../domain/projections/ApplicationUpdates";
import Caprover, { Application } from "../services/Caprover";
import DockerHub from "../services/DockerHub";
import Layout, { html } from "../ui/Layout";
const UpdateForm = (application: Application, latestVersions: string[]) => {
// sort by number of "dots" in the version to have the most specific version first
latestVersions.sort((a, b) => {
return b.split(".").length - a.split(".").length;
});
return html`<form method="POST">
<input type="hidden" name="appName" value="${application.name}" />
<select name="version">
${latestVersions.map((version) => {
return html`<option value="${version}">${version}</option>`;
})}
</select>
<button type="submit">Update</button>
</form>`;
};
const PendingUpdates = (pendingUpdates: UpdateDefinition[]) => {
if (pendingUpdates.length === 0) {
return "";
}
return html`<div>
<h2>Pending updates</h2>
<ul>
${pendingUpdates
.map((update) => {
return html`<li>${update.newVersion}</li>`;
})
.join("")}
</ul>
</div>`;
};
const Page = (
application: Application,
latestVersions: string[],
pendingUpdates: UpdateDefinition[]
) => {
return html`<div>
<h1>Updating ${application.name}</h1>
${PendingUpdates(pendingUpdates)}
<dl>
<dt>Last deployment</dt>
<dd>${application.lastDeployedAt.toLocaleString("fr-FR")}</dd>
<dt>Current version</dt>
<dd>
${application.dockerImage
? `<img height="32" width="32" src="https://cdn.simpleicons.org/docker" alt="Docker hub"/> <a href="${application.dockerImage.hubUrl}/tags">
${application.dockerImage.name}:${application.dockerImage.tag}
</a>`
: `<code>${application.imageName}</code>… check yourself!`}
</dd>
<dt>Latest versions</dt>
<dd>
${latestVersions.length === 0
? "No version found"
: UpdateForm(application, latestVersions)}
</dd>
</dl>
</div>`;
};
export default async (
req: Request,
caprover: Caprover,
dockerHub: DockerHub,
queries: AppQueries
): Promise<Response> => {
if (req.method === "POST") {
const body = await req.formData();
await caprover.updateApplication(
body.get("appName") as string,
body.get("version") as string
);
}
const applications = await caprover.getApps();
const nameFilter = new URL(req.url).searchParams.get("name");
const appToUpdate = applications
.filter((app) => {
// can we help to update this app?
return app.dockerImage;
})
.find((app) => {
return nameFilter ? app.name === nameFilter : app.isOlderThan(30);
});
if (!appToUpdate) {
return new Response(Layout(html`<h1>No application to update 🎉</h1>`), {
headers: { "Content-Type": "text/html" },
});
}
const latestVersions = await dockerHub.getLatestVersions(
appToUpdate.dockerImage!.name
);
const pendingUpdates = queries.pendingApplicationUpdates(appToUpdate.name);
return new Response(
Layout(Page(appToUpdate, latestVersions, pendingUpdates)),
{
headers: { "Content-Type": "text/html" },
}
);
};