This repository has been archived by the owner on Oct 15, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdrive.js
89 lines (76 loc) · 2.11 KB
/
drive.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
// Source https://blog.tericcabrel.com/upload-file-to-google-drive-with-nodejs/
const fs = require("fs");
const { google } = require("googleapis");
/**
* Browse the link below to see the complete object returned for folder/file creation and search
*
* @link https://developers.google.com/drive/api/v3/reference/files#resource
*/
class GoogleDriveService {
driveClient;
constructor(clientId, clientSecret, redirectUri, refreshToken) {
this.driveClient = this.createDriveClient(
clientId,
clientSecret,
redirectUri,
refreshToken
);
}
createDriveClient(clientId, clientSecret, redirectUri, refreshToken) {
const client = new google.auth.OAuth2(clientId, clientSecret, redirectUri);
client.setCredentials({ refresh_token: refreshToken });
return google.drive({
version: "v3",
auth: client,
});
}
createFolder(folderName) {
return this.driveClient.files.create({
resource: {
name: folderName,
mimeType: "application/vnd.google-apps.folder",
},
fields: "id, name",
});
}
getAllFolders() {
return new Promise((resolve, reject) => {
this.driveClient.files.list(
{
q: `mimeType='application/vnd.google-apps.folder'`,
spaces: "drive",
fields: "files(id)",
},
(err, res) => {
if (err) {
return reject(err);
}
return resolve(res.data.files);
}
);
});
}
saveFile(fileName, filePath, fileMimeType, folderId) {
return this.driveClient.files.create({
requestBody: {
name: fileName,
mimeType: fileMimeType,
parents: folderId ? [folderId] : [],
},
media: {
mimeType: fileMimeType,
body: fs.createReadStream(filePath),
},
});
}
async testCredentials(folderId) {
const folders = await this.getAllFolders();
const hasFolderId = folders.some((folder) => folder.id === folderId);
if (!hasFolderId) {
throw new Error("Given Drive folder ID cannot be accessed or found.");
}
}
}
module.exports = {
GoogleDriveService,
};