@suphark/files-client
v0.6.0
Published
Pi Files SDK: presigned/multipart upload, content proxy for Next.js route handlers, React upload hook, file references
Readme
@suphark/files-client
SDK ของ Pi Files (files.suphark.com) สำหรับ Next.js/React — dependency เดียวคือ zod; component สำเร็จรูป (/ui) ใช้ @suphark/ui ของแอป
pnpm add @suphark/files-clientเริ่มเร็วที่สุด: route เดียว + component (0.4.0)
// app/api/pi-files/[...path]/route.ts
export const { GET, POST, DELETE } = piFilesNext.route({
authorize: async (request, action) => {
const user = await getCurrentUser();
if (!user) return new Response(null, { status: 401 });
return (await canAccess(user, action)) && { userId: user.id, name: user.name };
},
});import { PiAttachments, PiImageField, usePiDraft } from "@suphark/files-client/ui"; // ต้องมี @suphark/ui ในแอป
<PiAttachments module="vendor.attachments" entity={{ type: "vendor", id }} />
<PiImageField module="user.avatar" entity={{ type: "user", id }} />ฉบับร่าง → ระเบียนจริง references.moveEntity(draft, to) · ลบระเบียน references.detachEntity(entity) — ดู docs/guides/quick-start.md
0.6.0: useUploadQueue().enqueueReplace(fileId, file) อัปโหลดเวอร์ชันใหม่ผ่านคิว · Google Drive ส่งเป็นช่วง 8 MiB เน็ตหลุดแล้วส่งต่อจากเดิม (useUpload ต่อได้แม้ refresh หน้า)
0.5.0: references.counts(entityType, ids) (จำนวนไฟล์ต่อระเบียน ครั้งเดียวต่อหน้า) · migration.adoptMany(items, { dryRun }) รับไฟล์เดิมจาก URL ทีละชุด
1. server client (@suphark/files-client)
import { createPiFiles } from "@suphark/files-client";
export const piFiles = createPiFiles({
baseUrl: process.env.PI_FILES_URL!, // https://files.suphark.com
appKey: process.env.PI_FILES_APP_KEY!, // pfk_… (ownerType APP)
});
// อัปโหลดจาก server (Buffer/Blob) ครบวงจร
const file = await piFiles.upload(buffer, {
filename: "รายงาน.pdf",
mimeType: "application/pdf",
sizeBytes: buffer.byteLength,
featureKey: "REPORT",
reference: { featureKey: "REPORT", entityType: "Project", entityId: "p1", role: "main" },
});
await piFiles.references.attach(file.id, {
featureKey: "REPORT",
entityType: "Project",
entityId: "p2",
role: "copy",
});
const mine = await piFiles.references.byEntity("Project", "p1");
const { url } = await piFiles.files.contentUrl(file.id, { download: true }); // presigned อายุสั้น
await piFiles.files.delete(file.id); // 409 FILE_REFERENCED ถ้ายังมี referencepiFiles.withUser(accessToken) → client เดียวกันแต่ใช้ Pi Auth JWT ของผู้ใช้ (ไฟล์ ownerType USER)
linked source (โฟลเดอร์ Google Drive เดิม) — 0.3.0
const src = await piFiles.sources.link({ folder: "https://drive.google.com/drive/folders/<id>" });
const tree = await piFiles.folders.contents(src.folderId, { recursive: true }); // relativePath, md5, modifiedTime, providerFileId
const set = await piFiles.folders.ensurePath(src.folderId, ["01_Docs", "ชุด A"]); // สร้างใน Drive จริง
const access = await piFiles.files.access(fileId); // ใครเปิดได้ใน Drive + ทำลิงก์สาธารณะได้ไหมwebhook file.created|updated|moved|deleted|missing, folder.* มี source.ancestorFolderIds — ดู docs/guides/connect-app.md §6.1
2. Next.js route handlers (@suphark/files-client/next)
// src/lib/pi-files.ts
import { createPiFiles, createPiFilesNext } from "@suphark/files-client/next";
export const piFiles = createPiFiles({ baseUrl, appKey });
export const piFilesNext = createPiFilesNext({ client: piFiles });
// app/api/files/uploads/[[...path]]/route.ts — proxy อัปโหลด (browser ไม่ถือ key)
export const { POST, DELETE } = piFilesNext.handlers.uploads({
authorize: async (request, action) => {
const user = await piAuth.getCurrentUser();
if (!user) return null; // 401
if (action.kind !== "create") return {};
return { input: { featureKey: "REPORT", onBehalfOfUserId: user.id, reference: {...} } };
},
});
// app/api/files/[id]/content/route.ts — URL same-origin ที่ browser ใช้
export const GET = piFilesNext.handlers.content({
strategy: "redirect", // หรือ "stream" (Range passthrough)
resolve: async (request, params) => {
const user = await piAuth.getCurrentUser();
if (!user) return new Response(null, { status: 401 });
if (!(await canView(user, params.id))) return null; // 404
return { fileId: String(params.id), download: request.url.includes("download=1") };
},
});3. React (@suphark/files-client/react)
"use client";
import { useUpload, useUploadQueue } from "@suphark/files-client/react";
const { upload, cancel, status, progress, error } = useUpload({ endpoint: "/api/files/uploads" });
await upload(file); // single PUT หรือ multipart (8 MiB/part, 3 ขนาน, resume หลัง refresh)
const { items, enqueue, enqueueReplace, cancel } = useUploadQueue({
endpoint: "/api/files/uploads",
parallel: 2,
});
enqueue(files);
enqueueReplace(existingFileId, file); // 0.6.0: เวอร์ชันใหม่ทับไฟล์เดิมในคิวเดียวกัน (เช่นผู้ใช้เลือก "แทนที่" เมื่อชื่อซ้ำ) — items[].replaceFileIdendpoint มีรูปแบบเดียวกับ /api/v1/uploads ของ Pi Files: POST (ticket), POST /:id/parts, POST /:id/complete, DELETE /:id
Errors
ทุก method โยน PiFilesError { status, code, message, problem } — code เช่น UNAUTHENTICATED, PERMISSION_DENIED, NOT_FOUND, QUOTA_EXCEEDED, UNSUPPORTED_MEDIA_TYPE, PAYLOAD_TOO_LARGE, FILE_REFERENCED, SIZE_MISMATCH, UPLOAD_INCOMPLETE, ABORTED
