|
| 1 | +import { readFile } from "fs/promises"; |
| 2 | +import type { SquareCloudBlob } from ".."; |
| 3 | +import { assertPutBlobObjectResponse } from "../assertions/put"; |
| 4 | +import { putBlobObjectPayloadSchema } from "../schemas/put"; |
| 5 | +import { SquareCloudBlobError } from "../structures/error"; |
| 6 | +import type { PutBlobObjectResponse, PutBlobObjectType } from "../types/put"; |
| 7 | + |
| 8 | +export class BlobObjectsManager { |
| 9 | + constructor(private readonly client: SquareCloudBlob) {} |
| 10 | + |
| 11 | + async put(object: PutBlobObjectType) { |
| 12 | + const payload = putBlobObjectPayloadSchema.parse(object); |
| 13 | + const file = await this.parseFile(payload.file); |
| 14 | + |
| 15 | + const formData = new FormData(); |
| 16 | + formData.append("file", new Blob([file])); |
| 17 | + |
| 18 | + const { response } = await this.client.api.request<PutBlobObjectResponse>( |
| 19 | + "blob/put", |
| 20 | + { |
| 21 | + method: "POST", |
| 22 | + body: formData, |
| 23 | + params: payload.params, |
| 24 | + }, |
| 25 | + ); |
| 26 | + |
| 27 | + return assertPutBlobObjectResponse(response); |
| 28 | + } |
| 29 | + |
| 30 | + private async parseFile(file: string | Buffer) { |
| 31 | + let result: Buffer | undefined; |
| 32 | + |
| 33 | + if (typeof file === "string") { |
| 34 | + result = await readFile(file).catch(() => undefined); |
| 35 | + } |
| 36 | + |
| 37 | + if (!result) { |
| 38 | + throw new SquareCloudBlobError("INVALID_FILE", "File not found"); |
| 39 | + } |
| 40 | + |
| 41 | + return result; |
| 42 | + } |
| 43 | + |
| 44 | + parseObjectUrl(url: string) { |
| 45 | + const pattern = |
| 46 | + /^https:\/\/public-blob\.squarecloud\.dev\/([^\/]+)\/([^\/]+\/)?([^_]+)_[\w-]+\.\w+$/; |
| 47 | + const match = pattern.exec(url); |
| 48 | + |
| 49 | + if (!match) { |
| 50 | + throw new SquareCloudBlobError( |
| 51 | + "INVALID_BLOB_URL", |
| 52 | + "Invalid blob object URL", |
| 53 | + ); |
| 54 | + } |
| 55 | + |
| 56 | + let [, id, prefix, name] = match; |
| 57 | + prefix = prefix ? prefix.slice(0, -1) : ""; |
| 58 | + |
| 59 | + return { id, prefix, name }; |
| 60 | + } |
| 61 | +} |
0 commit comments