如何在Google Apps Script中为新创建的空白自定义Schema字段赋值?
Google Apps Script 无法为未赋值的自定义Schema字段添加值
我正尝试用Google Apps Script给customSchema里的自定义字段赋值,但不管是通过Google Admin Console(GAC)还是Apps Script创建customSchema,都会碰到同一个问题:在GAC手动填入值之前,Admin SDK无法通过Apps Script识别到该customSchema。
初始代码
function updateCustomSchemaData(userEmail, schemaName, fieldName, newValue) { // userEmail = 'user@email.com' // schemaName = 'User_Information' // fieldName = 'Site_Code' // newValue = 'test' try { var user = AdminDirectory.Users.get(userEmail); var schemaData = user.customSchemas[schemaName]; schemaData[fieldName] = newValue; AdminDirectory.Users.update(user, userEmail); } catch (error) { Logger.log("Error updating custom schema data: " + error); } }
问题现象
我已通过GAC确认运行updateCustomSchemaData前该字段已存在,但执行代码时会抛出错误:
Error updating custom schema data: TypeError: Cannot read properties of undefined (reading 'User_Information')
查看user对象的输出,其中完全没有customSchema相关内容。但如果在GAC中手动编辑该字段并为customSchema添加值后,var user = AdminDirectory.Users.get(userEmail);的结果里就会包含该customSchema:
"customSchemas": { "User_Information": { "Site_Code": "This is a test" } },
确认Schema存在的依据
我能确定该schema确实存在,因为我有一个独立函数(使用AdminDirectory.schemas.insert)用于创建不存在的schema,只要该schema已在GAC中存在,哪怕user对象里没有它,执行创建函数时就会报错:
Failed addSchema with error API call to directory.schemas.insert failed with error: Entity Already Exists: resource.schemaName
简言之,新创建的空白customSchema字段无法被AdminDirectory.Users.get识别,且AdminDirectory.Users.update无法为该字段赋值,求解决方法。
更新1
修改后的代码不再报错,但仍无法为Site Code添加值:
function updateUser() { // update individual user, given email, to make Site Code match buildingId const user1Email = "user1@email.org"; //const user2Email = 'user2@email.org'; try { var user = getUser(user1Email); var userId = user.customerId const myFunction = () => { AdminDirectory.Users.update({ "customSchemas": { "User_Information": { "Site_Code": "This is a test" } } }, user1Email); myFunction(); } var user = getUser(user1Email); } catch (err) { console.log('Failed with error %s', err.message); } }
内容的提问来源于stack exchange,提问作者Kyle K.
相关产品推荐
相关产品推荐

