Node.js: cómo obtener contenido de la API de Google Drive de la manera más rápida posible

Estoy intentando crear un sitio web con Node.js y la API de Google Drive. Para hacerlo, después de obtener mi clave API de Google, puedo ir a un enlace como este:

https://www.googleapis.com/drive/v3/files?q=%27{my folder ID}%27+in+parents&key={my API key}

y obtengo una respuesta como esta:

{
 "kind": "drive#fileList",
 "incompleteSearch": false,
 "files": [
  {
   "kind": "drive#file",
   "id": "1MhS55q3ZmRyUxo_tPW3kqXuLIy-cAv1-",
   "name": "Capture001.png",
   "mimeType": "image/png"
  },
  {
   "kind": "drive#file",
   "id": "18y88x-DxOW4APcz6YGBFPVCeBB7eLPHC",
   "name": "contact.html",
   "mimeType": "text/html"
  },
  {
   "kind": "drive#file",
   "id": "1voNKTQv-kbyS-jJnsIXc-1OH1YudB3Xw4Dcvi6VKIqY",
   "name": "test",
   "mimeType": "application/vnd.google-apps.document"
  },
  {
   "kind": "drive#file",
   "id": "1QHbCATkynjDidEBjueVv4Qvh0ijfzV0S",
   "name": "Copy of 5737-12, 5738-01 (Freidin).mp4",
   "mimeType": "video/mp4"
  },
  {
   "kind": "drive#file",
   "id": "1u6VsnhYvvnEJlFXi_B7I-7DY4JkZP9mQ",
   "name": "Copy of 5750-01-03 Mincha-Maftir, Sicha and dollars.mpg",
   "mimeType": "video/mpeg"
  }
 ]
}

y luego si tuviera que obtener (teóricamente) una ID de un archivo en particular, entonces podría conectarlo a esta URL:

https://www.googleapis.com/drive/v3/files/{my file ID}?alt=media&key={my api key}

SO Estoy tratando de hacer un sitio web con node.js, que cuando alguien va a mi sitio web / nombre de usuario, entonces ese "nombre de sitio" accede a los valores en un diccionario con el ID de la carpeta principal en Google Drive, con la clave API, y luego es capaz de acceder teóricamente a todos los archivos / carpetas de esa carpeta con mysite / somename / file.png o /somename/contact.html o algo para mostrar páginas html, aquí está mi código completo de intento de nodejs hasta ahora (no todavía no admite subdirectorios), puede probarlo con su propia carpeta de Google Drive y clave API, solo conéctelo al objeto de la base de datos:

var http = require("http");
var fetch = require("node-fetch");

var gDriveFolder = (folderID, apiKey) => `https://www.googleapis.com/drive/v3/files?q=%27${folderID}%27+in+parents&key=${apiKey}`
var gDriveFile = (fileID, apiKey) => `https://www.googleapis.com/drive/v3/files/${fileID}?alt=media&key=${apiKey}`

var database = {
        "coby": {
            "apiKey":"{paste your API key here}",
            "folder":"{paste the shared URL of your Google Drive folder here}"
        }
    }
var server = http.createServer((request, response) => {

    var urlParts = request.url.split("/").filter(x => x.length > 0).map(x => x.split("%20").join(" "));



    if(urlParts[0] != "favicon.ico") { //to not make more than neccesary requests
        var html = "";
        var json = database;
        if(json) {
            console.log("We have a JSON!", json);
            if(urlParts.length > 0) {
                var folderWentTo = urlParts[0];
                var myData = null;
                for(var k in database) {
                    if(k == folderWentTo) {
                        myData = json[k];
                        break;
                    }
                    console.log(k, ":", json[k]);
                }

            }



            if(myData) {
                var key = myData["apiKey"];
                var mainFolderURL = gDriveFolder(IDfromDriveURL(myData["folder"]),key);
                console.log("main folder: ", mainFolderURL);
                myReq(mainFolderURL, (data) => {
                    var fileList = JSONorNull(data);
                    console.log("key???",key);
                    if(fileList) {
                        var html = "<b>nothing</b><br>";
                        var f = fileList["files"];
                        if(f) {
                            if(urlParts.length > 1) {
                                var fileObject = f.filter(x=>x["name"] == urlParts[1])[0];


                                if(fileObject) {
                                    var fileID = fileObject["id"];
                                    var fileRequestedURL = gDriveFile(fileID, key);
                                    console.log("trying to get contents of ", fileRequestedURL);
                                    myReq(fileRequestedURL, (fileData) => {
                                        html = fileData;
                                        console.log(fileObject["mimeType"]);
                                     //   console.log("file: ", fileObject["name"], "'s content: ", fileData);
                                    //    response.setHeader("Content-Type",fileObject["mimeType"]);
                                        response.end(html);
                                    });
                                } else {
                                    html = "file not found!";
                                    console.log("tried to find: ", urlParts[1], " in list: ", f);

                                    response.end(html);
                                }
                            } else {
                                console.log("loaded");
                                f.forEach((y, o) => {
                                //    var fileURL = gDriveFile(y["id"], myData["apiKey"]);
                                    html += `<a href="${urlParts[0]}/${y["name"]}">${y["name"]}</a><br>`
                                });
                                response.end(html);
                                console.log("printed");
                            }

                        } else {
                            response.end(html);
                        }

                    } else {
                        response.end("this data: " + data + " went wrong");
                    }
                });
            } else {
                html = ("asdf")
                response.end(html);
            }
            console.log("url parts:", urlParts);

        } else {
            console.log("no json :(");
            response.end("dude what happened with the JSON: " + json + ", from " + bdy);
        }

    }


    });

server.listen(80);

function myReq(url, cb) {
    var start = parseInt(Date.now());
    console.log("started", start);
    fetch(url).then(res => res.text()).then(body => {
        var end = parseInt(Date.now());
        console.log("ended at",end, " total:",(end-start));
       if(cb) {

            cb(body);
       }           
    });
}

function JSONorNull(str) {
    var result = null;
    try {
        result = JSON.parse(str);
    } catch(e) {
        console.log(str, " has an error: ", e);
    }
    return result;
}

function IDfromDriveURL(url) {
    return url.split("/").length > 1 ? (url.split("/").filter(x=>x.includes("open"))).join("").replace("open?id=", "") : url;
}

el problema: actualmente estoy usando node-fetch para obtener el contenido, como puede ver en la función myReq, pero esto aparentemente lleva mucho tiempo, IDK si es solo la API de Google, pero lo dudo, creo así es como obtengo el contenido ... Cuando trato de obtener una imagen simple de 800 kb con localhost / coby / Capture1.png, se imprime en mi consola (forma la función myReq):

started 1550048095674
ended at 1550048130691  total: 35017

eso significa que tomó 35 segundos cargar (y descargar automáticamente) la imagen ... También solo para la página principal localhost / coby, el resultado es de alrededor de 2500ms a 4440ms ...

SO claramente ya sea que algo está mal con la API de la unidad (lo cual dudo) o la recuperación de nodo está actuando muy lentamente ..

SO: ¿cuál es la forma más rápida de obtener el contenido de una página (y varias páginas, como lo que estoy haciendo) en node.js? Probé el módulo de solicitud, pero también es lento y se supone que la recuperación es más rápida ...

Intente probarlo con su propia carpeta de Google Drive y avíseme si funciona rápido o no.

ACTUALIZA Por cierto, si simplemente copio esta función (y la ejecuto):

function coby2() {
    var startTime = Date.now();
    const drive_url = "https://www.googleapis.com/drive/v3/files?q=%27{my file id}%27+in+parents&key={myAPIkey}";
    let drive_request = {
        method: "GET",
        /*headers: new Headers({
            Authorization: "Bearer "+access_token
        })*/
    }
    fetch(drive_url, drive_request).then( response => {
        var txt = response.json();
        console.log(response, txt);
        return(txt);
    }).then( list =>  {
        var endTime = Date.now();
        console.log("Found files:",list.files, " with time total: ", (endTime - startTime));
    });
}

mi tiempo de respuesta es de aproximadamente 150-300 ms, y si copio exactamente la misma función en Node.js y la llamo en la función de solicitud / respuesta (en la función http.createServer), la respuesta sigue siendo de aproximadamente 4000 ms en promedio. Creo que es algo con el módulo node-fetch.

Respuestas a la pregunta(0)

Su respuesta a la pregunta