google drive | insert google drive permissions | test google sheet create | Search

The createSheet(email) function creates a Google Sheets document, inserts permissions for two emails, and exports it as a module, using the authorizeSheets and insertPermission modules to handle authorization and permission insertion.

Run example

npm run import -- "create a sheet in google drive"

create a sheet in google drive

var util = require('util');
var importer = require('../Core');
var authorizeSheets = importer.import("authorize sheets api");
var insertPermission = importer.import("insert google drive permissions");

function createSheet(email) {
    var sheets;
    
    return authorizeSheets()
        .then(s => sheets = s)
        .then(() => util.promisify(sheets.spreadsheets.create.bind(sheets))())
        .then(r => insertPermission(r.data.spreadsheetId, 'megamindbrian@gmail.com'))
        .then(r => insertPermission(r.data.spreadsheetId, email))
}

module.exports = createSheet;

What the code could have been:

const { google } = require('googleapis');
const { authorizeSheets, insertPermission } = require('../Core');

/**
 * Creates a new Google Sheet and grants the specified email permission to access it.
 * @param {string} email The email address to grant permission to.
 * @returns {Promise}
 */
async function createSheet(email) {
  // TODO: Validate the provided email address.

  const auth = new google.auth.GoogleAuth();
  const sheets = google.sheets({ version: 'v4', auth });

  // Authorize the API client
  await authorizeSheets(sheets);

  // Create a new spreadsheet
  const spreadsheet = await sheets.spreadsheets.create({
    properties: {
      title: 'New Spreadsheet',
    },
  });

  // Insert permission for the specified email address
  await insertPermission(spreadsheet.data.spreadsheetId, email);
  await insertPermission(spreadsheet.data.spreadsheetId,'megamindbrian@gmail.com');

  // TODO: Return the spreadsheet ID or other relevant information.
}

module.exports = createSheet;

Code Breakdown

Dependencies

Imported Modules

Function: createSheet(email)

This function creates a Google Sheets document and inserts permissions for two emails.

Code Flow

  1. authorizeSheets(): authorizes the application to use the Google Sheets API.
  2. util.promisify(sheets.spreadsheets.create.bind(sheets))(): creates a new Google Sheets document using the Sheets API.
  3. insertPermission(r.data.spreadsheetId,'megamindbrian@gmail.com'): inserts permission for'megamindbrian@gmail.com' using the created spreadsheet ID.
  4. insertPermission(r.data.spreadsheetId, email): inserts permission for the provided email using the created spreadsheet ID.

Export

The createSheet(email) function is exported as a module, making it available for use in other parts of the application.