cancel
Showing results for 
Search instead for 
Did you mean: 

Cannot create draft for Node.js CAP Service in custom handler

11-23-2022 1:15 AM
Steven-Mason Explorer
4561 views 10 comments Go to solution
0 Likes
Subscribe

I have created a simple project to showcase the issue that I am having at repo: draft-concern.

In this example repo, I have created a very simple service with entity project that has been annotated with @odata.draft.enabled. In the same service, I have created an additional action (createDraft) to add my custom handler code.

using { Customers as schemaCustomers } from '../db/schema';

service CustomerService{
  entity Customers as projection on schemaCustomers;
  annotate Customers with @odata.draft.enabled;

  action createDraft() returns {ID: UUID};
  
}

If I run a simple post command to the Customer entity set, a draft is created as expected:

curl -X POST -H "Content-Type:application/json" -d '{}' http://localhost:4004/customer/Customers
{"@odata.context":"$metadata#Customers/$entity","ID":"1a8b20eb-c044-422e-a137-d7c724c6f91d","CustomerID":null,"CustomerName":null,"IsActiveEntity":false,"HasActiveEntity":false,"HasDraftEntity":false}%

Specifically, you will see that the IsActiveEntity field is set to false since the draft has not been activated yet.

The issue I am running into in my project is when I try to replicate this behavior in a custom handler. In this case I have a very simple handler for the "createDrafts" action defined on the service.

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

module.exports = cds.service.impl( async (srv) => {
  srv.on('createDraft', async (req) => {
    const { Customers } = srv.entities
    const { ID } =  await srv.post(Customers, {})
    return { ID }
  })
})

When I call this action against the service, the behavior is not as expected:

curl -X POST -H "Content-Type:application/json" -d '{}' http://localhost:4004/customer/createDraft
{"@odata.context":"$metadata#CustomerService.return_CustomerService_createDraft","ID":"9d552f07-275c-4a7f-a79f-0fb7e59d94f9"}%

curl -X GET http://localhost:4004/customer/Customers
{"@odata.context":"$metadata#Customers","value":[{"ID":"9d552f07-275c-4a7f-a79f-0fb7e59d94f9","CustomerID":null,"CustomerName":null,"IsActiveEntity":true,"HasActiveEntity":false,"HasDraftEntity":false}]}%
                                         

Here you will see that the IsActiveEntity field has been set to true even though the draft has not been activated.

While in this example, I am using the post convenience method for a CAP service in my custom handler, the same results have occurred regardless of the way I have attempted a post on the Customer entity set via a custom handler.

This appears broken to me due to the fact that an direct POST command to the Customers entity set is not behaving in the same manner as the post method within the custom action of the service.

Any help on how to properly mimic the POST command within a custom handler where a draft entry gets created (with IsActiveEntity is set to false) would be truly appreciated!

cds -v
@sap/cds: 6.3.2
@sap/cds-compiler: 3.4.2
@sap/cds-dk: 4.1.5
@sap/cds-foss: 4.0.0
@sap/cds-mtx: -- missing --
Node.js: v16.18.1
draft-concern: 1.0.0
home: /Users/stevenmason/dev/cap/draft-concern/node_modules/@sap/cds<br>
0 Likes

Accepted Solutions (1)

Accepted Solutions (1)

OlenaT
Product and Topic Expert
Product and Topic Expert

Hi the_mason_abides,

Could you please try the following CQN notation? It worked for me:

await srv.send({query: INSERT.into('CatalogService.Books').entries({}), event: 'NEW'})

Best regards,

Olena

gregorw
SAP Mentor
SAP Mentor
0 Likes

I can confirm that this works. Check my comment here.

Steven-Mason
Explorer
0 Likes

Hello Olena,

This solution did work and I really appreciate the help!

Regards,

Steven

Youssef-kh1
Explorer
0 Likes
I have the same problem
Youssef-kh1
Explorer
0 Likes
I have the same problem,

Answers (3)

Answers (3)

Youssef-kh1
Explorer
0 Likes

Hi,

I see that you have resolved the problem in your code.
I've reviewed your approach, and it seems to be aligned with what I've implemented in my project. However, I'm encountering an unexpected behavior when executing the DUPLICATE action in my TypeScript-based project.

Here's a breakdown of my code:
In OutletsController.ts, I have a method for handling outlet duplication:

public async duplicateOutlet(req: Request): Promise<any> {
try {
let selectedItemID: string;
const firstParam = req.params[0] as { ID: string };
console.log('firstParam:', firstParam.ID);

selectedItemID = firstParam.ID;

const { Outlets } = cds.entities(Constants.CDS_NAMESPACE);
const sQuery = SELECT.from(Outlets).where`(ID) = ${selectedItemID}`;
let selectedItem = await cds.run(sQuery);
console.log('selectedItem:', selectedItem);

// Setting IsActiveEntity to true (unexpected behavior)
selectedItem[0].IsActiveEntity = true;
const newItemData = { ...selectedItem[0] };
delete newItemData.ID;
console.log('newItemData: ',newItemData);

const insertedItem = await INSERT.into(Outlets).entries(newItemData);
console.log(insertedItem);
return insertedItem;
} catch (error) {
console.error('Error duplicating outlet:', error);
throw error;
}
}
In service.cds, I've defined the Outlets entity with the DUPLICATE action:
service.cds

@odata.draft.enabled
entity Outlets as select ID, code @mandatory, description from planification.Outlets actions {
action DUPLICATE() returns Outlets;
}

In service.ts, I'm binding the DUPLICATE action to the duplicateOutlet method in my controller:
this.on(
"DUPLICATE",
this.outletsController.duplicateOutlet.bind(this.outletsController)
);

Despite following similar patterns to your solution, I'm facing issues where the IsActiveEntity field is unexpectedly set to true after executing the DUPLICATE action.
Your guidance on resolving this unexpected behavior would be greatly appreciated.

Youssef.

OlenaT
Product and Topic Expert
Product and Topic Expert
0 Likes

Hi the_mason_abides,

You are not using the .send API correctly. As described in the documentation you mentioned, you need to provide either data or query.

As I mention in the link I gave you, we don't recommend rewriting our draft implementation and don't provide any API to support it. You can use draft events to add your custom logic as described here https://cap.cloud.sap/docs/node.js/app-services#draft, but if you decide to reimplement our out-of-the-box draft handling - we cannot assist you.

Best regards,

Olena

Steven-Mason
Explorer
0 Likes

Hello Olena,

Thanks again for your response. I am definitely not trying to re-implement the out-of-the-box draft handling. As noted in my original post, when I call the draft handling via a POST call from an external HTTP client, it behaves exactly as expected. All I am wanting to do is trigger the same POST behavior, but from within my custom code.

With regard to the srv.send API, inn the example above, my data set is empty (empty brackets). I did this as this is allowed for a POST from an external HTTP client (as demonstrated in my original post). If I pre-fill data for the srv.send call:

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

module.exports = cds.service.impl(async (srv) => {
  srv.on("createDraft", async (req) => {
    const { Customers } = srv.entities

    //const { ID } =  await srv.post(Customers, {})

    const generatedID = cds.utils.uuid()
    const customerID = 1234
    const customerName = "Example Customer"
    const ID = await srv.send("POST", Customers, { ID: generatedID, CustomerID: customerID, CustomerName: customerName })
    return { ID }
  })
})

I still receive the same error message from crud.js:

[INTERNAL ERROR] TypeError: Cannot read properties of undefined (reading 'INSERT')
    at ApplicationService.<anonymous> (/Users/stevenmason/dev/cap/draft-concern/node_modules/@sap/cds/libx/_runtime/common/generic/crud.js:46:32)
    at next (/Users/stevenmason/dev/cap/draft-concern/node_modules/@sap/cds/lib/srv/srv-dispatch.js:75:36)
    at ApplicationService.handle (/Users/stevenmason/dev/cap/draft-concern/node_modules/@sap/cds/lib/srv/srv-dispatch.js:79:6)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async ApplicationService.<anonymous> (/Users/stevenmason/dev/cap/draft-concern/srv/customer-service.js:12:16)
    at async next (/Users/stevenmason/dev/cap/draft-concern/node_modules/@sap/cds/lib/srv/srv-dispatch.js:75:17)
    at async ApplicationService.handle (/Users/stevenmason/dev/cap/draft-concern/node_modules/@sap/cds/lib/srv/srv-dispatch.js:73:10)
    at async /Users/stevenmason/dev/cap/draft-concern/node_modules/@sap/cds/libx/_runtime/cds-services/adapter/odata-v4/handlers/action.js:52:16

Am I missing something with regard to providing data to the srv.send call that is causing this issue?

Thanks again,

Steven

OlenaT
Product and Topic Expert
Product and Topic Expert
0 Likes

Hi the_mason_abides,

Could you please check if this question and answer related to your issue?https://answers.sap.com/answers/13768341/view.html

Best regards,

Olena

Steven-Mason
Explorer
0 Likes

Hello Olena,

Thank you very much for your response. Unfortunately that question is similar, but does not answer my question. I have tried both the srv.post statement (which I am including in my example repo above) and I have also tried the srv.send statement as well. When I have used the srv.send method, I actually receive an error message in inside the cds crud.js source file. Here is the code when attempting to use the srv.send method:

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

module.exports = cds.service.impl( async (srv) => {
  srv.on('createDraft', async (req) => {
    const { Customers } = srv.entities
    //const { ID } =  await srv.post(Customers, {})
    const ID = await srv.send('POST', Customers, {})
    return { ID }
  })
})

When I do this, I get the following error message:

[INTERNAL ERROR] TypeError: Cannot read properties of undefined (reading 'INSERT')
    at ApplicationService.<anonymous> (/Users/stevenmason/dev/cap/draft-concern/node_modules/@sap/cds/libx/_runtime/common/generic/crud.js:46:32)
    at next (/Users/stevenmason/dev/cap/draft-concern/node_modules/@sap/cds/lib/srv/srv-dispatch.js:75:36)
    at ApplicationService.handle (/Users/stevenmason/dev/cap/draft-concern/node_modules/@sap/cds/lib/srv/srv-dispatch.js:79:6)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async ApplicationService.<anonymous> (/Users/stevenmason/dev/cap/draft-concern/srv/customer-service.js:7:16)
    at async next (/Users/stevenmason/dev/cap/draft-concern/node_modules/@sap/cds/lib/srv/srv-dispatch.js:75:17)
    at async ApplicationService.handle (/Users/stevenmason/dev/cap/draft-concern/node_modules/@sap/cds/lib/srv/srv-dispatch.js:73:10)
    at async /Users/stevenmason/dev/cap/draft-concern/node_modules/@sap/cds/libx/_runtime/cds-services/adapter/odata-v4/handlers/action.js:52:16<br>

Here you can see where that error is occurring within crud.js:

It is possible I am calling the srv.send method incorrectly, but I am following the example set in the CAP documentation here.

As mentioned in my previous post, if I call this service directly with a POST method via a HTTP client, I have no issues and draft works correctly. All I am wanting to do is programmatically replicated the POST request in my code. Any suggestions on how to accomplish this is greatly be appreciated!