mirror of
https://github.com/Portabase/portabase.git
synced 2026-07-14 11:16:13 +02:00
70 lines
2.0 KiB
TypeScript
70 lines
2.0 KiB
TypeScript
"use server"
|
|
import {mkdir, writeFile, unlink, readFile} from 'fs/promises';
|
|
import path from 'path';
|
|
import {StorageDeleteInput, StorageGetInput, StorageResult, StorageUploadInput} from '../types';
|
|
import fs from "node:fs";
|
|
import {getServerUrl} from "@/utils/get-server-url";
|
|
|
|
const BASE_DIR = "/private/uploads/files/";
|
|
|
|
export async function uploadLocal(
|
|
config: { baseDir?: string },
|
|
input: { data: StorageUploadInput }
|
|
): Promise<StorageResult> {
|
|
const base = config.baseDir || BASE_DIR;
|
|
const fullPath = path.join(process.cwd(), base, input.data.path);
|
|
|
|
await mkdir(fullPath, {recursive: true});
|
|
await writeFile(fullPath, input.data.file);
|
|
|
|
return {
|
|
success: true,
|
|
provider: 'local',
|
|
url: path.join(fullPath),
|
|
};
|
|
}
|
|
|
|
export async function getLocal(
|
|
config: { baseDir?: string },
|
|
input: { data: StorageGetInput }
|
|
): Promise<StorageResult> {
|
|
const base = config.baseDir || BASE_DIR;
|
|
const filePath = path.join(base, input.data.path)
|
|
const fileName = path.basename(input.data.path);
|
|
const file = await readFile(filePath);
|
|
|
|
|
|
if (!fs.existsSync(filePath)) {
|
|
console.error("File not found at:", filePath);
|
|
return({
|
|
success: false,
|
|
provider: 'local',
|
|
});
|
|
}
|
|
const crypto = require("crypto");
|
|
const baseUrl = getServerUrl();
|
|
|
|
const expiresAt = Date.now() + 60 * 1000;
|
|
const token = crypto.createHash("sha256").update(`${fileName}${expiresAt}`).digest("hex");
|
|
|
|
return {
|
|
success: true,
|
|
provider: 'local',
|
|
file: file,
|
|
url: `${baseUrl}/api/files/${fileName}?token=${token}&expires=${expiresAt}`,
|
|
};
|
|
}
|
|
|
|
export async function deleteLocal(
|
|
config: { baseDir?: string },
|
|
input: { data: StorageDeleteInput }
|
|
): Promise<StorageResult> {
|
|
const base = config.baseDir || BASE_DIR;
|
|
const fullPath = path.join(process.cwd(), base, input.data.path);
|
|
await unlink(fullPath);
|
|
return {
|
|
success: true,
|
|
provider: 'local',
|
|
};
|
|
}
|