Я разрабатываю приложение SSR с использованием Adonis Js и использую Google Drive для хранения файлов. Я выполнил базовую c node js начальную настройку и добился некоторого прогресса.
// FileManagerController.js
'use strict'
const fs = require("fs");
const util = require("util");
const readline = require("readline");
const { google } = require("googleapis");
const Helpers = use('Helpers')
const fsp = fs.promises;
readline.Interface.prototype.question[util.promisify.custom] = function (
prompt
) {
return new Promise((resolve) =>
readline.Interface.prototype.question.call(this, prompt, resolve)
);
};
readline.Interface.prototype.questionAsync = util.promisify(
readline.Interface.prototype.question
);
// If modifying these scopes, delete token.json.
const SCOPES = ["https://www.googleapis.com/auth/drive"];
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
const TOKEN_PATH = "token.json";
class FileManagerController {
async index({ request, response, view }) {
const content = await fsp.readFile("credentials.json");
const oAuth2Client = await this.authorize(JSON.parse(content));
const files = await this.listFiles(oAuth2Client);
const folders = await this.listFolders(oAuth2Client);
console.log(folders);
return view.render('file-manager', {files: files, folders: folders})
}
async authorize(credentials) {
const { client_secret, client_id, redirect_uris } = credentials.installed;
const oAuth2Client = new google.auth.OAuth2(
client_id,
client_secret,
redirect_uris[0]
);
// Check if we have previously stored a token.
try {
const token = await fsp.readFile(TOKEN_PATH);
oAuth2Client.setCredentials(JSON.parse(token).tokens);
return oAuth2Client;
} catch (error) {
console.error(error);
return this.getAccessToken(oAuth2Client);
}
}
async getAccessToken(oAuth2Client) {
const authUrl = oAuth2Client.generateAuthUrl({
access_type: "offline",
scope: SCOPES,
});
console.log("Authorize this app by visiting this url:", authUrl);
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
const code = await rl.questionAsync("Enter the code from that page here: ");
rl.close();
try {
const token = await oAuth2Client.getToken(code);
oAuth2Client.setCredentials(token);
// Store the token to disk for later program executions
await fsp.writeFile(TOKEN_PATH, JSON.stringify(token));
return oAuth2Client;
} catch (error) {
console.error("Error retrieving access token", error);
throw error;
}
}
async listFiles(auth) {
try {
const drive = google.drive({ version: "v3", auth });
const response = await drive.files.list({
q: "mimeType != 'application/vnd.google-apps.folder'",
fields: "nextPageToken, files(id, name, mimeType, kind, fileExtension, size, iconLink, parents, thumbnailLink, hasThumbnail)",
orderBy: "modifiedTime"
});
return response.data.files;
} catch (error) {
console.error("The API returned an error:", error);
}
}
async listFolders(auth) {
try {
const drive = google.drive({ version: "v3", auth });
const response = await drive.files.list({
q: "mimeType = 'application/vnd.google-apps.folder'",
fields: "nextPageToken, files(id, name, mimeType, kind, fileExtension, size, iconLink, parents, thumbnailLink, hasThumbnail)",
orderBy: "modifiedTime"
});
return response.data.files;
} catch (error) {
console.error("The API returned an error:", error);
}
}
}
Список папок и файлов работает нормально. Затем я сделал функцию удаления, как показано ниже
// FileManagerController.js
async deleteFile(auth) {
try {
const drive = google.drive({ version: "v3", auth });
const response = await drive.files.delete({
fileId: "1aLn7yhiK_m6Orvz5QstgZfQ289XV4xdW"
});
} catch (error) {
console.error("The API returned an error:", error);
}
}
Но для этого я получаю эту ошибку
The API returned an error: TypeError: authClient.request is not a function
at createAPIRequestAsync (C:\Projects_Laravel\kramana\node_modules\googleapis-common\build\src\apirequest.js:273:31)
at Object.createAPIRequest (C:\Projects_Laravel\kramana\node_modules\googleapis-common\build\src\apirequest.js:53:16)
at Resource$Files.delete (C:\Projects_Laravel\kramana\node_modules\googleapis\build\src\apis\drive\v3.js:692:44)
at FileManagerController.deleteFile (C:\Projects_Laravel\kramana\app\Controllers\Http\FileManagerController.js:130:48)
at Server._routeHandler (C:\Projects_Laravel\kramana\node_modules\@adonisjs\framework\src\Server\index.js:121:31)
at MiddlewareBase._resolveMiddleware (C:\Projects_Laravel\kramana\node_modules\@adonisjs\middleware-base\index.js:195:28)
at Runnable._invoke (C:\Projects_Laravel\kramana\node_modules\co-compose\src\Runnable.js:76:42)
at once (C:\Projects_Laravel\kramana\node_modules\co-compose\src\Runnable.js:73:34)
at f (C:\Projects_Laravel\kramana\node_modules\once\once.js:25:25)
at Auth.handle (C:\Projects_Laravel\kramana\node_modules\@adonisjs\auth\src\Middleware\Auth.js:127:11)
(node:8136) ExperimentalWarning: The fs.promises API is experimental
Кто-нибудь может мне помочь? Почему возникает эта ошибка? Как это решить?