@souseha/media-sdk
v1.0.3
Published
Cloudflare Media API Client SDK
Readme
@souseha/media-sdk
Cloudflare Media API 的 TypeScript SDK。
安裝
npm install @souseha/media-sdk
# 或
pnpm add @souseha/media-sdk使用方式
初始化
import { MediaClient } from '@souseha/media-sdk';
const client = new MediaClient({
baseUrl: 'API_URL',
apiKey: 'your-api-key-here',
});Images 操作
// 上傳圖片
const image = await client.images.upload(file, {
table: 'characters',
record_id: 'luna',
purpose: 'avatar',
custom_id: 'characters/luna/avatar', // 選填
});
// 列出圖片
const images = await client.images.list({
table: 'characters',
per_page: 50,
});
// 取得單張圖片資訊
const info = await client.images.get('image-id');
// 刪除圖片
await client.images.delete('image-id');R2 操作
// 上傳檔案
const object = await client.r2.upload('my-bucket', file, {
key: 'path/to/file.json',
table: 'backups',
record_id: 'daily-2024-01-15',
});
// 列出檔案
const objects = await client.r2.list('my-bucket', {
prefix: 'backups/',
limit: 100,
});
// 取得檔案資訊
const objInfo = await client.r2.get('my-bucket', 'path/to/file.json');
// 取得簽名 URL
const { url, expires_at } = await client.r2.getSignedUrl('my-bucket', 'path/to/file.json', {
expires_in: 3600,
});
// 下載檔案
const response = await client.r2.download('my-bucket', 'path/to/file.json');
const blob = await response.blob();
// 刪除檔案
await client.r2.delete('my-bucket', 'path/to/file.json');錯誤處理
import { MediaApiError } from '@wangch/media-sdk';
try {
await client.images.get('non-existent-id');
} catch (error) {
if (error instanceof MediaApiError) {
console.log(error.code); // 'NOT_FOUND'
console.log(error.message); // '圖片不存在'
console.log(error.status); // 404
}
}API 文件
MediaClient
建構選項
| 選項 | 類型 | 必填 | 說明 | |------|------|------|------| | baseUrl | string | 是 | API 基礎 URL | | apiKey | string | 是 | API Key | | timeout | number | 否 | 請求超時時間(毫秒,預設 30000) |
ImagesModule
upload(file, options)
上傳圖片。
參數:
file: File | Blob - 圖片檔案options.table: string - 資料表名稱(必填)options.record_id: string - 關聯記錄 ID(選填)options.purpose: string - 用途(選填)options.custom_id: string - 自訂 ID(選填)options.extra_meta: Record<string, string> - 額外 metadata(選填)
list(filter?)
列出圖片。
參數:
filter.table: string - 過濾資料表filter.record_id: string - 過濾記錄 IDfilter.purpose: string - 過濾用途filter.page: number - 頁碼(預設 1)filter.per_page: number - 每頁數量(預設 20,最大 100)
get(id)
取得單張圖片資訊。
delete(id)
刪除圖片。
R2Module
upload(bucket, file, options)
上傳檔案。
參數:
bucket: string - Bucket 名稱file: File | Blob - 檔案options.key: string - 檔案路徑/名稱(必填)options.table: string - 資料表名稱(必填)options.record_id: string - 關聯記錄 ID(選填)options.purpose: string - 用途(選填)options.content_type: string - Content-Type(選填)options.extra_meta: Record<string, string> - 額外 metadata(選填)
list(bucket, filter?)
列出檔案。
get(bucket, key)
取得檔案資訊。
getSignedUrl(bucket, key, options?)
取得簽名 URL。
download(bucket, key)
下載檔案。
delete(bucket, key)
刪除檔案。
License
MIT
