Files
imexmobile/util/document-upload.utility.js

174 lines
4.7 KiB
JavaScript

import axios from "axios";
import env from "../env";
import { client } from "../graphql/client";
import { INSERT_NEW_DOCUMENT } from "../graphql/documents.queries";
import { axiosAuthInterceptorId } from "./CleanAxios";
//Context: currentUserEmail, bodyshop, jobid, invoiceid
//Required to prevent headers from getting set and rejected from Cloudinary.
var cleanAxios = axios.create();
cleanAxios.interceptors.request.eject(axiosAuthInterceptorId);
export const handleUpload = async (ev, context) => {
console.log("ev,context", ev, context);
const { onError, onSuccess, onProgress } = ev;
const { bodyshop, jobId } = context;
const newFile = await (await fetch(ev.uri)).blob();
let key = `${bodyshop.id}/${jobId}/${newFile.data.name.replace(
/\.[^/.]+$/,
""
)}`;
console.log("Got here");
return uploadToCloudinary(
key,
newFile.type,
newFile,
onError,
onSuccess,
onProgress,
context
);
};
export const uploadToCloudinary = async (
key,
fileType,
file,
onError,
onSuccess,
onProgress,
context
) => {
const {
bodyshop,
jobId,
billId,
uploaded_by,
callback,
tagsArray,
photo,
} = context;
//Set variables for getting the signed URL.
let timestamp = Math.floor(Date.now() / 1000);
let public_id = key;
let tags = `${bodyshop.textid},${
tagsArray ? tagsArray.map((tag) => `${tag},`) : ""
}`;
// let eager = process.env.REACT_APP_CLOUDINARY_THUMB_TRANSFORMATIONS;
//Get the signed url.
let signedURLResponse;
try {
signedURLResponse = await axios.post("https://api.imex.online/media/sign", {
public_id: public_id,
tags: tags,
timestamp: timestamp,
upload_preset: "incoming_upload",
});
} catch (error) {
console.log("ERROR GETTING SIGNED URL", error);
return { success: false, error: error };
}
if (signedURLResponse.status !== 200) {
console.log("Error Getting Signed URL", signedURLResponse.statusText);
if (!!onError) onError(signedURLResponse.statusText);
return { success: false, error: signedURLResponse.statusText };
}
//Build request to end to cloudinary.
var signature = signedURLResponse.data;
var options = {
headers: { "X-Requested-With": "XMLHttpRequest" },
onUploadProgress: (e) => {
if (!!onProgress) onProgress({ percent: (e.loaded / e.total) * 100 });
},
};
const formData = new FormData();
formData.append("file", {
uri: photo.uri,
type: fileType,
name: file.data.name,
});
console.log("Applying lower quality transforms.");
formData.append("upload_preset", "incoming_upload");
formData.append("api_key", env.REACT_APP_CLOUDINARY_API_KEY);
formData.append("public_id", public_id);
formData.append("tags", tags);
formData.append("timestamp", timestamp);
formData.append("signature", signature);
//Upload request to Cloudinary
let cloudinaryUploadResponse;
try {
cloudinaryUploadResponse = await cleanAxios.post(
`${env.REACT_APP_CLOUDINARY_ENDPOINT}/upload`,
formData,
{
...options,
}
);
console.log("Cloudinary Upload Response", cloudinaryUploadResponse.data);
} catch (error) {
console.log("CLOUDINARY error", error, cloudinaryUploadResponse);
return { success: false, error: error };
}
if (cloudinaryUploadResponse.status !== 200) {
console.log(
"Error uploading to cloudinary.",
cloudinaryUploadResponse.statusText,
cloudinaryUploadResponse
);
if (!!onError) onError(cloudinaryUploadResponse.statusText);
return { success: false, error: cloudinaryUploadResponse.statusText };
}
//Insert the document with the matching key.
const documentInsert = await client.mutate({
mutation: INSERT_NEW_DOCUMENT,
variables: {
docInput: [
{
jobid: jobId,
uploaded_by: uploaded_by,
key: key,
billid: billId,
type: fileType,
},
],
},
});
if (!documentInsert.errors) {
if (!!onSuccess)
onSuccess({
uid: documentInsert.data.insert_documents.returning[0].id,
name: documentInsert.data.insert_documents.returning[0].name,
status: "done",
key: documentInsert.data.insert_documents.returning[0].key,
});
// notification["success"]({
// message: i18n.t("documents.successes.insert"),
// });
if (callback) {
callback();
}
} else {
if (!!onError) onError(JSON.stringify(documentInsert.errors));
// notification["error"]({
// message: i18n.t("documents.errors.insert", {
// message: JSON.stringify(JSON.stringify(documentInsert.errors)),
// }),
// });
return { success: false, error: JSON.stringify(documentInsert.errors) };
}
return { success: true };
};