payloadcms-import-export-plugin
Version:
A comprehensive Payload CMS plugin that enables seamless import and export of collection data with support for CSV and JSON formats, featuring advanced field mapping, duplicate handling, and batch processing capabilities.
97 lines (96 loc) • 3.61 kB
JavaScript
'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { Button, SaveButton, toast, Translation, useConfig, useForm, useFormModified, useTranslation } from '@payloadcms/ui';
import React from 'react';
export const ExportSaveButton = ()=>{
const { t } = useTranslation();
const { config: { routes: { api }, serverURL }, getEntityConfig } = useConfig();
const { getData, setModified } = useForm();
const modified = useFormModified();
const exportsCollectionConfig = getEntityConfig({
collectionSlug: 'exports'
});
const disableSave = exportsCollectionConfig?.admin?.custom?.disableSave === true;
const disableDownload = exportsCollectionConfig?.admin?.custom?.disableDownload === true;
const label = t('general:save');
const handleDownload = async ()=>{
let timeoutID = null;
let toastID = null;
try {
setModified(false); // Reset modified state
const data = getData();
// Set a timeout to show toast if the request takes longer than 200ms
timeoutID = setTimeout(()=>{
toastID = toast.success('Your export is being processed...');
}, 200);
const response = await fetch(`${serverURL}${api}/exports/download`, {
body: JSON.stringify({
data
}),
credentials: 'include',
headers: {
'Content-Type': 'application/json'
},
method: 'POST'
});
// Clear the timeout if fetch completes quickly
if (timeoutID) {
clearTimeout(timeoutID);
}
// Dismiss the toast if it was shown
if (toastID) {
toast.dismiss(toastID);
}
if (!response.ok) {
throw new Error('Failed to download file');
}
const fileStream = response.body;
const reader = fileStream?.getReader();
const decoder = new TextDecoder();
let result = '';
while(reader){
const { done, value } = await reader.read();
if (done) {
break;
}
result += decoder.decode(value, {
stream: true
});
}
const blob = new Blob([
result
], {
type: 'text/plain'
});
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `${data.name}.${data.format}`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
} catch (error) {
console.error('Error downloading file:', error);
toast.error('Error downloading file');
}
};
return /*#__PURE__*/ _jsxs(React.Fragment, {
children: [
!disableSave && /*#__PURE__*/ _jsx(SaveButton, {
label: label
}),
!disableDownload && /*#__PURE__*/ _jsx(Button, {
disabled: !modified,
onClick: handleDownload,
size: "medium",
type: "button",
children: /*#__PURE__*/ _jsx(Translation, {
i18nKey: "upload:download",
t: t
})
})
]
});
};
//# sourceMappingURL=index.js.map