LoginSignup
0
0

More than 3 years have passed since last update.

Node.jsでGoogle Drive内の特定のファイルが特定のフォルダの配下にいるかどうかを調べる (Google Drive API v3)

Posted at

Google Drive APIをNode.jsから触る以下の記事たちの続きです

GETメソッドを再帰的に使う

GETメソッドfieldsparentsを指定することで、親フォルダのIDを取得できます。
これを再帰的に繰り返していって、祖先を遡っていったときにフォルダ名が指定した名前のものが見つかったら終了です。

ちなみにGETメソッドの返却値はFILESのリファレンスを見ると確認できますが、けっこうたくさんあるので把握するのは大変そうですね。

スコープ

https://www.googleapis.com/auth/drive
https://www.googleapis.com/auth/drive.file
https://www.googleapis.com/auth/drive.readonly
https://www.googleapis.com/auth/drive.metadata.readonly
https://www.googleapis.com/auth/drive.appdata
https://www.googleapis.com/auth/drive.metadata
https://www.googleapis.com/auth/drive.photos.readonly

なかなか多い。

簡単な実装

基本的な認証周りなどのコードは他の記事同様です。

get.js

省略

//特定のファイル(fileId)が特定フォルダ(folderName)の配下にいるか確認
const folderName = `定期発生`; 
const fileId = `xxxxxxxxxxxxxxxxxxxx`;

async function loop(drive, fileId, path = ''){
    //STEP1: IDからファイル情報を取得
    const params = {
        fileId: fileId,
        fields: 'parents,name,kind,mimeType,id,spaces'
    }
    const res = await drive.files.get(params);
    console.log('---',res.data);
    path = `/${res.data.name}${path}`;

    //STEP2: 親フォルダのIDをGET - ここが複数あるとうまく動かないときあるかも...
    const parentsFolderId = res.data.parents[0];

    //STEP3: 親フォルダを再帰的に探していく
    try {
        if(res.data.name === folderName){
            console.log(`このファイルは${folderName}の配下です。`, path);
        }else{
            await loop(drive, parentsFolderId, path);        
        }
    } catch (error) {
        console.log(`このファイルは${folderName}の配下ではありません。`)
    }
}

async function main(auth) {
    const drive = google.drive({version: 'v3', auth});
    await loop(drive, fileId);
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0