google-apps-scriptgoogle-drive-apigoogle-docs-apibatch-request

error while send batchRequests for batchUpdate in google docs with google app script


I am trying to create a copy of Google doc file and replace the text in it using the methods batchRequest, batchUpdate, replaceAllText

As a library, I use the library tanaike batchRequests from github

I can create copies, but when I try to replace the text I get an error 404

Here's my code:

/**
 * переменная LIST получает данные с листа с названием 1 которые содержаться в 1 и 2 колонке
 * номер и фио
 */

const LIST = SpreadsheetApp.getActiveSpreadsheet()
  .getSheetByName('1')
  .getDataRange()
  .getValues()
  .filter(f => f[0] != "")
  .map(f => [f[0], f[1]]);

function Creator() {
  var requests = LIST.map(([b1, a2], i) => {
    return {
      method: "POST",
      endpoint: `https://www.googleapis.com/drive/v3/files/1IzwefpoJOksTyBo0CaGcsaG9L_jrZW6Vuw4lGqC07_Y/copy`,
      requestBody: {
        parents: ["1qI-T2m1sL_I69wc7EAOJr3ZK3233X5qX"], name: `Договор № ${b1} с ${a2}`} // заполните здесь название которое вам нужно что бы получилось
    }
  });
  var res = BatchRequest.EDo({
    batchPath: "batch/drive/v3",
    requests: requests,
  });
  console.log(res);
  batchUpdate(res);
}

function batchUpdate(res) {
  var IDS = res.map((item) => {
    return item.id;
  });
  var requests = support_lib.concatArrays(LIST,IDS).map(([num, name, id]) => {
    return {
      method: "POST",
      endpoint: `https://docs.googleapis.com/v1/documents/${id}:batchUpdate`,
      requestBody: {
        replaceAllText:
        {
          replaceText: num, containsText: { text: "<номер>", matchCase: true },
          replaceText: name, containsText: { text: "<фио>", matchCase: true }
        }
      }
    }
  });
  var response = BatchRequest.EDo({
    batchPath: "batch/drive/v3",
    requests: requests,
  });
  console.log(JSON.stringify(response, null, 2));
}

response:

17:08:00    Информация  [ { kind: 'drive#file',
    id: '1d11ss2B9tjQ_ZUZU6i58DdjT0pGzYcDDHs04BWkSirs',
    name: 'Договор № 1 с Кожевников Антон Юрьевич',
    mimeType: 'application/vnd.google-apps.document' },
  { kind: 'drive#file',
    id: '1499DdvTuFzjSFFz8Fi-q9-_MSRUAGfVa36Nc9l1GQm0',
    name: 'Договор № 2 с Кожевникова Любвоь Алексеевна',
    mimeType: 'application/vnd.google-apps.document' } ]
17:08:00    Информация  [
  {
    "error": {
      "code": 404,
      "message": "URL path: /v1/documents/1d11ss2B9tjQ_ZUZU6i58DdjT0pGzYcDDHs04BWkSirs:batchUpdate could not be resolved. Maybe there is an error parsing the batch item.",
      "errors": [
        {
          "message": "URL path: /v1/documents/1d11ss2B9tjQ_ZUZU6i58DdjT0pGzYcDDHs04BWkSirs:batchUpdate could not be resolved. Maybe there is an error parsing the batch item.",
          "domain": "global",
          "reason": "notFound"
        }
      ],
      "status": "NOT_FOUND"
    }
  },
  {
    "error": {
      "code": 404,
      "message": "URL path: /v1/documents/1499DdvTuFzjSFFz8Fi-q9-_MSRUAGfVa36Nc9l1GQm0:batchUpdate could not be resolved. Maybe there is an error parsing the batch item.",
      "errors": [
        {
          "message": "URL path: /v1/documents/1499DdvTuFzjSFFz8Fi-q9-_MSRUAGfVa36Nc9l1GQm0:batchUpdate could not be resolved. Maybe there is an error parsing the batch item.",
          "domain": "global",
          "reason": "notFound"
        }
      ],
      "status": "NOT_FOUND"
    }
  }
]

Solution

  • Modification points:

    Although I'm not sure about support_lib.concatArrays(LIST,IDS), when it is supposed that support_lib.concatArrays(LIST,IDS) returns valid values, how about the following modification?

    In this modification, the function batchUpdate(res) is modified.

    Modified script:

    This script uses Google Docs API. So, please enable Google Docs API at Advanced Google services.

    function batchUpdate(res) {
      var IDS = res.map((item) => {
        return item.id;
      });
      support_lib.concatArrays(LIST, IDS).forEach(([num, name, id]) => {
        const requests = [
          { replaceAllText: { replaceText: num, containsText: { text: "<номер>", matchCase: false } } },
          { replaceAllText: { replaceText: name, containsText: { text: "<фио>", matchCase: false } } }
        ];
        const res = Docs.Documents.batchUpdate({ requests }, id);
        console.log(res);
        
        // Utilities.sleep(5000); // If there are a lot of IDs, this might be required to be used by adjusting the wait time.
      });
    }
    

    References: