0

Google Apps-script API を利用して、事前に作成された Google Apps スクリプトを実行しようとしています。残念ながら、すべてのサンプル ドキュメントが Angular 用に作成されているわけではありませんが、node.js は類似しており、Angular でやり直そうとしています。このエラーが発生し続け、API 関数 script.run に必要なパラメーターを与えているように見えるため、ここで何が問題なのか理解できません。

私が得ている完全なエラーは

node_modules/google-auth-library/build/src/auth/oauth2client.d.ts(298,55) のエラー: エラー TS1039: 初期化子は >ambient コンテキストでは許可されていません。src/app/app.component.ts(98,3): エラー TS2345: タイプ '{ auth: >any; の引数。リソース: { 関数: 文字列; }; scriptId: 文字列; }' は、タイプ 'Params$Resource$Scripts$Run' のパラメーターに >代入できません。オブジェクト リテラルは既知のプロパティのみを指定でき、'resource' はタイプ 'Params$Resource$Scripts$Run' に >存在しません。

リソースのタイプ {function : string } を変更してみて、それが役立つかどうかを確認しましたが、役に立ちませんでした。ここのドキュメント: https://developers.google.com/apps-script/api/reference/rest/v1/scripts/run

これらが必要なパラメータであることを暗示しているようです。

app.component.ts のコードは次のとおりです。

import { Component } from '@angular/core';
var file = require('file-system');
var fs = require('fs');
//import { readFile } from 'fs';
const readline = require('readline');
//const {google} = require('googleapis');
import { google } from "googleapis";



@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  // If modifying these scopes, delete token.json.
  SCOPES = ['https://www.googleapis.com/auth/script.projects'];
  // 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.
  TOKEN_PATH = 'token.json';  

constructor() {


// Load client secrets from a local file.
fs.readFile('credentials.json', (err, content) => {
  if (err) return console.log('Error loading client secret file:', err);
  // Authorize a client with credentials, then call the Google Apps Script API.
  this.authorize(JSON.parse(content), this.callAppsScript);
});
}

/**
 * Create an OAuth2 client with the given credentials, and then execute the
 * given callback function.
 * @param {Object} credentials The authorization client credentials.
 * @param {function} callback The callback to call with the authorized client.
 */
 authorize(credentials, callback) {
  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.
  fs.readFile(this.TOKEN_PATH, (err, token) => {
    if (err) return this.getAccessToken(oAuth2Client, callback);
    oAuth2Client.setCredentials(JSON.parse(token));
    callback(oAuth2Client);
  });
}

/**
 * Get and store new token after prompting for user authorization, and then
 * execute the given callback with the authorized OAuth2 client.
 * @param {google.auth.OAuth2} oAuth2Client The OAuth2 client to get token for.
 * @param {getEventsCallback} callback The callback for the authorized client.
 */
 getAccessToken(oAuth2Client, callback) {
  const authUrl = oAuth2Client.generateAuthUrl({
    access_type: 'offline',
    scope: this.SCOPES,
  });
  console.log('Authorize this app by visiting this url:', authUrl);
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
  });
  rl.question('Enter the code from that page here: ', (code) => {
    rl.close();
    oAuth2Client.getToken(code, (err, token) => {
      if (err) return console.error('Error retrieving access token', err);
      oAuth2Client.setCredentials(token);
      // Store the token to disk for later program executions
      fs.writeFile(this.TOKEN_PATH, JSON.stringify(token), (err) => {
        if (err) return console.error(err);
        console.log('Token stored to', this.TOKEN_PATH);
      });
      callback(oAuth2Client);
    });
  });
}

/**
 * Creates a new script project, upload a file, and log the script's URL.
 * @param {google.auth.OAuth2} auth An authorized OAuth2 client.
 */
 callAppsScript(auth) {
 // eslint-disable-line no-unused-vars
    const scriptId = 'MQjfx_a74LdckdFiqPexPXbj574JS7smg';
    const script = google.script('v1');


// Make the API request. The request object is included here as 'resource'.
script.scripts.run({
  auth: auth,
  resource: {
    function: 'myFunction',
  },
  scriptId: scriptId,
}, function(err, resp) {
  if (err) {
    // The API encountered a problem before the script started executing.
    console.log('The API returned an error: ' + err);
    return;
  }
  if (resp.error) {
    // The API executed, but the script returned an error.

    // Extract the first (and only) set of error details. The values of this
    // object are the script's 'errorMessage' and 'errorType', and an array
    // of stack trace elements.
    const error = resp.error.details[0];
    console.log('Script error message: ' + error.errorMessage);
    console.log('Script error stacktrace:');

    if (error.scriptStackTraceElements) {
      // There may not be a stacktrace if the script didn't start executing.
      for (let i = 0; i < error.scriptStackTraceElements.length; i++) {
        const trace = error.scriptStackTraceElements[i];
        console.log('\t%s: %s', trace.function, trace.lineNumber);
      }
    }
  } else {
    // The structure of the result will depend upon what the Apps Script
    // function returns. Here, the function returns an Apps Script Object
    // with String keys and values, and so the result is treated as a
    // Node.js object (folderSet).
    const folderSet = resp.response.result;
    if (Object.keys(folderSet).length == 0) {
      console.log('No folders returned!');
    } else {
      console.log('Folders under your root folder:');
      Object.keys(folderSet).forEach(function(id) {
        console.log('\t%s (%s)', folderSet[id], id);
      });
    }
  }
});
}
}

期待される結果は、呼び出されて実行される関数である必要があります。代わりに、次のエラーが表示されます。

ERROR in node_modules/google-auth-library/build/src/auth/oauth2client.d.ts(298,55): error TS1039: Initializers are not allowed in ambient contexts.
src/app/app.component.ts(98,3): error TS2345: Argument of type '{ auth: any; resource: { function: string; }; scriptId: string; }' is not assignable to parameter of type 'Params$Resource$Scripts$Run'.
  Object literal may only specify known properties, and 'resource' does not exist in type 'Params$Resource$Scripts$Run'.
4

0 に答える 0