0

我通过为 req.user 提供一个实例在服务器上进行身份验证cds.User,并添加了一些属性:

User {
  id: '110226363079182595683',
  attr: { name: 'depth1', email: 'depth1@protonmail.com' },
  _roles: { 'identified-user': true, 'authenticated-user': true }
}

这允许我使用经过身份验证的用户调用我的 CDS 服务。
它运作良好。

然后,我在我的 CDS 模式中有一个实体:

entity Comments {
    key ID      : Integer;
        project : Association to Projects;
        title  : String;
        text   : String;
        CreatedBy  : String  @cds.on.insert : $user;
        CreatedByName  : String  @cds.on.insert : $user.name;
}

我在 SQLite 数据库上的架构。我启动了服务器,我启动了一个 UI5 应用程序,它允许在 OData V4 中插入评论,这就是发生的事情:

HTTP 请求:

--batch_id-1642708209182-45
Content-Type:application/http
Content-Transfer-Encoding:binary

POST Projects(1)/comments HTTP/1.1
Accept:application/json;odata.metadata=minimal;IEEE754Compatible=true
Accept-Language:fr-FR
Content-Type:application/json;charset=UTF-8;IEEE754Compatible=true

{"ID":0,"text":"test comment"}
--batch_id-1642708209182-45--
Group ID: $auto

服务器日志:

[cds] - > CREATE Projects(1)/comments

HTTP 响应:

--batch_id-1642708209182-45
content-type: application/http
content-transfer-encoding: binary

HTTP/1.1 201 Created
odata-version: 4.0
content-type: application/json;odata.metadata=minimal;IEEE754Compatible=true
location: Comments(101)

{"@odata.context":"../$metadata#Comments/$entity","ID":101,"project_ID":1,"title":null,"text":"test comment","CreatedBy":"110226363079182595683","CreatedByName":"depth1"}
--batch_id-1642708209182-45--

HTTP 请求:

--batch_id-1642708209355-46
Content-Type:application/http
Content-Transfer-Encoding:binary

GET Projects(1)/comments(101)?$select=CreatedByName,ID,text HTTP/1.1
Accept:application/json;odata.metadata=minimal;IEEE754Compatible=true
Accept-Language:fr-FR
Content-Type:application/json;charset=UTF-8;IEEE754Compatible=true


--batch_id-1642708209355-46--
Group ID: $auto

服务器日志

[cds] - > READ Projects(1)/comments(101) { '$select': 'CreatedByName,ID,text' }

HTTP 响应

--batch_id-1642708209355-46
content-type: application/http
content-transfer-encoding: binary

HTTP/1.1 200 OK
odata-version: 4.0
content-type: application/json;odata.metadata=minimal;IEEE754Compatible=true

{"@odata.context":"../$metadata#Comments(CreatedByName,ID,text)/$entity","CreatedByName":null,"ID":101,"text":"aaa"}
--batch_id-1642708209355-46--

在我的数据库中,CreatedBy已填充但未填充CreatedByName。同样在创建请求中,我得到了CreatedByName服务器的填充并返回它真的很奇怪。

我怎样才能cds.User在数据库中插入一些属性?!谢谢 !

4

1 回答 1

0

哇,我找到了解决方案!通过在service.js

const cds = require('@sap/cds')

module.exports = cds.service.impl(function() {
    this.before('CREATE', 'Comments', fillData)
})

async function fillData(req) {
    req.data.CreatedByName = req.user.attr.name;
}
于 2022-01-20T20:12:03.063 回答