import { readFile } from "node:fs/promises";
const API_BASE_URL = process.env.API_BASE_URL ?? "https://api.sandbox.trycollate.ai";
const API_KEY = process.env.API_KEY;
const AUTHORIZATION_ID = process.env.AUTHORIZATION_ID;
if (!API_KEY) {
throw new Error("Set API_KEY before running this example.");
}
if (!AUTHORIZATION_ID) {
throw new Error("Set AUTHORIZATION_ID before running this example.");
}
type RequestOptions = {
method?: "GET" | "POST";
body?: unknown;
};
type CreateFileResponse = {
file: {
id: string;
status: string;
};
upload: {
url: string;
headers: Record<string, string>;
};
};
type FileRecord = {
id: string;
status: string;
downloadUrl: string | null;
};
async function request<T>(path: string, options: RequestOptions = {}): Promise<T> {
const response = await fetch(`${API_BASE_URL}${path}`, {
method: options.method ?? "GET",
headers: {
Authorization: `Bearer ${API_KEY}`,
"Content-Type": "application/json",
},
body: options.body ? JSON.stringify(options.body) : undefined,
});
if (!response.ok) {
throw new Error(`${response.status} ${await response.text()}`);
}
return response.json() as Promise<T>;
}
async function main() {
const bytes = await readFile("./clinical-note.pdf");
const created = await request<CreateFileResponse>("/v1/files", {
method: "POST",
body: {
fileName: "clinical-note.pdf",
contentType: "application/pdf",
purpose: "authorization_attachment",
},
});
console.log("Created file session", created.file.id, created.file.status);
const uploadResponse = await fetch(created.upload.url, {
method: "PUT",
headers: created.upload.headers,
body: bytes,
});
if (!uploadResponse.ok) {
throw new Error(`Upload failed: ${uploadResponse.status} ${await uploadResponse.text()}`);
}
const completed = await request<FileRecord>(`/v1/files/${created.file.id}/complete`, {
method: "POST",
});
console.log("Completed file", completed.id, completed.status);
const attachment = await request<{ id: string; fileId: string }>(
`/v1/prior-auth/authorizations/${AUTHORIZATION_ID}/attachments`,
{
method: "POST",
body: {
fileId: completed.id,
label: "Clinical note",
},
},
);
console.log("Attached file", attachment.id, "to authorization", AUTHORIZATION_ID);
}
main().catch((error) => {
console.error(error);
process.exit(1);
});