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

Node环境(无React)下使用Apollo实现批量更新的示例求助

没问题!我来给你一个纯Node.js环境下用Apollo Client执行批量更新的示例,和你熟悉的React快速入门里的功能对齐,完全不需要React依赖。

使用Apollo Client在Node.js中执行批量更新

1. 安装必要依赖

首先在项目里安装Apollo Client核心包、GraphQL支持包,以及Node环境需要的fetch实现:

npm install @apollo/client graphql node-fetch

2. 编写批量更新脚本(myscript.js)

下面是完整的脚本代码,每部分都做了注释,和你React环境里的逻辑保持一致:

// 导入Apollo Client核心模块和Node环境的fetch
const { ApolloClient, InMemoryCache, gql } = require('@apollo/client');
const fetch = require('node-fetch');

// 创建Apollo Client实例,配置和React环境完全一致
const client = new ApolloClient({
  uri: '你的GraphQL服务器地址', // 替换成你实际的后端地址
  cache: new InMemoryCache(), // 本地缓存,和React里的缓存逻辑相同
  fetch: fetch, // 给Node环境提供HTTP请求能力
});

// 定义更新用的Mutation,和你React组件里用的保持一致
const UPDATE_ITEM_MUTATION = gql`
  mutation UpdateItem($id: ID!, $newValue: String!) {
    updateItem(id: $id, newValue: $newValue) {
      id
      newValue
    }
  }
`;

// 批量更新核心函数
async function batchUpdateItems(itemsToUpdate) {
  try {
    // 用Promise.all并行处理所有更新请求(如果后端支持批量Mutation,也可以改成单请求发送)
    const updateResults = await Promise.all(
      itemsToUpdate.map(item => 
        client.mutate({
          mutation: UPDATE_ITEM_MUTATION,
          variables: {
            id: item.id,
            newValue: item.newValue
          },
          // 可选:如果需要更新本地缓存(和React里的cache更新逻辑一致)
          update(cache, { data: { updateItem } }) {
            // 示例:假设你有一个查询单个Item的Query,这里同步更新缓存
            const existingItem = cache.readQuery({
              query: gql`
                query GetItem($id: ID!) {
                  item(id: $id) {
                    id
                    newValue
                  }
                }
              `,
              variables: { id: updateItem.id }
            });

            if (existingItem) {
              cache.writeQuery({
                query: gql`
                  query GetItem($id: ID!) {
                    item(id: $id) {
                      id
                      newValue
                    }
                  }
                `,
                variables: { id: updateItem.id },
                data: { item: updateItem }
              });
            }
          }
        })
      )
    );

    console.log('✅ 批量更新完成!所有结果:', updateResults);
  } catch (error) {
    console.error('❌ 批量更新失败:', error.message);
  }
}

// 示例:要更新的条目列表,替换成你实际的数据
const itemsToUpdate = [
  { id: 'item_1', newValue: '更新后的内容1' },
  { id: 'item_2', newValue: '更新后的内容2' },
  { id: 'item_3', newValue: '更新后的内容3' }
];

// 执行批量更新
batchUpdateItems(itemsToUpdate);

3. 运行脚本

在终端里执行以下命令就能启动批量更新:

node myscript.js

额外优化:如果后端支持批量Mutation

如果你的GraphQL后端提供了批量更新的接口(比如一个batchUpdateItems字段),可以改成单请求发送所有更新,效率更高:

// 定义批量Mutation(需后端支持)
const BATCH_UPDATE_MUTATION = gql`
  mutation BatchUpdateItems($updates: [ItemUpdateInput!]!) {
    batchUpdateItems(updates: $updates) {
      id
      newValue
    }
  }
`;

async function batchUpdateWithSingleRequest(itemsToUpdate) {
  try {
    const result = await client.mutate({
      mutation: BATCH_UPDATE_MUTATION,
      variables: { updates: itemsToUpdate }
    });
    console.log('✅ 单请求批量更新完成!结果:', result.data.batchUpdateItems);
  } catch (error) {
    console.error('❌ 批量更新失败:', error.message);
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 16:08:15