Greetings Everyone!
I am aiming to transfer the database (RealmJS
) that is currently stored on my device storage to Google Drive using Google Drive API V3
. To accomplish this, I have already installed various node modules such as react-native-fs
and
@react-native-community/google-signin
.
The process of uploading the database is progressing smoothly. However, I am encountering difficulty in determining the appropriate method for file upload. After extensive research, I came across methods like Buffer
, new Blob()
, and new FormData()
.
Despite trying all three methods, I observed discrepancies in file size with the Buffer
and new Blob()
options, while the new FormData()
method consistently resulted in network errors despite having a stable network connection.
Given my limited experience with Google Drive API V3
and struggles with English comprehension, I am seeking assistance in resolving this issue. Any insights or solutions shared will not only benefit me but also assist other readers facing similar challenges. Please include a clear explanation along with any provided code snippets.
Below is the code snippet I am working with:
import fs from 'react-native-fs';
import {GoogleSignin} from '@react-native-community/google-signin';
/**
* Logging into my personal Google account to retrieve the access token
*/
async function backupDatabase() {
const {accessToken} = await GoogleSignin.getTokens();
const noneMime = 'application/octet-stream';
/**
* Using "uploadType=resumable" due to larger file size exceeding 5MB
*/
const requestUpload = await fetch(
'https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable',
{
method: 'POST',
headers: {
Authorization: `Bearer ${accessToken}`,
'Content-Type': 'application/json; charset=UTF-8',
'X-Upload-Content-Type': noneMime,
},
body: JSON.stringify({
name: 'mydb.realm',
mimeType: noneMime,
description: 'Backup Database',
parents: ['appDataFolder'],
}),
},
);
if (requestUpload.ok) {
const resumableUploadURL = requestUpload.headers.get('location');
/**
* Reading the file with ".realm" extension and encoding it in "base64"
*/
const myFile = await fs.readFile(myPathFile, 'base64');
/**
* Uploading the file using different methods
*/
const fileBlob = new Blob([myFile], {type: noneMime});
const fileBuffer = Buffer.from(myFile, 'base64');
// The following method consistently fails causing network issues even though the connection is fine
const fileFormData = new FormData();
fileFormData.append('file', fileBlob);
const uploadDatabase = await fetch(resumableUploadURL, {
method: 'PUT',
headers: {
Authorization: `Bearer ${accessToken}`,
'Content-Type': 'application/octet-stream',
'X-Upload-Content-Type': 'application/octet-stream',
},
// Unsure about which method to use - "Buffer", "Blob", or "FormData"?
body: fileBlob, // OR "fileBuffer" OR "fileFormData"
});
const responseUpload = await uploadDatabase.json();
console.log(responseUpload);
}
}