Files
portabase/src/features/storages/dispatch.ts
T

104 lines
2.8 KiB
TypeScript
Raw Normal View History

2026-01-12 21:16:52 +01:00
"use server";
2026-01-13 22:22:01 +01:00
import {eq} from 'drizzle-orm';
import * as drizzleDb from '@/db';
import {db} from '@/db';
import type {StorageInput, StorageProviderKind, StorageResult,} from './types';
import {dispatchViaProvider} from "@/features/storages/providers";
import {StorageChannel} from "@/db/schema/12_storage-channel";
import {Json} from "drizzle-zod";
2026-01-12 21:16:52 +01:00
export async function dispatchStorage(
2026-01-13 22:22:01 +01:00
input: StorageInput,
2026-01-12 21:16:52 +01:00
policyId?: string,
channelId?: string,
organizationId?: string
2026-01-13 22:22:01 +01:00
): Promise<StorageResult> {
2026-01-12 21:16:52 +01:00
try {
let channel: StorageChannel | null = null;
if (policyId) {
const policyDb = await db.query.storagePolicy.findFirst({
where: eq(drizzleDb.schemas.storagePolicy.id, policyId),
with: {
storageChannel: true
},
});
if (!policyDb || !policyDb.storageChannel) {
return {
success: false,
provider: null,
error: "Policy or associated channel not found",
};
}
if (!policyDb.enabled || !policyDb.storageChannel.enabled) {
return {
success: false,
provider: policyDb.storageChannel.provider as any,
error: "Policy or channel is disabled",
};
}
channel = {
...policyDb.storageChannel,
config: policyDb.storageChannel.config as Json,
};
}
2026-01-12 21:16:52 +01:00
if (channelId) {
const fetchedChannel = await db.query.storageChannel.findFirst({
where: eq(drizzleDb.schemas.storageChannel.id, channelId),
});
2026-01-12 21:16:52 +01:00
if (!fetchedChannel) {
return {
success: false,
provider: null,
error: "Channel not found",
};
}
channel = {
...fetchedChannel,
config: fetchedChannel.config as Json,
};
}
if (!channel) {
2026-01-12 21:16:52 +01:00
return {
success: false,
provider: null,
error: "No valid channel to dispatch on storage",
2026-01-12 21:16:52 +01:00
};
}
if (!channel.enabled) {
2026-01-12 21:16:52 +01:00
return {
success: false,
provider: null,
error: "Channel not active",
2026-01-12 21:16:52 +01:00
};
}
2026-01-13 22:22:01 +01:00
return await dispatchViaProvider(
channel.provider as StorageProviderKind,
2026-01-12 21:16:52 +01:00
channel.config,
2026-01-13 22:22:01 +01:00
input
2026-01-12 21:16:52 +01:00
);
2026-01-12 21:16:52 +01:00
} catch (err: any) {
return {
success: false,
provider: null,
2026-01-13 22:22:01 +01:00
error: err.message || 'Unexpected storage dispatch error',
2026-01-12 21:16:52 +01:00
};
}
}