【问题标题】:How to add/update piece field when the user saves/commits用户保存/提交时如何添加/更新片段字段
【发布时间】:2020-11-16 23:57:36
【问题描述】:

在 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);
  }
});

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

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

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

【问题讨论】:

    标签: node.js apostrophe-cms


    【解决方案1】:

    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 属性,并且(我很确定)也可以在模板中读取它(如果存在)(确保在打印前在模板中检查它)。

    【讨论】:

    • 太棒了,它确实做到了所需要的!现在,既然我们有 50 多个项目要更新,有没有办法强制提交?不需要对片段的数据进行任何更改,因此提交说“没有进行任何更改”并且不起作用......或者这应该是另一个 SO 问题吗?
    • 可能是另一个 SO 问题或 Discord:chat.apostrophecms.com。我没有完全理解用户流程,但我的快速想法是查看commitbatchCommit 路线:github.com/apostrophecms/apostrophe-workflow/blob/main/lib/…
    猜你喜欢
    • 2020-11-12
    • 1970-01-01
    • 1970-01-01
    • 2019-02-15
    • 1970-01-01
    • 2016-08-01
    • 2017-09-23
    • 2013-08-24
    • 1970-01-01
    相关资源
    最近更新 更多