目前,此任务在应用制作工具中并非微不足道,而且非常通用。我们可以将问题措辞更改为CRUD operations with 3rd party datasources。让我们把它分解成更小的部分并分别解决它们。
读取/列出联系人
这项任务相对容易。您需要使用Calculated Model 代理Apps Scripts Contacts API 响应。一旦您使用来自Contact 响应的字段子集创建模型,您就可以为模型创建数据源并将其绑定到列表或表格小部件。您也可以尝试在Calculated Model Sample 中寻找灵感。
// Server side script
function getContacts_() {
var contacts = ContactsApp.getContacts();
var records = contacts.map(function(contact) {
var record = app.models.Contact.newRecord();
record.FirstName = contact.getGivenName();
record.LastName = contact.getFamilyName();
var companies = contact.getCompanies();
if (companies.length > 0) {
var company = companies[0];
record.Organization = company.getCompanyName();
record.Title = company.getJobTitle();
}
var emails = contact.getEmails();
if (emails.length > 0) {
record.Email = emails[0].getAddress();
}
var phones = contact.getPhones();
if (phones.length > 0) {
record.Phone = phones[0].getPhoneNumber();
}
return record;
});
return records;
}
创建/更新/删除
由于计算模型有一些limitations,我们需要发挥想象力从它们的数据源中创建、更新和删除记录。 CUD 操作的基本策略将是calling server side scripts,以响应客户端的用户操作。要从 UI 获取用户输入,我们需要利用页面的 Custom Properties,每个联系人字段的一个属性:
这里有一些可以解释这个想法的sn-ps
创建
// Client script
function onSubmitContactClick(submitButton) {
var props = submitButton.root.properties;
var contact = {
FirstName: props.FirstName,
LastName: props.LastName,
Organization: props.Organization,
...
};
google.script.run
.withSuccessHandler(function() {
// Most likely we'll need to navigate user back to the
// page with contacts list and reload its datasource
// to reflect recent changes, because our `CUD` operations
// are fully detached from the list datasource
app.showPage(app.pages.Contacts);
app.datasources.Contacts.load();
})
.withFailureHandler(function() {
// TODO: Handle error
})
.createContact(contact);
}
// Server script
function createContact(contactDraft) {
var contact = ContactsApp.createContact(contactDraft.FirsName,
contactDraft.LastName,
contactDraft.Email);
contact.addCompany(contactDraft.Organization, contactDraft.Title);
contact.addPhone(ContactsApp.Field.WORK_PHONE, contactDraft.Phone);
}
更新
更新联系人记录的想法将与新的联系人创建流程非常相似,所以我现在跳过它。
删除
假设删除按钮位于联系人表格行内。
// Client script
function onDeleteContactClick(deleteButton) {
var email = deleteButton.datasource.item.Email;
google.script.run
.withSuccessHandler(function() {
// To update contacts list we can either reload the entire
// datasource or explicitly remove deleted item on the client.
// Second option will work way faster.
var contactIndex = deleteButton.parent.childIndex;
app.datasources.Contacts.items.splice(contactIndex, 1);
})
.withFailureHandler(function() {
// TODO: Handle error
})
.deleteContact(contact);
}
// Server script
function deleteContact(email) {
var contact = ContactsApp.getContact(email);
ContactsApp.deleteContact(contact);
}