Pages 02 and 03 gave the Order Approval Portal a data model and two services that already answer every OData request without a single line of JavaScript. This page adds the business logic that a generic provider cannot guess: defaults and checks when a rep creates a request (CR3) and the one-click approve / reject for managers (CR4). You learn where the code lives (a class that extends cds.ApplicationService), the three handler phases before → on → after, the req object, errors, CQL with cds.ql, queries over associations, transactions, actions and functions, events emitted inside the app, and the patterns and pitfalls interviewers ask about. The same logic in Java is on page 05. Sources: capire (cap.cloud.sap/docs/node.js and the Services guide).
Part 1 – Why custom logic, and what this page builds
Requirements on this page
ID | Requirement | CAP concept | Part |
|---|---|---|---|
CR3 | Set deadline and region automatically when a rep creates a request | before handlers, defaults in | 3 |
CR3 | Reject bad input: no request type, a foreign region, a rejection without a reason |
| 4, 8 |
CR3 | Show managers which requests are overdue | after READ handler, virtual | 3 |
CR4 | Managers approve or reject with one click | bound actions | 8 |
CR4 | Badge with the number of open requests | unbound function | 8 |
CR4 | Other parts of the app react when a request is decided |
| 9 |
Why: CAP's generic providers (page 03) already do CREATE, READ, UPDATE, DELETE, paging, sorting, deep inserts, draft and the declarative checks (@mandatory, @assert…). Custom code is only for the *difference*: rules that depend on other data, computed values, status changes and calls to other services. capire's advice is to look for a declarative option first (annotations, constraints, status flows) and write handlers only for what is left.
You need… | Declarative first | Handler when… |
|---|---|---|
A required field |
| the rule is conditional (amount, role) |
Value ranges, formats, existing references |
| the check reads other tables |
Allowed status changes for actions |
| the action also writes other data |
Default values |
| the default is computed (deadline) |
Read-only / computed fields |
| value needs code (overdue flag) |
ABAP view: the handlers of this page play the role of a RAP behavior pool – determinations (defaults), validations (checks) and action implementations. The difference: CAP has no separate interaction and save phase; one request is one database transaction (Part 7). Side-by-side mapping: → see CAP › 01 · CAP Foundations (CAP vs RAP).
Part 2 – The service implementation class
Every service defined in CDS is served by an instance of cds.ApplicationService – created for you by cds.serve when there is no code. To add logic, place a .js file with the same name next to the .cds file. CAP loads it automatically and uses the exported class as the service.

|
Element | What it does | Tip |
|---|---|---|
extends cds.ApplicationService | inherits generic CRUD, deep CRUD, draft, paging, | extend |
init() | runs once at server start; registers handlers | no request data here – only registrations and setup |
this.entities | the entity definitions of this service | use them as handler targets and in |
return super.init() | lets the base class register its generic handlers | register your own handlers before it, as capire shows |
Same-name | found automatically | or set |
- The older function style
module.exports = function () { this.on(...) }(orcds.service.impl) still works and appears in many samples. New code uses the class style shown above. - TypeScript works too:
cds add typescriptsets the project up and addscds-typer, which generates typed entity classes from the model;cds watchdetectstsconfig.jsonand runs.tshandlers withcds-tsx(since@sap/cds-dk8.6). Precompile to JavaScript for production.
Part 3 – Event handlers: before, on, after
Every request is an event (CREATE, READ, UPDATE, DELETE, an action name, or a custom event) for a target entity. You register handlers for three phases. The picture follows the rep's new request through all of them.

Phase | Signature (capire) | Typical use | Execution |
|---|---|---|---|
before | srv.before(event, entity?, req => …) | validate input, set defaults, check preconditions | all matching handlers run in parallel |
on | srv.on(event, entity?, (req, next) => …) | implement actions, replace or wrap generic CRUD, delegate to a remote service | one after another; each decides whether to call |
after | srv.after(event, entity?, (results, req) => …) | computed fields, hide data, follow-up work | all matching handlers run in parallel |
3.1 CR3 – defaults in a before handler
|
req.data is the payload that the generic handler will insert, so changing it in before changes what is stored. status is @readonly in RepService (page 03), so a client cannot send its own value and the CDS default #New ('N') applies; the deadline is computed, so it needs code.
3.2 Event names and targets
Registration | Meaning |
|---|---|
this.before('CREATE', ApprovalRequests, …) | one event, one entity |
this.before(['CREATE', 'UPDATE'], ApprovalRequests, …) | several events |
this.before('SAVE', ApprovalRequests, …) | shortcut for CREATE and UPDATE |
this.on('approve', ApprovalRequests, …) | bound action (Part 8) |
this.on('openCount', …) | unbound function – no entity argument |
this.before('*', …) | every event of the service, e.g. logging |
this.after('each', ApprovalRequests, row => …) | once per row of a READ result, synchronous only |
this.before('NEW', ApprovalRequests.drafts, …) | draft events – → see CAP › 06 · Fiori Elements & Draft |
3.3 on handlers and next()
on handlers form an interceptor stack: the first registered runs first; it may do its own work and call next() to hand over to the next handler – finally the generic handler. A handler that returns without calling next() ends the chain and its return value is the result.
|
3.4 CR3 – the overdue colour in an after handler
criticality is a virtual element added to the service projection (virtual criticality : Integer, explained on page 02), so the database has no column for it. The after('each') handler in Part 2 fills it per row – red for overdue or rejected, yellow for open, green for approved – and Fiori elements colours the status with it (page 06). Use after('READ') when you need the whole array, for example to load extra data for all rows with one query.
- If a plain yes/no is enough, a calculated element (
overdue : Boolean = deadline < $now, page 02) needs no code at all – CAP computes it in the database. - Do not change the database in
after READhandlers – reads must stay free of side effects, and the result has already been read.
Part 4 – The req object, the current user and errors
Every handler receives a cds.Request (req) – in after handlers it is the second argument. Asynchronous messages arrive as cds.Event, the base class with only event, data and headers.
Property | Content | Order Approval example |
|---|---|---|
req.event | event name |
|
req.target | target entity definition ( | ManagerService.ApprovalRequests |
req.data | payload / action parameters – changeable |
|
req.params | keys from the URL path, in order; each entry an object such as |
|
req.subject | pointer to the targeted row(s), usable in | SELECT.one.from(req.subject) |
req.query | the request as a CQN query | inspect |
req.user | authenticated user: | req.user.is('Manager') |
req.locale | preferred language from |
|
req.tenant | tenant id in multitenant apps | → page 11 |
req.timestamp | one constant | same time for all writes |
| headers; Express | rarely needed |
4.1 Reading the user and locale
|
Prefer declarative @requires / @restrict for role checks and req.user only for rules that annotations cannot express – such as checking the region of a new row, which a where restriction cannot do. Locally, the mocked users mia and raj (role Rep, regions EMEA / APAC) and lena (role Manager) come from cds.requires.auth in package.json – → see CAP › 07 · Authorization & Security. Messages are localized automatically when you use message keys from _i18n/messages*.properties: req.reject(409, 'MY_KEY', { stock }) looks the key up in cds.i18n.messages for the request's locale and fills {stock}.
4.2 req.error, req.reject, req.warn, req.info
Method | Behaviour | Use for |
|---|---|---|
req.reject(…) | builds the error and throws immediately – the handler stops | a fatal precondition (wrong status, missing role) |
req.error(…) | collects the error in | field validations – show every wrong field at once |
| success response with messages in the | "Deadline is a public holiday" |
All accept (status?, message, target?, args?) or one object { status, code, message, target, args }. target names the field, so Fiori elements highlights the right input.
|
The other half of CR3 – "no rejection without a reason" – is a precondition of the reject action and uses req.reject (Part 8). Simple field rules (@mandatory, @assert.range, @assert with a case expression) are already declared on page 03 – code only adds what annotations cannot see.
- A plain
throw new Error('…')also fails the request, but with status 500 and no field target – usereq.reject/req.errorfor business errors.
Part 5 – CQL with cds.ql: SELECT, INSERT, UPSERT, UPDATE, DELETE
CQL is CDS's query language – SQL plus path expressions over associations. In Node.js you build queries with cds.ql (globals SELECT, INSERT, UPSERT, UPDATE, DELETE). A query is a CQN object (a JSON query tree) that CAP translates into SQL for SQLite, HANA or PostgreSQL, or into OData calls for remote services.

|
Rule | Why |
|---|---|
Always | queries are lazy thenables; without |
| no service handlers, no service authorization – the right choice inside your own handlers |
| its handlers and checks run – use it to call another CAP or remote service |
Objects or tagged templates only | values become bind parameters. Never concatenate strings; never put parentheses around a tagged template (capire marks it BAD) |
Use service entities ( | projections are views in the database, so they work with |
The same queries work interactively: start cds repl in the project and try await SELECT.from('sap.capire.orderapproval.ApprovalRequests') against the sample data.
Part 6 – Querying associations and compositions
CQL navigates the model like an ABAP CDS view navigates associations: no explicit JOINs. The model relations come from page 02 – customer (association to Customers), notes and decisions (compositions).
Need | cds.ql | Result |
|---|---|---|
Field of an associated entity (to-one) | SELECT.from(ApprovalRequests).columns('ID', 'customer.name as customer') | flat rows – CAP adds the JOIN |
Request with its notes (to-many, nested) | SELECT.one.from(ApprovalRequests, id, r => { r.ID, r.salesOrder, r.notes(n => { n.text, n.createdAt }) }) | one object with a |
Only the notes of one request |
| rows of |
Filter by a related entity | tagged-template where with exists notes[text like '%urgent%'] (see code) | requests that have such a note |
|
Customerscomes from S/4HANA in production (CR9). A path such ascustomer.nameonly becomes a JOIN when both entities are in the same database; for remote entities you read them separately – → see CAP › 09 · Remote Services & Integration.- Avoid the N+1 pattern: never run one query per row in a loop. Read related data with one nested projection or one
where({ ID: { in: ids } })query.
Part 7 – Transactions: cds.tx, nested calls and background work
Why it matters: approving a request writes two rows (status and decision). Both must succeed or neither. CAP opens one root transaction per incoming request and commits or rolls it back after the after phase – you do not write COMMIT WORK. Every service your handler calls (the database, another CAP service) joins as a nested transaction and commits with the root.

|
Situation | Use |
|---|---|
Normal handler code | the automatic request transaction |
Script, test, startup code, CLI |
|
Work that must survive a failure of the request (audit of a failed attempt) |
|
Scheduled or long work after the response | cds.spawn(…) |
E-mail / push after a successful commit |
|
- There are no distributed transactions: an HTTP call to S/4HANA made inside the handler is not undone by a rollback. Use the transactional outbox (
cds.queued) for such calls – → see CAP › 10 · Messaging & Events. srv.tx(req)/cds.tx(req)from older samples still works but capire says it is neither required nor recommended any more – the context is propagated throughcds.context.
Part 8 – Actions and functions (CR4: approve and reject)
Generic CRUD cannot express "approve". CDS actions (may change data, called with POST) and functions (read only, called with GET) add operations to a service. Bound operations belong to one entity instance; unbound ones belong to the service.

8.1 Declare them in CDS
|
8.2 Implement them in Node.js
|
Call | HTTP (OData V4) |
|---|---|
bound action |
|
bound action with a parameter |
|
bound action with draft-enabled entity | key includes |
unbound function | GET /odata/v4/rep/openCount() |
unbound action (if you add one) |
|
from code |
|
OData requires the service-qualified name for bound operations (ManagerService.approve); CAP also accepts the short form for convenience. Functions need (). In .http test files you can call both forms – → testing on page 12.
8.3 Declarative alternative: status flows
The status check in the before handler is so common that CAP offers it declaratively. With @flow.status, CAP checks @from before the action (409 Conflict if the status does not match) and sets @to afterwards. Your handler then only writes the decision row.
|
- Status flows use the enum type
Statusof page 02 (New,Approved,Rejected). Node.js supports them out of the box; Java needs thecom.sap.cds:cds-feature-flowdependency insrv/pom.xml.@to: $flow.previousreturns to the status before the last transition. - Fiori elements shows bound actions as buttons once you add
@UI.LineItem/@UI.Identificationentries; enabling them only for status N (@Core.OperationAvailable) and refreshing the page after the action (side effects) → see CAP › 06 · Fiori Elements & Draft.
Part 9 – Events emitted inside the app
Not every follow-up belongs in the approve handler. Declare an event in the service, emit it, and let other parts of the app subscribe. The emitter does not know its listeners – loose coupling inside one app, and the same code later works across apps with a message broker.
|
Question | Answer |
|---|---|
Who receives the event? | every handler registered with |
What does | a |
When is it sent to other apps? | when the event is configured for messaging ( |
Difference to |
|
- CR10's
OrderApprovedevent for the S/4HANA side is exactly this pattern with a broker behind it – page 10 configures it.
Part 10 – Typical patterns and pitfalls
Pitfall | What happens | Do instead |
|---|---|---|
Forgetting | generic CRUD handlers are missing; requests fail or return nothing | always end |
Missing | query never runs, or runs after commit – "my update is lost" | await every query; lint with |
String concatenation in | SQL injection risk | objects or tagged templates without ( ) |
Read status, then update (race) | two managers approve the same request at the same time | conditional |
Throwing plain | HTTP 500, no field highlight | req.reject(4xx, msg, target) |
One query per row in | N+1 queries, slow lists | one query with |
Async work in | handler must be synchronous; promise ignored |
|
Calling remote APIs before validation ends | remote side effect although the request fails | validate in |
| separate root transaction – not rolled back with the request | use the request transaction; |
Business rules only in the UI | API clients (CR2) bypass them | rules in handlers or annotations – the service is the boundary |
Role checks in code everywhere | hard to audit |
|
Reusable patterns
- Validation handler: collect with
req.error, let CAP reject after the phase – one round trip shows all wrong fields. - Wrapper:
on+next()to add logging, caching or a fallback around generic handlers. - Delegation:
this.on('READ', Customers, req => s4.run(req.query))forwards reads to the remote S/4HANA service (page 09). - Helper methods on the class: keep handlers short (
this.decide(…)) and test the logic withcds.test(page 12).
Part 11 – Interview questions
Q1. Where do you put custom logic in a CAP Node.js service?
In a .js file with the same name next to the service's .cds file (or one named by @impl). It exports a class that extends cds.ApplicationService, registers handlers with this.before/on/after in init() and ends with return super.init() so the generic handlers are registered too.
Q2. Explain the before, on and after phases.
before validates and enriches req.data – all handlers run in parallel. on does the work – handlers run one after another as an interceptor stack, each can call next(); the generic CRUD handler sits at the end. after post-processes results – in parallel, receiving (results, req). All three run in the same transaction, so an error in any phase rolls everything back.
Q3. What is the difference between req.error and req.reject?
req.reject throws immediately and stops the handler. req.error only collects errors in req.errors; CAP rejects the request after the current phase with all of them (MULTIPLE_ERRORS). Use req.error for field validations, req.reject for fatal preconditions. req.warn / req.info return messages with a successful response.
Q4. What is CQN, and how does await SELECT.from(X) know where to run?
CQN is the JSON object form of a CQL query that cds.ql builds. A query is a lazy thenable; awaiting it runs it on the primary database (cds.db.run). srv.run(q) sends it through another service, for example a remote OData service, where CAP translates CQN into OData requests.
Q5. How do you read a request together with its notes?
With a nested projection: SELECT.one.from(ApprovalRequests, id, r => { r.ID, r.notes(n => { n.text }) }) returns an object with a notes array. To-one fields use path expressions such as customer.name; filters over to-many use exists notes[...]. No manual JOINs.
Q6. How are transactions handled? When would you use cds.tx?
CAP starts a root transaction per request and commits or rolls back after the after phase; services called inside join as nested transactions. cds.tx(async tx => …) creates a new root – for scripts, tests, jobs, or work that must commit independently. cds.spawn runs background jobs with their own transaction; req.on('succeeded') runs after commit.
Q7. Bound vs unbound actions, and actions vs functions?
Bound operations are declared in entity … actions { } and called on one instance (/ApprovalRequests(ID=…)/ManagerService.approve); the handler uses req.subject or req.params. Unbound ones are declared at service level. Actions may change data and use POST; functions are side-effect free, use GET and need ().
Q8. How do you get the current user and language in a handler?
req.user.id, req.user.is('Manager') and req.user.attr (token attributes); req.locale from Accept-Language; req.tenant in multitenant apps. Role checks should be declarative with @requires / @restrict wherever possible.
Q9. Why should handlers write with await UPDATE(...) and not via srv.update(...) on the same service?
Inside your own handlers you normally want the database directly (cds.db): no re-entry into your own handlers, no second authorization pass and no endless loops. Use srv.send / srv.run when you deliberately want the target service's handlers and checks – for example calling another service or the remote S/4HANA API.
Q10. Scenario: two managers click Approve on the same request at the same time. What happens and how do you prevent a double decision?
With read-check-update both may pass the status check and insert two decisions. Make the update conditional – UPDATE(ApprovalRequests).set({ status: 'A' }).where({ ID, status: 'N' }) – and reject with 409 when the affected count is 0; or lock with SELECT.one.from(…).forUpdate(), use @flow.status, or ETags (@odata.etag) so the second client gets a precondition error.
Q11. Scenario: the rep gets an e-mail "request created" even when the save failed. Why, and the fix?
The e-mail is sent inside the handler before the transaction commits; a later error rolls the data back but the e-mail is already out. Send it in req.on('succeeded'), or better through an outboxed (cds.queued) mail service so it is stored with the transaction and delivered with retries after commit.
Q12. A colleague wraps a tagged template in parentheses inside where(...). What is wrong?
The parentheses turn the tagged template into a normal string, so the value is concatenated into the query – SQL injection. Write the template directly after .where (no parentheses) or use .where({ status: s }); both pass the value as a bind parameter.
🏠 Start Here · ◀ 03 · Services · 05 · CAP Java ▶ · Sections: CORE ABAP | OOPS ABAP | ABAP on HANA | Clean Core | RAP | ABAP Points | SAP Fiori | SAPUI5 | Mobile Development (MDK) | BTP Foundations | BTP Development | CAP | SAP Build | ABAP on BTP | Integration Suite | SAP Business AI | SAP BASIS | Security | SAP SDLC
Functional: FICO ABAP | TRM ABAP | VIM | SAP BIS | SD ABAP | MM ABAP | PP ABAP | QM ABAP | PM ABAP | PS ABAP | EWM | TM ABAP | EHS ABAP | HR ABAP | BW | SAP MDG | SAP Analytics Cloud | SAP Ariba | SAP CX | SAP IBP