TypeScript: Create a file in any folder in GoogleDrive's TeamDrive

Page content

Introduction

While googleapis can be used to access various Google services, we note how to create files (e.g., Spreadsheet files ) in TeamDrive or any folder within it.

Version

  • typescript: 4.6.3
  • googleapis: 100.0.0

How to create a file in any folder in GoogleDrive’s TeamDrive

Install googleapis

Install googleapis first.

npm install googleapis

Creating a Service Account

You will need a Google service account, so create one. You can find the procedure for creating a Google Service Account by searching for it.

How to Write

Assuming the service account contents are in SERVICE_ACCOUNT_CREDENTIALS. For example, if you define createFileInGoogleDrive() like this

import { google } from "googleapis";

export type CreateGoogleDriveFileProps = {
  name: string; // Filename
  mimeType: string; // File Type。 https://developers.google.com/drive/api/guides/mime-types
  parents?: string[]; // Parent Folder ID
  teamDriveId?: string; // TeamDrive ID
};

export type GoogleServiceScopeType = "spreadsheet";

function convertScopes(
  typeNames: GoogleServiceScopeType[] | string[]
): string[] {
  const scopes: Set<string> = new Set();
  for (const typeName of typeNames) {
    switch (typeName) {
      case "spreadsheet": {
        scopes.add("https://www.googleapis.com/auth/drive");
        scopes.add("https://spreadsheets.google.com/feeds");
        break;
      }
      default:
        scopes.add(typeName);
    }
  }
  return Array.from(scopes.values());
}

export interface ServiceAccountCredentials {
  client_email: string;
  private_key: string;
}

export function initGoogleApi(
  credentials: ServiceAccountCredentials,
  scopes: string[] | GoogleServiceScopeType[]
) {
  google.options({
    auth: new google.auth.GoogleAuth({
      credentials,
      scopes: convertScopes(scopes),
    }),
  });
}

export async function createFileInGoogleDrive(
  props: CreateGoogleDriveFileProps
): Promise<string | undefined> {
  const drive = google.drive("v3");
  const requestBody: CreateGoogleDriveFileProps = { ...props };
  const file = await drive.files.create({
    requestBody,
    supportsTeamDrives: !!requestBody.teamDriveId,
  });
  return file.data["id"] || undefined;
}

Call as follows

initGoogleApi(SERVICE_ACCOUNT_CREDENTIALS, ["spreadsheet"]);
const fileId = await createFileInGoogleDrive({
  name: "MySheet",
  mimeType: "application/vnd.google-apps.spreadsheet",
  parents: [FOLDER_ID],
  teamDriveId: TEAM_DRIVE_ID,
});

Key Points

  • Authentication information is first passed as google.options.
  • Use Files API
  • You need to look up Scopes and MimeType.