feat: implement app templates storefront and deployment engine

This commit is contained in:
SaelixCode
2026-03-04 14:26:07 -05:00
parent 3889d4914e
commit 1676dc22df
7 changed files with 574 additions and 3 deletions
+46
View File
@@ -19,6 +19,7 @@ import { HostTerminalService } from './services/HostTerminalService';
import { DatabaseService } from './services/DatabaseService';
import { NotificationService } from './services/NotificationService';
import { MonitorService } from './services/MonitorService';
import { templateService } from './services/TemplateService';
import YAML from 'yaml';
import { promises as fsPromises } from 'fs';
@@ -1048,6 +1049,51 @@ app.post('/api/system/networks/delete', async (req: Request, res: Response) => {
}
});
// --- App Templates Routes ---
app.get('/api/templates', async (req: Request, res: Response) => {
try {
const templates = await templateService.getTemplates();
res.json(templates);
} catch (error) {
res.status(500).json({ error: 'Failed to fetch templates' });
}
});
app.post('/api/templates/deploy', async (req: Request, res: Response) => {
try {
const { stackName, template, envVars } = req.body;
if (!stackName || !template) {
return res.status(400).json({ error: 'stackName and template are required' });
}
// 1. Create stack directory
await fileSystemService.createStack(stackName);
// 2. Generate compose YAML and save
const composeYaml = templateService.generateComposeFromTemplate(template);
await fileSystemService.saveStackContent(stackName, composeYaml);
// 3. Generate env string and save to default .env
if (envVars) {
const envString = templateService.generateEnvString(envVars);
const stackDir = path.join(fileSystemService.getBaseDir(), stackName);
const defaultEnvPath = path.join(stackDir, '.env');
await fsPromises.writeFile(defaultEnvPath, envString, 'utf-8');
}
// 4. Deploy the stack
await composeService.deployStack(stackName, terminalWs || undefined);
res.json({ success: true, message: 'Template deployed successfully' });
} catch (error: any) {
console.error('Failed to deploy template:', error);
res.status(500).json({ error: error.message || 'Failed to deploy template' });
}
});
// Serve static files in production (for Docker deployment)
if (process.env.NODE_ENV === 'production') {
+106
View File
@@ -0,0 +1,106 @@
import axios from 'axios';
export interface TemplateEnv {
name: string;
label?: string;
default?: string;
}
export interface TemplateVolume {
container: string;
bind?: string;
readonly?: boolean;
}
export interface Template {
type?: number;
title: string;
description: string;
logo?: string;
image?: string;
ports?: string[];
volumes?: TemplateVolume[] | string[];
env?: TemplateEnv[];
categories?: string[];
platform?: string;
repository?: {
url: string;
stackfile: string;
};
}
export interface TemplatesResponse {
version: string;
templates: Template[];
}
export class TemplateService {
private cachedTemplates: Template[] = [];
private lastFetchTime: number = 0;
private readonly CACHE_DURATION_MS = 24 * 60 * 60 * 1000; // 24 hours
private readonly TEMPLATES_URL = 'https://raw.githubusercontent.com/Lissy93/portainer-templates/main/templates.json';
public async getTemplates(): Promise<Template[]> {
const now = Date.now();
if (this.cachedTemplates.length > 0 && now - this.lastFetchTime < this.CACHE_DURATION_MS) {
return this.cachedTemplates;
}
try {
const response = await axios.get<TemplatesResponse>(this.TEMPLATES_URL);
// Filter out templates without images as we are generating compose files from image, ports, etc.
this.cachedTemplates = (response.data.templates || []).filter((t: Template) => !!t.image && t.type === 1);
this.lastFetchTime = now;
return this.cachedTemplates;
} catch (error) {
console.error('Failed to fetch templates', error);
if (this.cachedTemplates.length > 0) {
return this.cachedTemplates;
}
throw new Error('Could not fetch templates from registry');
}
}
public generateComposeFromTemplate(template: Template): string {
let yaml = `services:\n app:\n`;
if (template.image) {
yaml += ` image: ${template.image}\n`;
}
yaml += ` restart: unless-stopped\n`;
if (template.ports && template.ports.length > 0) {
yaml += ` ports:\n`;
for (const port of template.ports) {
yaml += ` - "${port}"\n`;
}
}
if (template.volumes && template.volumes.length > 0) {
yaml += ` volumes:\n`;
for (const vol of template.volumes) {
if (typeof vol === 'string') {
yaml += ` - ${vol}\n`;
} else if (vol.container) {
// If bind is not provided, we extract the folder name from the container path
const containerFolder = vol.container.split('/').pop() || 'data';
const localBind = vol.bind ? vol.bind.replace(/^\//, './') : `./${containerFolder}`;
yaml += ` - ${localBind}:${vol.container}${vol.readonly ? ':ro' : ''}\n`;
}
}
}
yaml += ` env_file:\n - .env\n`;
return yaml;
}
public generateEnvString(envVars: Record<string, string>): string {
return Object.entries(envVars)
.map(([key, value]) => `${key}=${value}`)
.join('\n');
}
}
export const templateService = new TemplateService();