TypeScript: GoogleDrive の TeamDrive の 任意のフォルダーにファイルを作成する

目次

はじめに

googleapis を使うと色々な Google サービスにアクセスできますが、 TeamDrive やその中の任意のフォルダーにファイル(例えば、Spreadsheet ファイル)を作成する方法についてメモしておきます。

Version

  • typescript: 4.6.3
  • googleapis: 100.0.0

GoogleDrive の TeamDrive の 任意のフォルダーにファイルを作成する方法

Install googleapis

まず googleapis を Install します。

npm install googleapis

Service Account の作成

Google のサービスアカウントが必要なので、作成しておきます。 作成方法については検索すると出てくると思いますので割愛します。

書き方

サービスアカウントの内容が SERVICE_ACCOUNT_CREDENTIALS にあるとして、 例えば、このように createFileInGoogleDrive() を定義して、

import { google } from "googleapis";

export type CreateGoogleDriveFileProps = {
  name: string; // Filename
  mimeType: string; // ファイルの種類。 https://developers.google.com/drive/api/guides/mime-types
  parents?: string[]; // 親の 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;
}

以下のように呼び出します。

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

ポイント

  • 認証情報は最初に google.options で渡しておく
  • Files API を使う
  • Scopes とか MimeType などは 調べる必要がある