Edits history of script submission #23311 for ' Create Document from Template (gdocs)'

  • bunnative
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    
    /**
     * Create Document from Template
     * Copy a template Google Doc and replace each `{{key}}` placeholder (in every tab) with the matching value from `variables`, e.g. `{"name": "Ada"}` fills `{{name}}`. Placeholders are matched case-sensitively; unmatched ones are left as-is. Requires the drive scope on the connection (to copy a template the app didn't create), in addition to documents.
     */
    export async function main(
      auth: RT.Gdocs,
      template_id: string,
      title: string,
      variables: { [key: string]: any },
      folder_id: string | undefined
    ) {
      const copy = await fetch(
        `https://www.googleapis.com/drive/v3/files/${template_id}/copy?supportsAllDrives=true`,
        {
          method: "POST",
          headers: {
            Authorization: `Bearer ${auth.token}`,
            "Content-Type": "application/json",
            Accept: "application/json",
          },
          body: JSON.stringify({
            name: title,
            parents: folder_id ? [folder_id] : undefined,
          }),
        }
      )
      if (!copy.ok) {
        throw new Error(`${copy.status} ${await copy.text()}`)
      }
      const { id: document_id } = (await copy.json()) as { id: string }
    
      const requests = Object.entries(variables ?? {}).map(([key, value]) => ({
        replaceAllText: {
          containsText: { text: `{{${key}}}`, matchCase: true },
          replaceText: String(value ?? ""),
        },
      }))
      let replies: any[] = []
      if (requests.length) {
        const response = await fetch(
          `https://docs.googleapis.com/v1/documents/${document_id}:batchUpdate`,
          {
            method: "POST",
            headers: {
              Authorization: `Bearer ${auth.token}`,
              "Content-Type": "application/json",
              Accept: "application/json",
            },
            body: JSON.stringify({ requests }),
          }
        )
        if (!response.ok) {
          throw new Error(`${response.status} ${await response.text()}`)
        }
        replies = (await response.json()).replies ?? []
      }
    
      return {
        document_id,
        title,
        url: `https://docs.google.com/document/d/${document_id}/edit`,
        occurrences_changed: Object.fromEntries(
          Object.keys(variables ?? {}).map((k, i) => [
            k,
            replies[i]?.replaceAllText?.occurrencesChanged ?? 0,
          ])
        ),
      }
    }
    

    Submitted by hugo989 6 hours ago