如何通过 Apps Script & 创建新的脚本文件驱动 SDK [英] How to create a new script file via Apps Script & Drive SDK

查看:23
本文介绍了如何通过 Apps Script & 创建新的脚本文件驱动 SDK的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试通过在 Apps 脚本中调用 Drive SDK 的文件创建一个新项目.

Trying to create a new project with files with a call to the Drive SDK within Apps Script.

以下内容在 UrlFetchApp 请求中的确切位置...

Where exactly would the following go in a UrlFetchApp request...

{
  "files": [
    {
      "id":"9basdfbd-749a-4as9b-b9d1-d64basdf803",
      "name":"Code",
      "type":"server_js",
      "source":"function doGet() {\n  return HtmlService.createHtmlOutputFromFile(\u0027index\u0027);\n}\n"
    },
    {
      "id":"3asf7c0d-1afb-4a9-8431-5asdfc79e7ae",
      "name":"index",
      "type":"html",
      "source":"\u003chtml\u003e\n  \u003cbody\u003e\n    New message!!\n  \u003c/body\u003e\n\u003c/html\u003e"
    }
  ]
}

它来自导入/导出文档示例视频 Dan 提到这些调用是针对 Apps 脚本之外的语言的,但要求提供脚本文件类型列表和这些文件一旦使用Eric的库进行授权设置,就可以使用.

It's from the import/export docs and in the example video Dan mentions the calls are for languages outside of Apps Script but requesting a list of script file types and the content of those files does work once the authorization is setup with Eric's oAuth2 library.

我最近的猜测...

function createProject( ) {
  var token = getDriveService().getAccessToken(); // from Eric's oAuth2 lib

  var url = 'https://www.googleapis.com/upload/drive/v2/files?convert=true';

  // Where does this go?
  var files = {
    "files": [
      {
        "name":"Code",
        "type":"server_js",
        "source":"function doGet() {\n  return HtmlService.createHtmlOutputFromFile(\u0027index\u0027);\n}\n"
      },
      {
        "name":"index",
        "type":"html",
        "source":"\u003chtml\u003e\n  \u003cbody\u003e\n    Hello, world!!\n  \u003c/body\u003e\n\u003c/html\u003e"
      }
    ]
  };

  // Where does this go too?
  var metadata = {
    'title': 'script-test1',
    'mimeType': 'application/vnd.google-apps.script',
    "parents": [
      {
        "id": "0B2VkNbQMTnaCODBRVjZQcXBXckU"
      }
    ],
  };

  var options = {
    'headers' : {
      'Authorization': 'Bearer ' +  token,
      'Content-Type': 'application/vnd.google-apps.script+json',
    },
    'method' : 'POST',
    'payload' : files  // probably not right

  };

  var response = UrlFetchApp.fetch(url, options);
  Logger.log(response.getResponseCode());

}

会创建未知类型的无标题​​ Drive 文件,并将有效负载插入其中,但不会转换为脚本文件类型.

An untitled Drive file of unknown type does get created and the payload does get inserted into it, but it's not converted to a script file type.

走另一条路线,只是使用...

Going another route and just using...

var file = {
    "title": "Test script",
    "mimeType": "application/vnd.google-apps.script",
    "parents": [
      {
        "id": "[INSERT FOLDER ID HERE]"
      }
    ]
  };

Drive.Files.insert(file);

...引发内部错误.

还了解具有客户端的 Drive insert 文档-JS 端示例,但不知道应该将其中的多少翻译(如果可能)到服务器端 Apps 脚本.

Also aware of the Drive insert docs that have a client-side JS example, but don't know how much of it should be translated over (if possible) to server-side Apps Script.

推荐答案

大功告成,但还有一些错误.您的第一种方法(使用 UrlFetch)在 options 变量中有一些错误.这是一个 doGet() 函数,它(在验证授权后)创建一个新的 Apps 脚本项目并将 UrlFetch 响应写入页面:

You're almost there, but you have a few mistakes. Your first approach (using UrlFetch) has some errors in the options variable. Here's a doGet() function that (after verifying authorization) creates a new Apps Script Project and writes the UrlFetch response to the page:

function doGet() {
  var driveService = getDriveService();
  if (!driveService.hasAccess()) {
    var authorizationUrl = driveService.getAuthorizationUrl();
    var template = HtmlService.createTemplate(
        '<a href="<?= authorizationUrl ?>" target="_blank">Authorize</a>. ' +
        'Refresh the page when authorization complete.');
    template.authorizationUrl = authorizationUrl;
    var page = template.evaluate();
    return page;
  } else {     
    var url = "https://www.googleapis.com/upload/drive/v2/files?convert=true";   
    var requestBody =  {
      "files": [
        {
          "name":"Code",
          "type":"server_js",
          "source":"function doGet() {\n  return HtmlService.createHtmlOutputFromFile(\u0027index\u0027);\n}\n"
        },
        {
          "name":"index",
          "type":"html",
         "source":"\u003chtml\u003e\n  \u003cbody\u003e\n    Created with Apps Script.\n  \u003c/body\u003e\n\u003c/html\u003e"
        }
      ]
    };

    var options = {
      "headers": {
         'Authorization': 'Bearer ' +  driveService.getAccessToken(),
       }, 
      "contentType": "application/vnd.google-apps.script+json",
      "method" : "post",
      "payload": JSON.stringify(requestBody)
    }

    var response = UrlFetchApp.fetch(url, options);
    return HtmlService.createHtmlOutput(response.getContentText());
  }
}

此代码会在根云端硬盘文件夹中创建一个名为Untitled"的 Apps 脚本项目文件.options 对象应指定 POST 作为创建项目的方法(默认为 GET),payload 需要从 JSON 对象转换为字符串以供 UrlFetch.

This code creates an Apps Script project file called "Untitled" in the root Drive folder. The options object should specify POST as the method for creating projects (default is GET), and the payload needs to be converted to a string from a JSON object to be understood by UrlFetch.

或者,您可以使用 Apps 脚本中的高级驱动器服务代替 UrlFetch 来执行相同的操作.以下代码创建相同的 Apps 脚本项目(但将其放在指定的文件夹中并将文件命名为测试脚本"):

Alternatively, you can do the same thing by using the Advanced Drive Service in Apps Script instead of UrlFetch. The following code creates the same Apps Script project (but places it in the specified folder and names the file 'Test script'):

function createGoogleFileInFolder3() {  
    var requestBody =  {
      "files": [
        {
          "name":"Code",
          "type":"server_js",
          "source":"function doGet() {\n  return HtmlService.createHtmlOutputFromFile(\u0027index\u0027);\n}\n"
        },
        {
          "name":"index",
          "type":"html",
          "source":"\u003chtml\u003e\n  \u003cbody\u003e\n    Created with Apps Script.\n  \u003c/body\u003e\n\u003c/html\u003e"
        }
      ]
    };

  var resource = {
    "title": "Test script",
    "parents": [
      {
        "id": "<parent folder id here>"
      }
    ]
  };

  var blob = Utilities.newBlob(JSON.stringify(requestBody), "application/vnd.google-apps.script+json");

  Drive.Files.insert(resource, blob, {"convert":"true"});
}

这篇关于如何通过 Apps Script &amp; 创建新的脚本文件驱动 SDK的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆