import { readFile } from "node:fs/promises"
import { basename } from "node:path"
const api = "https://api.ofauth.com"
const filename = process.argv[2]
const bytes = await readFile(filename)
const contentType = "image/png"
const headers = {
apikey: process.env.OFAUTH_API_KEY,
"x-connection-id": process.env.CONNECTION_ID
}
async function post(path, body) {
const response = await fetch(`${api}${path}`, {
method: "POST",
headers: { ...headers, "content-type": "application/json" },
body: JSON.stringify(body)
})
if (!response.ok) throw new Error(await response.text())
return response.json()
}
const upload = await post("/v2/access/uploads", {
filename: basename(filename),
size: bytes.length,
contentType
})
for (const part of upload.parts) {
const response = await fetch(part.uploadUrl, {
method: "PUT",
headers: { ...headers, "content-type": contentType },
body: bytes.subarray(part.byteRange.start, part.byteRange.end + 1)
})
if (!response.ok) throw new Error(await response.text())
}
if (upload.uploadType === "multipart") {
await post(`/v2/access/uploads/${encodeURIComponent(upload.mediaUploadId)}/finalize`, {})
}
const story = await post("/v2/access/stories", {
mediaItems: [upload.mediaUploadId]
})
console.log(story.id)