Is it possible to instantly utilize the unique Ids of newly created files and folders in Google Drive API?

INQUIRY IN BRIEF:

I am seeking to utilize Javascript to generate a folder structure while verifying the existence of any/all/none of the folders. Providing folder names "A", "B", "C", and "D", I aim to create "A" in the root directory, then establish "B" within "A", continuing this pattern. The challenge lies in the asynchronous insertion of all folders without their respective ParentIds, leading them all to be placed in the root directory.

EXPANDED VERSION AND WORK IN PROGRESS (WIP):

My goal is to simultaneously create three or more folders along the same path.

For instance, if the desired file path is State\City\Street, I begin by arranging the folders in an array according to the preferred order (note that in the final project, these will not be hardcoded but generated dynamically based on user and Salesforce record).

const filePath = ["State", "City", "Street"];

The next step involves passing this information to a method responsible for creating these folders sequentially, utilizing the preceding folder's Id as its parentId.

function createFolder() {

    var parentFolderId = "root";

    for (let i = 0; i < filePath.length; i++) {

        var folderMetadata = {
            'name' : filePath[i],
            'mimeType' : 'application/vnd.google-apps.folder',
            'parents': [parentFolderId]
        }
        gapi.client.drive.files.create({
            resource: folderMetadata,
        }).then(function(response) {
            switch(response.status){
                case 200:
                    var file = response.result;
                    parentFolderId = file.Id;
                    console.log(i + ' file.Id= ' + file.Id);
                    break;
                default:
                    console.log('Error creating the folder, ' + response);
                    break;
            }
        });
     }
}

However, due to the asynchronous nature of the process, all folders are created after the function completion, prior to the execution of the "parentFolderId = file.Id;" line, resulting in placement within the root directory.

I acknowledge that an alternative approach could involve creating all folders, querying them, and subsequently rearranging. However, the subsequent phase of my project entails dynamically identifying the presence of any/all existing folders, with potential variations in the folder structure.

Answer №1

After some adjustments, I found that the solution provided by @Alessandro on this particular inquiry actually suited my needs:

  • To enhance readability, I decided to reverse the order of the methods.
  • Given the depth of my file structure, I integrated a FOR loop to handle multiple nested folders in the directory path.
  • I observed that the condition (!parent) was not returning properly due to being "undefined" instead of "null." Ensuring that it defaulted to "null" when an existing folder wasn't located was essential. Thus, I set parentId to "root" since the initial folder would always be at the root level.
  • The variable newFolderId stores the created or found folder's ID and is utilized as the parentId for the subsequent iteration in the FOR loop.
  • Lastly, I modified "'parent': parent" to "'parents' : [parent]." The addition of the plural 's' and enclosing brackets proved crucial; otherwise, each newly created folder defaulted to the root directory.
        async function constructFilePath() {

            console.log("constructFilePath()");

            var parentId = "root";

            for (let i = 0; i < filePath.length; i++) {
                var folderName = filePath[i];

                newFolderId = await getFolder(folderName, parentId);
                console.log(folderName + " id is " + newFolderId + ", parentId is " + parentId);
                if (newFolderId == null) {
                    newFolderId = await createFolder(folderName,parentId);
                    console.log ("created new folder " + folderName + " with Id " + parentId);
                } else {
                    // parentId = newParentId;
                    console.log (folderName + " already exist, move on to next.");
                }
                parentId = newFolderId;
            }
        }
        async function getFolder(name, parent) {

            const res = await gapi.client.drive.files.list({
                'pageSize': 1,
                'fields': "nextPageToken, files(id, name, mimeType, parents)",
                'q': "mimeType='application/vnd.google-apps.folder' \
                            and '" + parent + "' in parents \
                            and name = '" + name + "' \
                            and trashed = false"
            });
            return res.result.files.length > 0 ? res.result.files[0]['id'] : null;
        }
        async function createFolder(name, parent) {

            if (!parent) parent = 'root';

            var fileMetadata = {
                'name': name,
                'mimeType': 'application/vnd.google-apps.folder',
                'parents': [parent]
            };
            const res = await gapi.client.drive.files.create({
                'resource': fileMetadata,
                'fields': 'id'
            });
            return res.result['id'];
        }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Master the art of customizing SweetAlert designs!

Can anyone provide guidance on how to style the AJAX response data in SweetAlert? Below is my code and a sample image. Any assistance would be greatly appreciated. Order screenshot swal({ title: "Confirm your transaction", html:true, showSpinner: ...

When the email field is changed, the string is not being set to the state if it is

I encountered a strange issue while setting an email input as a string to state. Even though I can see on React Dev Tools that it gets sent, when I try to log it from another function, I get an empty string. The odd part is, if I change the order of the in ...

JavaScript bug: receiving an 'undefined' error when using getElementsByClassName

How can I retrieve the children of a specific div that belongs to the "vid_div selected" class? First, I select the correct div using this code: var vid_div = document.getElementsByClassName('vid_div selected'); However, when attempting to acces ...

The iframe is not large enough to contain all the HTML content

I'm encountering a problem with a website I'm currently developing - specifically, I am struggling to embed an HTML document into an iframe in a manner that fills the entire page. Additionally, I am utilizing Angular to retrieve the HTML document ...

How can I successfully implement the Add To Calendar Button Package?

Recently, I decided to incorporate this particular component into my application. Although it seemed simple enough at first, I'm now faced with a puzzling TypeError originating from within the package. The react component I am constructing is as foll ...

Unable to add a review to the user profile using Node.js (Express) and MongoDB (Mongoose)

I am encountering an issue when it comes to adding reviews for a user. After creating a review for a user, only the ID is displayed, but not the text or author or any other properties. I would appreciate any insights on this matter. Below are my schemas a ...

How can we manually trigger $(document).ready() from within the ready callback of head.js using jQuery?

I am in search of ways to enhance the loading speed of a web application, particularly one that encompasses numerous javascript files on every HTML page. My plan is to experiment with head.js on a specific page to observe if it has a positive impact on loa ...

Tips for passing parameters to a function in an object declaration

I am facing a challenge in my code where I have most of it inside an object literal. There are a few functions where I would like to pass arguments as parameters, but I am struggling to make it work. Here is a snippet of the object structure: var example ...

Sending parameters to a function within the ngAfterViewInit() lifecycle method in Angular version 6

As a beginner in coding, I have created a canvas in Angular and am attempting to pass data received from my server to a function within ngAfterViewInit(). When I hard code the values I want to pass, everything works perfectly. However, if I try to pass da ...

Is it possible to retrieve browser history from Google Chrome using Node.js on a Windows operating system?

I'm currently developing a personal electron app for managing my lifestyle. One of the key features is controlling my daily internet browsing through the app. I am aiming to integrate my Chrome history into the electron app. Could someone recommend a ...

Signal for a complete 360 degree rotation of an image

Looking to enhance my 360 image rotator with an indicator that fades out after the first image. I added this function to the end of my 360.js: (function(){ if( $('#first').css('visibility','hidden')) { $('#rotat ...

The attempt to install myapp using npx create-react-app has failed. The installation has been aborted

Attempting to create a new project using npx create-react-app my-app resulted in an error message saying Aborting installation. https://i.sstatic.net/IhpQJ.jpg Initially, I had node v14.17.1 installed. Upgrading to the latest version 16.4.0 did not resol ...

Angular directives make it possible to easily toggle a single item with just

I have a group of "toggleable" items. When a "toggleable" element is clicked, it expands using the ng-show directive. The item remains open if clicked inside, but contracts when clicked elsewhere. To achieve this functionality, I created a directive that ...

Tips for displaying a modal within a modal in React

Currently, I have two components with modals. My goal is to open one modal from a button in the other component but clicking the button only closes the current active modal and doesn't open a new one. //Modal 1 <div className="modal fade" ...

Using React - accessing a variable that has been declared within the componentDidMount method and utilizing it within the render

Below is the code I have implemented to retrieve an object from Window and utilize it during rendering. Upon checking the console, I noticed that the value of componentData appears as undefined. How can I resolve this issue and access the value properly? ...

Dramatist: What are effective methods for distinguishing and monitoring frames within a webpage?

When it comes to storing my own copy of frames, I want to utilize the page.on("frameattached") and page.on("framedetached") events to properly manage the lifecycle of the frames. My main concern is how I can uniquely identify them across these events. I ...

What is the best way to retrieve a jobID from Kue?

I am currently working with Express and I'm facing a challenge in creating a job whenever someone posts to my route. My goal is to have the response include the job.id, but the job id is only generated within the callback of my queue.createFunction. I ...

Ember - Issue with Page Display

Currently tackling my first ember application, which consists of two pages: the Welcome page and a page displaying student details. To accomplish this, I have established two routes named index and studentdb. Unfortunately, I'm encountering an issue w ...

alert the Q Promise progress within a Node.js environment

When attempting to utilize the Q Promise Progress feature, my code is designed to catch progress and resolve the Promise once progress reaches 100. Here is the specific code snippet: var q = require("q"); var a = function(){ return q.Promise(functio ...