UNPKG

@oystehr/sdk

Version:

Oystehr SDK

108 lines (103 loc) 2.93 kB
import { defaultProjectApiUrl, SDKResource } from '../../client/client'; import { OystehrSdkError } from '../../errors'; import { Z3GetPresignedUrlParams, Z3GetPresignedUrlResponse } from '../types'; function baseUrlThunk(this: SDKResource): string { return this.config.services?.['projectApiUrl'] ?? 'https://project-api.zapehr.com/v1'; } /** * Uploads a file to the bucket and key. Files should be Blobs. * * @param params upload file params */ export async function uploadFile( this: SDKResource, { bucketName, 'objectPath+': key, file, }: { bucketName: string; 'objectPath+': string; file: Blob; } ): Promise<void> { const uploadUrl = await this.request( '/z3/{bucketName}/{objectPath+}', 'post', baseUrlThunk.bind(this) )({ action: 'upload', bucketName, 'objectPath+': key, }); await fetch(uploadUrl.signedUrl, { method: 'PUT', body: file, }); } /** * Downloads an object matching the bucket and key. File content is returned as an ArrayBuffer. * * @param params download file params */ export async function downloadFile( this: SDKResource, { bucketName, 'objectPath+': key, }: { bucketName: string; 'objectPath+': string; } ): Promise<ArrayBuffer> { const uploadUrl = await this.request( '/z3/{bucketName}/{objectPath+}', 'post', baseUrlThunk.bind(this) )({ action: 'download', bucketName, 'objectPath+': key, }); const resp = await fetch(uploadUrl.signedUrl, { method: 'GET', }); if (!resp.ok) { throw new Error('Failed to download file'); } return resp.arrayBuffer(); } /** * This helper performs a `getPresignedUrl` request for Z3 URLs of the forms * `https://projects-api.oystehr.com/v1/z3/<bucket>/<key>` or `z3://<bucket>/<key>` * instead of the standard SDK `Z3GetPresignedUrlParams`. * * @param params url and action */ export async function getPresignedUrlForZ3Url( this: SDKResource, params: { url: string; action: Z3GetPresignedUrlParams['action'] } ): Promise<Z3GetPresignedUrlResponse> { let bucket: string; let key: string; const url = new URL(params.url); if (url.protocol === 'z3:') { // remove leading forward slash const z3PathParts = url.pathname.split('/').slice(1); bucket = url.hostname; key = z3PathParts.join('/'); } else if (url.href.startsWith(this.config.services?.['projectApiUrl'] ?? defaultProjectApiUrl)) { // remove leading `/v1/z3` const httpsPathParts = url.pathname.split('/').slice(3); bucket = httpsPathParts[0]; key = httpsPathParts.slice(1).join('/'); } else { throw new OystehrSdkError({ message: 'Invalid Z3 URL', code: 400 }); } const requestParams: Z3GetPresignedUrlParams = { action: 'upload', bucketName: bucket, 'objectPath+': key, }; return this.request('/z3/{bucketName}/{objectPath+}', 'post', baseUrlThunk.bind(this))(requestParams); }