@oystehr/sdk
Version:
Oystehr SDK
82 lines (78 loc) • 2.67 kB
JavaScript
;
var client = require('../../client/client.cjs');
var index = require('../../errors/index.cjs');
function baseUrlThunk() {
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
*/
async function uploadFile({ bucketName, 'objectPath+': key, file, }) {
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
*/
async function downloadFile({ bucketName, 'objectPath+': key, }) {
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
*/
async function getPresignedUrlForZ3Url(params) {
let bucket;
let key;
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'] ?? client.defaultProjectApiUrl)) {
// remove leading `/v1/z3`
const httpsPathParts = url.pathname.split('/').slice(3);
bucket = httpsPathParts[0];
key = httpsPathParts.slice(1).join('/');
}
else {
throw new index.OystehrSdkError({ message: 'Invalid Z3 URL', code: 400 });
}
const requestParams = {
action: 'upload',
bucketName: bucket,
'objectPath+': key,
};
return this.request('/z3/{bucketName}/{objectPath+}', 'post', baseUrlThunk.bind(this))(requestParams);
}
exports.downloadFile = downloadFile;
exports.getPresignedUrlForZ3Url = getPresignedUrlForZ3Url;
exports.uploadFile = uploadFile;
//# sourceMappingURL=z3-ext.cjs.map