You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在TypeScript中构造含指定参数的Google Spreadsheets API响应

实现方案

第一步:定义TS类型

先定义请求参数、Google接口原始返回、以及扩展后响应结构的类型约束:

// Google Drive files.get 接口请求参数类型
interface DriveFileGetParams {
  fileId: string;
  supportsAllDrives: boolean;
  fields: string;
}

// Google接口返回的原始文件数据类型(对应你指定的fields字段)
interface RawDriveFile {
  id: string;
  name: string;
  modifiedTime: string;
}

// 扩展后的响应类型,同时包含传入的请求参数和接口返回数据
interface DriveFileResponse {
  // 你需要保留的入参字段
  requestParams: Pick<DriveFileGetParams, 'fileId' | 'supportsAllDrives'>;
  // Google接口返回的原始文件数据
  fileData: RawDriveFile;
  // 可按需新增其他字段,比如请求状态码
  status: number;
}

第二步:封装请求方法

以常用的axios库为例实现,也可以替换成fetch或者其他HTTP客户端:

import axios from 'axios';

// 封装获取Google Drive文件元数据的方法
async function getSpreadsheetMeta(params: DriveFileGetParams): Promise<DriveFileResponse> {
  const { fileId, supportsAllDrives, fields } = params;
  try {
    const response = await axios.get<RawDriveFile>(
      `https://www.googleapis.com/drive/v3/files/${fileId}`,
      {
        params: {
          supportsAllDrives,
          fields
        },
        // 这里替换为你自己的Google API授权头
        headers: {
          Authorization: `Bearer ${YOUR_ACCESS_TOKEN}`
        }
      }
    );

    // 构造目标响应结构,包含你需要的入参字段
    return {
      requestParams: {
        fileId,
        supportsAllDrives
      },
      fileData: response.data,
      status: response.status
    };
  } catch (error) {
    console.error('请求Google Drive接口失败', error);
    throw error;
  }
}

第三步:调用示例

async function main() {
  const result = await getSpreadsheetMeta({
    fileId: '替换为你的Spreadsheet对应的ID',
    supportsAllDrives: true,
    fields: 'id,name,modifiedTime'
  });

  console.log('传入的fileId:', result.requestParams.fileId);
  console.log('传入的supportsAllDrives:', result.requestParams.supportsAllDrives);
  console.log('接口返回的文件数据:', result.fileData);
}

内容的提问来源于stack exchange,提问作者print

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 15:09:03