如何在用户保存/提交时添加/更新工件字段



在ApostropheCMS应用程序中,我们有一个工件类型"书";。前端用户可以从CMS更新工件的index.js中声明的字段。

一旦用户保存,我们需要动态添加或更新一个字段,即citations字段。我们使用Citation.js根据编辑在CMS中输入的内容生成MLA、Chicago等引文。

我们不想让这个字段在CMS中可见,因为它需要总是被Citation.js生成的结果覆盖。(如果有一种方法可以添加字段并将其隐藏在CMS中,那将是一个很好的解决方案!(。

我们目前的想法是在保存时添加字段(如果缺失(或更新字段(如果存在(:

(mostly) pseudo code
self.on('apostrophe-docs:afterSave', 'updateBook', async (req) => {
const { piece } = req;
// fetch citations
const citations = { ... };
// create update piece
const updated = _.cloneDeep(piece);
updated.citations = citations;
// check if citations field already present
if (!('citations' in piece)) {
// add citations field
// should method be different if field doesnt exist yet?
self.update(req, updated);
} else {
// check when citations were last updated to ensure enough time diff to update
// update citations field if all is well
self.update(req, updated);
}
});

正如预期的那样,这当前创建了一个无限循环,因为'apostrophe-docs:afterSave'是在调用self.update之后调用的。

  • 有没有办法传递一个参数来阻止回调?
    • 否则,我们正在考虑检查最后一次update()发生的时间,有更好的建议吗
  • update()是否不添加传递给方法的工件上的字段?它是否只关心index.js中定义的字段

欢迎就如何实现这一目标提出任何建议。

beforeSave更可能是您应该使用的。如果您只需在将信息实际保存到数据库之前将其添加到工件上,就不需要调用.update()

对于您关于可见性的问题,您不需要将文档属性添加到工件模式中即可保存它们。字段需要在工件模式中才能在UI中编辑或查看(即使设置为readOnly: true(。

因此,在构建步骤中,您可以添加以下内容:

self.on('books:beforeSave', 'populateCitation');
self.populateCitation = function (req, piece, options) {
// Being extra safe here.
if (piece.type !== 'book') {
return;
}
// Let's pretend `bookInfo` 
if (piece.bookInfo) {
// `getCitation` would be a method using Citation.js
const citationInfo = getCitation(piece.bookInfo);
piece.citation = citationInfo;
}
};

然后,您可以在代码中读取文档上的citation属性,也可以在模板中读取(我很确定(,如果它存在的话(请确保在打印之前在模板中检查它(。

最新更新