How to add multiple users email id to share file from a google drive api using node js

Viewed 23

When I run this code , an error came ==>

The permission type field is required.

How can i use multiple Email addressess to share the file of google drive in node js

async function updateFilePermissions(){
    try{
        const fileId = fileId;
let resourceContents = [{
    role: 'writer',
    type: 'user',
    emailAddress: 'SomeEmail@gmail.com',
  },{
    role: 'writer',
    type: 'user',
    emailAddress: 'someEmail@gmail.com'
  }];

  await drive.permissions.create({

    resource: resourceContents,
    fileId: fileId,
    sendNotificationEmail: true,
    fields: '*'

  });
 /* 
    webViewLink: View the file in browser
    webContentLink: Direct download link 
    */
    const result = await drive.files.get({
      fileId: fileId,
      fields: 'webViewLink, webContentLink',
    });
    console.log(result.data);
  } catch (error) {
    console.log(error.message);
  }
}
1 Answers

I believe your goal is as follows.

  • You want to create the permissions to 2 email addresses as role: 'writer' and type: 'user'.
  • You want to achieve this using googleapis for Node.js.
  • You have permission for creating the permissions to the file. And also, your access token can be used for creating the permissions to the file.

Unfortunately, in the current stage, an array cannot be used for resource of drive.permissions.create of googleapis for Node.js. In this case, please use it in a loop. When this is reflected in your script, how about the following modification?

From:

let resourceContents = [{
    role: 'writer',
    type: 'user',
    emailAddress: 'SomeEmail@gmail.com',
  },{
    role: 'writer',
    type: 'user',
    emailAddress: 'someEmail@gmail.com'
  }];

  await drive.permissions.create({

    resource: resourceContents,
    fileId: fileId,
    sendNotificationEmail: true,
    fields: '*'

  });

To:

const emails = ['SomeEmail@gmail.com', 'someEmail@gmail.com'];
for (let i = 0; i < emails.length; i++) {
  const res = await drive.permissions
    .create({
      resource: {
        role: "writer",
        type: "user",
        emailAddress: emails[i],
      },
      fileId: fileId,
      sendNotificationEmail: true,
      fields: "*",
    })
    .catch((err) => console.log(err.errors));
  if (res) console.log(res.data);
}
  • When this script is run, the permission of role: "writer", type: "user" for the file of fileId is given to the emails of emails.

References:

Related