integratedhub/routes/api/create/property_media.ts
2026-01-20 09:02:26 -06:00

97 lines
3.0 KiB
TypeScript

// routes/api/create/property_media.ts
import { define } from "../../../utils.ts";
import { createPropertyMedia } from "../../../services/propertyMediaService.ts";
import { SessionCookie } from "../../auth/callback.ts";
export const handler = define.handlers({
async POST(ctx) {
try {
const stateData: SessionCookie = ctx.state.data;
const contentType = ctx.req.headers.get("content-type") || "";
let data: Record<string, string | number> = {};
let sender: string | null = null;
let isJsonRequest = false;
// Handle both JSON and form data
if (contentType.includes("application/json")) {
isJsonRequest = true;
const jsonData = await ctx.req.json();
data = jsonData;
} else {
const formData = await ctx.req.formData();
sender = formData.get("sender")?.toString() || null;
data = {
property_id: formData.get("property_id")?.toString() || "",
media_type: formData.get("media_type")?.toString() || "",
file_url: formData.get("file_url")?.toString() || "",
file_name: formData.get("file_name")?.toString() || "",
display_order: parseInt(
formData.get("display_order")?.toString() || "0",
),
};
}
const property_id = data.property_id as string;
const media_type = data.media_type as string;
const file_url = data.file_url as string;
const file_name = data.file_name as string;
const display_order = data.display_order as number || 0;
if (!property_id || !media_type || !file_url || !file_name) {
return new Response(
JSON.stringify({
error:
"Property ID, media type, file URL, and file name are required",
}),
{
status: 400,
headers: { "Content-Type": "application/json" },
},
);
}
const result = await createPropertyMedia(
property_id,
media_type,
file_url,
file_name,
display_order,
);
// Return appropriate response based on request type
if (isJsonRequest) {
return new Response(
JSON.stringify({
success: true,
media: result[0],
}),
{
status: 200,
headers: { "Content-Type": "application/json" },
},
);
} else {
// Redirect back to the sender URL
const senderPath = sender?.toString() || "/";
let redirectUrl = senderPath;
try {
if (senderPath.startsWith("/")) {
const url = new URL(ctx.req.url);
redirectUrl = url.origin + senderPath;
}
} catch (_) {
// fallback: just use senderPath
}
return Response.redirect(redirectUrl, 303);
}
} catch (e) {
return new Response(JSON.stringify({ error: e }), {
status: 500,
headers: { "Content-Type": "application/json" },
});
}
},
});