如何使用:SharePoint 操作(预览)

使用 Power Apps SDK 将代码应用连接到 SharePoint,并使用生成的模型和服务在 SharePoint 列表中执行 CRUD(创建、读取、更新、删除)作。

先决条件

支持的方案

使用 Power Apps SDK 连接到 SharePoint 时支持以下方案:

  • 使用 PAC CLI 将 SharePoint 列表添加为数据源
  • 对 SharePoint 列表执行 CRUD 操作
  • 获取选择、查找或人员/组列的可能值

设置您的代码应用程序

在代码应用中执行创建、读取、更新和删除(CRUD)作之前,请完成这些设置步骤。

确保在数据调用之前初始化 Power Apps SDK

在您的 App.tsx 文件中实现逻辑,以确保在执行任何数据操作之前等待 Power Apps SDK 完全初始化。 此方法可防止由未初始化的服务或缺少上下文导致的错误。

在进行 API 调用之前,使用异步函数或状态管理来确认初始化。 例如:

useEffect(() => { 
// Define an async function to initialize the Power Apps SDK 
const init = async () => { 
      try { 
            await initialize(); // Wait for SDK initialization 
            setIsInitialized(true); // Mark the app as ready for data operations 
      } catch (err) { 
            setError('Failed to initialize Power Apps SDK'); // Handle initialization errors 
            setLoading(false); // Stop any loading indicators 
      } 
};

init(); // Call the initialization function when the component mounts 
}, []); 
 
useEffect(() => { 
// Prevent data operations until the SDK is fully initialized 
if (!isInitialized) return; 
 
// Place your data reading logic here 
}, []); 

添加 SharePoint 数据源

按照 “连接到数据”中的说明添加 SharePoint 数据源。

导入所需的类型和服务

添加数据源时,会自动生成模型和服务文件并将其放置在 /generated/services/ 文件夹中。 例如,如果添加 ChoicesTest1 列表,将创建以下文件:

  • ChoicesTest1Model.ts – 定义 ChoicesTest1 列表的数据模型。
  • ChoicesTest1Service.ts – 提供用于与 ChoicesTest1 列表中的数据交互的服务方法。

可以在 App.tsx 代码中导入和使用这些文件,如下所示:

import { ChoicesTest1Service } from './generated/services/ChoicesTest1Service'; 
import type { ChoicesTest1 } from './generated/models/ChoicesTest1Model'; 

读取记录

此示例提取所有项并设置状态。

const loadRecords = async () => { 
  try { 
    const result = await ChoicesTest1Service.getAll(); 
    if (result.data) { 
      setRecords(result.data); // result.data is T[] 
    } else { 
      // handle empty or error 
    } 
  } catch (err) { 
    // handle error 
  } 
}; 

此示例读取单个记录。

const fetchOne = async (id: string) => { 
  const r = await ChoicesTest1Service.get(id); 
  if (r.data) { 
    // r.data is a single record typed as ChoicesTest1 
  } 
}; 

创建记录

对于以下步骤中的示例,模型文件中的示例类型为ChoicesTest1Choices1ValuepersonValuelookupValue

  1. 将所选 ID 映射到展开的对象

注释

生成的模型可能包含用于表单绑定的内部属性名称 # (例如: Choices1#Id),但不应包含在发送到 SharePoint 连接器的有效负载中。 在列表中更新或创建行时,SharePoint API 需要为引用列(作者、编辑器、人员/组列等)提供扩展对象,而不仅仅是 ID。 有关详细信息,请参阅 SharePoint API 文档

const choices1Obj = selectedChoices1Id 
? choices1Options.find(c => c.Id === selectedChoices1Id) 
: undefined; 
const personObj = selectedPersonClaims 
? personOptions.find(p => p.Claims === selectedPersonClaims) 
: undefined; 
const lookupObj = selectedLookupId 
? lookupOptions.find(l => l.Id === selectedLookupId) 
: undefined; 
  1. 构建有效负载并创建

请务必省略包含 #的属性,包括用于选择、查找和人员的扩展对象,并在必要时添加内容类型信息。 使用生成的模型类型来帮助生成有效负载。

// Content type (example static sample; retrieve dynamically if needed) 
const contentTypeId = "0x0100..."; // replace with your content type id 

const payload = { 
Title: titleValue, 
Choices1: choices1Obj, 
Choices2: choices2Obj, 
Choices3: choices3Obj, 
person: personObj, 
yesno: yesnoBoolean, 
lookup: lookupObj,
"{ContentType}": { 
   "@odata.type": "#Microsoft.Azure.Connectors.SharePoint.SPListExpandedContentType",
   Id: contentTypeId, 
   Name: "Item" 
} 
} as Partial<Omit<ChoicesTest1, "ID">>; 

// create 
const created = await ChoicesTest1Service.create(payload as Omit<ChoicesTest1, "ID">); 
if (created.data) { 
// success 
} 

更新记录

请使用生成的服务文件中的 update(id, payload)。 提供与创建记录时相同的扩展对象。

例如:

const updatePayload = { 
  Title: updatedTitle, 
  Choices1: updatedChoices1Obj, 
  // ... 
} as Partial<Omit<ChoicesTest1, "ID">>; 

await ChoicesTest1Service.update(recordId, updatePayload); 

删除记录

确保 recordId 是服务预期的字符串 ID。 这通常是转换为字符串的数字项 ID。

await ChoicesTest1Service.delete(recordId); 

引用的实体(选项/查找/人员)

若要填充下拉列表,请调用 getReferencedEntity()。 SharePoint 始终返回一个值数组,其中包含引用实体中的对象。 你可能希望规范化响应,因为某些连接器以格式 { value: [] }返回结构,而另一些连接器则直接提供数组。

// The first parameter is a search term, the second is the referenced entity name 
const res = await ChoicesTest1Service.getReferencedEntity("", "Choices1"); 
// normalize: 
const dataArray = (res.data as { value?: any[] })?.value || res.data; 
const options = Array.isArray(dataArray) ? dataArray : []; 
// map to select options: 
const selectOpts = options.map(o => ({ id: o.Id, label: o.Value })); 

不支持的方案

Power Apps SDK 和 PAC CLI 允许对 SharePoint 列表执行 CRUD 操作,但不支持文档处理 API 或像项同步或权限更改这样的操作。 可以通过为代码应用创建自定义服务文件来添加这些功能。