@mussnad/frappe-js-client
Version:
Next-generation TS/JS client for Frappe REST APIs, built on axios for robust, type-safe integration.
229 lines (228 loc) • 7.64 kB
JavaScript
;
/**
* @module file
* @description Provides functionality for file upload operations in Frappe.
* This module handles file uploads with progress tracking, authentication,
* and custom metadata support.
*
* @packageDocumentation
*
* @example
* ```typescript
* import { FrappeApp } from '@frappe/sdk';
*
* const app = new FrappeApp('https://instance.example.com');
* const fileUploader = app.file();
*
* // Upload a file with progress tracking
* await fileUploader.uploadFile(
* fileBlob,
* {
* isPrivate: true,
* folder: 'Home/Documents'
* },
* (uploaded, total) => {
* console.log(`Progress: ${(uploaded/total) * 100}%`);
* }
* );
* ```
*/
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.FrappeFileDownload = exports.FrappeFileUpload = void 0;
var axios_1 = require("../utils/axios");
/**
* Handles file upload operations for Frappe.
*
* @class FrappeFileUpload
* @description Provides methods for uploading files to a Frappe instance with
* support for progress tracking, authentication, and custom metadata.
*
* @example
* ```typescript
* const uploader = new FrappeFileUpload(
* 'https://instance.example.com',
* axiosInstance,
* true,
* () => localStorage.getItem('token'),
* 'Bearer'
* );
*
* // Upload a file
* const response = await uploader.uploadFile(
* file,
* { isPrivate: true }
* );
* ```
*/
var FrappeFileUpload = /** @class */ (function () {
/**
* Creates a new FrappeFileUpload instance.
*
* @param appURL - Base URL of the Frappe instance
* @param axios - Configured Axios instance for making requests
* @param useToken - Whether to use token-based authentication
* @param token - Function that returns the authentication token
* @param tokenType - Type of token to use ('Bearer' or 'token')
* @param customHeaders - Additional headers to include in requests
*
* @example
* ```typescript
* const uploader = new FrappeFileUpload(
* 'https://instance.example.com',
* axiosInstance,
* true,
* () => localStorage.getItem('token'),
* 'Bearer'
* );
* ```
*/
function FrappeFileUpload(appURL, axios, useToken, token, tokenType, customHeaders) {
this.appURL = appURL;
this.axios = axios;
this.useToken = useToken !== null && useToken !== void 0 ? useToken : false;
this.token = token;
this.tokenType = tokenType;
this.customHeaders = customHeaders;
}
/**
* Uploads a file to the Frappe instance with optional progress tracking.
*
* @template T - Type of additional data to be sent with the file
* @param file - The file to upload
* @param args - Configuration options for the upload
* @param onProgress - Optional callback for tracking upload progress
* @param apiPath - Optional custom API endpoint path (defaults to 'upload_file')
*
* @returns Promise that resolves with the upload response
* @throws {FrappeError} If the upload fails
*
* @example
* ```typescript
* // Basic file upload
* const response = await uploader.uploadFile(
* file,
* { isPrivate: true }
* );
*
* // Upload with progress tracking
* const response = await uploader.uploadFile(
* file,
* { folder: 'Home/Documents' },
* (uploaded, total) => {
* console.log(`Progress: ${(uploaded/total) * 100}%`);
* }
* );
*
* // Upload with custom metadata
* interface CustomData {
* category: string;
* }
*
* const response = await uploader.uploadFile<CustomData>(
* file,
* {
* doctype: 'File',
* docname: 'FILE-001',
* otherData: { category: 'Important' }
* }
* );
* ```
*/
FrappeFileUpload.prototype.uploadFile = function (file, args, onProgress, apiPath) {
if (apiPath === void 0) { apiPath = 'upload_file'; }
var formData = new FormData();
if (file)
formData.append('file', file, file.name);
var isPrivate = args.isPrivate, folder = args.folder, file_url = args.file_url, doctype = args.doctype, docname = args.docname, fieldname = args.fieldname, otherData = args.otherData;
if (isPrivate) {
formData.append('is_private', '1');
}
if (folder) {
formData.append('folder', folder);
}
if (file_url) {
formData.append('file_url', file_url);
}
if (doctype && docname) {
formData.append('doctype', doctype);
formData.append('docname', docname);
if (fieldname) {
formData.append('fieldname', fieldname);
}
}
if (otherData) {
Object.keys(otherData).forEach(function (key) {
var v = otherData[key];
formData.append(key, v);
});
}
return (0, axios_1.handleRequest)({
axios: this.axios,
config: {
url: "/api/method/".concat(apiPath),
data: formData,
onUploadProgress: function (progressEvent) {
if (onProgress) {
onProgress(progressEvent.loaded, progressEvent.total, progressEvent);
}
},
headers: __assign(__assign({}, (0, axios_1.getRequestHeaders)(this.useToken, this.tokenType, this.token, this.appURL, this.customHeaders)), { 'Content-Type': 'multipart/form-data' }),
},
errorMessage: 'There was an error while uploading the file.',
transformResponse: function (response) { return response.data.message; },
});
};
return FrappeFileUpload;
}());
exports.FrappeFileUpload = FrappeFileUpload;
/**
* Handles file download operations for Frappe.
*
* @class FrappeFileDownload
* @description Provides methods for downloading files from a Frappe instance.
*
* @example
* ```typescript
* const downloader = new FrappeFileDownload(axiosInstance)
* const response = await downloader.downloadFile('https://instance.example.com/files/test.pdf')
* ```
*/
var FrappeFileDownload = /** @class */ (function () {
function FrappeFileDownload(axios) {
this.axios = axios;
}
/**
* Downloads a file from the Frappe instance.
*
* @param fileURL - The URL of the file to download
* @returns Promise that resolves with the download response
* @throws {FrappeError} If the download fails
*/
FrappeFileDownload.prototype.downloadFile = function (fileURL) {
return (0, axios_1.handleRequest)({
axios: this.axios,
config: {
method: 'GET',
url: '/api/method/download_file',
params: {
file_url: fileURL,
},
},
errorMessage: 'There was an error while downloading the file.',
transformResponse: function (response) { return response.data; },
});
};
return FrappeFileDownload;
}());
exports.FrappeFileDownload = FrappeFileDownload;