Beyond ABAPdesigned by@Tejoram97
Beyond ABAP / CAP / Custom Logic in Node.js – Event Handlers, CQL & Actions

Custom Logic in Node.js – Event Handlers, CQL & Actions

CAP · SAP BTP ·

Open the interactive lesson →
  1. Why custom logic, and what this page builds
  2. The service implementation class
  3. Event handlers: before, on, after
  4. The req object, the current user and errors
  5. CQL with cds.ql: SELECT, INSERT, UPSERT, UPDATE, DELETE
  6. Querying associations and compositions
  7. Transactions: cds.tx, nested calls and background work
  8. Actions and functions (CR4: approve and reject)
  9. Events emitted inside the app
  10. Typical patterns and pitfalls
  11. Interview questions

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 req.data

3

CR3

Reject bad input: no request type, a foreign region, a rejection without a reason

req.error, req.reject

4, 8

CR3

Show managers which requests are overdue

after READ handler, virtual criticality

3

CR4

Managers approve or reject with one click

bound actions approve() / reject(reason)

8

CR4

Badge with the number of open requests

unbound function openCount() in RepService

8

CR4

Other parts of the app react when a request is decided

event RequestDecided, this.emit

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

@mandatory on the element (page 02)

the rule is conditional (amount, role)

Value ranges, formats, existing references

@assert.range, @assert.format, @assert.target

the check reads other tables

Allowed status changes for actions

@flow.status + @from / @to (Part 8)

the action also writes other data

Default values

default in CDS, managed aspect

the default is computed (deadline)

Read-only / computed fields

@readonly, calculated elements

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.

Project layout with rep-service.js and manager-service.js next to their cds files, and the ManagerService class extending cds.ApplicationService with init and super.init
// srv/rep-service.js
const cds = require('@sap/cds')

module.exports = class RepService extends cds.ApplicationService {
init () {
const { ApprovalRequests } = this.entities   // the service's projection, not db.ApprovalRequests

this.before('CREATE', ApprovalRequests, req => this.checkInput(req))
this.before('CREATE', ApprovalRequests, req => this.setDefaults(req))
this.after('each', ApprovalRequests, row => { row.criticality = criticality(row) })
this.on('openCount', () => this.openCount())

return super.init()                           // always: registers the generic handlers
}
checkInput (req) { /* Part 4 */ }
setDefaults (req) { /* Part 3 */ }
openCount () { /* Part 8 */ }
}
const today = () => new Date().toISOString().slice(0, 10)
const criticality = r =>                          // 1 red, 2 yellow, 3 green (Fiori criticality)
r.status === 'A' ? 3 : r.status === 'R' ? 1 : r.deadline < today() ? 1 : 2

Element

What it does

Tip

extends cds.ApplicationService

inherits generic CRUD, deep CRUD, draft, paging, @assert checks, authorization, managed fields

extend cds.Service only for services that have no entities

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 cds.ql; cds.entities('sap.capire.orderapproval') gives the db entities

return super.init()

lets the base class register its generic handlers

register your own handlers before it, as capire shows

Same-name .js file

found automatically

or set @impl: 'srv/handlers/manager.js' on the service

  • The older function style module.exports = function () { this.on(...) } (or cds.service.impl) still works and appears in many samples. New code uses the class style shown above.
  • TypeScript works too: cds add typescript sets the project up and adds cds-typer, which generates typed entity classes from the model; cds watch detects tsconfig.json and runs .ts handlers with cds-tsx (since @sap/cds-dk 8.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.

Request flow through before handlers (validation, defaults), on handlers (custom, then generic CRUD via next) and after handlers, followed by commit and succeeded hooks

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 next()

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

setDefaults (req) {
const in3days = new Date(Date.now() + 3 * 24 * 60 * 60 * 1000)
req.data.deadline = in3days.toISOString().slice(0, 10)    // Date element: 'YYYY-MM-DD'
req.data.region ??= req.user.attr.region?.[0]             // rep's own region (attribute list, CR7)
}   // status needs no code: the model says  status : Status default #New

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.

// wrap the generic READ: count how often managers open the list
this.on('READ', ApprovalRequests, async (req, next) => {
const result = await next()             // generic handler reads from the database
console.log(`${req.user.id} read ${result.length ?? 1} request(s)`)
return 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 READ handlers – 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

'CREATE', 'approve'

req.target

target entity definition (undefined for unbound operations)

ManagerService.ApprovalRequests

req.data

payload / action parameters – changeable

{ salesOrder, netAmount, type_code }, { reason }

req.params

keys from the URL path, in order; each entry an object such as { ID: … }

const [{ ID }] = req.params in a bound action

req.subject

pointer to the targeted row(s), usable in cds.ql

SELECT.one.from(req.subject)

req.query

the request as a CQN query

inspect $filter from Fiori

req.user

authenticated user: .id, .is(role), .attr

req.user.is('Manager')

req.locale

preferred language from Accept-Language

'de' → German texts

req.tenant

tenant id in multitenant apps

→ page 11

req.timestamp

one constant Date per request (used for $now)

same time for all writes

req.headers, req.http

headers; Express req / res for HTTP requests

rarely needed

4.1 Reading the user and locale

this.before('CREATE', ApprovalRequests, req => {
if (!req.user.is('Rep')) return req.reject(403, 'Only sales reps create approval requests')
const myRegions = req.user.attr.region ?? []   // token attribute (XSUAA / IAS) – a list, e.g. ['EMEA']
console.log(req.user.id, myRegions, req.locale) // 'mia' [ 'EMEA' ] 'en'
})

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 req.errors; CAP rejects after the phase with all errors (MULTIPLE_ERRORS)

field validations – show every wrong field at once

req.warn(…) / req.info(…) / req.notify(…)

success response with messages in the sap-messages header

"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.

checkInput (req) {
const { type_code, region, netAmount } = req.data
const myRegions = req.user.attr.region ?? []
if (!type_code) req.error(400, 'Choose a request type (CRED, DISC or PRIC)', 'type_code')
if (region && !myRegions.includes(region))
req.error(403, `You cannot create requests for region ${region}`, 'region')
if (type_code === 'DISC' && !(netAmount > 0))
req.error(400, 'A discount request needs the net amount of the order', 'netAmount')
}   // no throw here: CAP rejects after the before phase with all collected errors

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 – use req.reject / req.error for 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.

The five cds.ql statements with Order Approval examples next to Open SQL equivalents, plus notes on lazy execution, where queries run and SQL injection safety
const { ApprovalRequests, Decisions, Customers, Notes } = this.entities
const today = new Date().toISOString().slice(0, 10)

// SELECT – arrays, single rows, columns, order, paging
const open    = await SELECT.from(ApprovalRequests).where({ status: 'N' }).orderBy('deadline desc').limit(50)
const one     = await SELECT.one.from(ApprovalRequests, id)           // by key -> object or undefined
const big     = await SELECT.from(ApprovalRequests).where({ netAmount: { '>': 10000 }, currency_code: 'EUR' })
const late    = await SELECT.from(ApprovalRequests).where `status = 'N' and deadline < ${today}`
const amounts = await SELECT.from(ApprovalRequests).columns('ID', 'salesOrder', 'netAmount')

// INSERT and UPSERT
await INSERT.into(Decisions).entries({ request_ID: id, outcome: 'R', comment: reason })  // createdBy = $user
await UPSERT.into(Customers).entries({ ID: '1000123', name: 'MedSupply GmbH' })    // insert or update by key

// UPDATE – by key, or with a condition
await UPDATE(ApprovalRequests, id).with({ status: 'A' })
const n = await UPDATE(ApprovalRequests).set({ status: 'A' }).where({ ID: id, status: 'N' })
if (n === 0) req.reject(409, 'Request was already decided')            // optimistic guard

// DELETE
await DELETE.from(Notes).where({ request_ID: id })

Rule

Why

Always await a query

queries are lazy thenables; without await nothing runs, or it runs after the transaction is closed

await q runs on the primary database (cds.db)

no service handlers, no service authorization – the right choice inside your own handlers

await srv.run(q) / srv.read(…) runs through a service

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 (this.entities)

projections are views in the database, so they work with cds.db too and keep code aligned with the API

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 notes array (like OData $expand)

Only the notes of one request

SELECT.from with path ApprovalRequests[ID=${id}]:notes

rows of Notes

Filter by a related entity

tagged-template where with exists notes[text like '%urgent%'] (see code)

requests that have such a note

// a request with customer name and its notes, newest first
const r = await SELECT.one.from(ApprovalRequests, id, r => {
r.ID, r.salesOrder, r.netAmount, r.customer(c => { c.name }),
r.notes(n => { n.text, n.createdBy, n.createdAt })
})

// requests that have an 'urgent' note (exists over the to-many composition)
const urgent = await SELECT.from(ApprovalRequests).where `exists notes[text like '%urgent%']`

// deep insert: request + notes in one call through the service (generic deep CRUD)
const rep = await cds.connect.to('RepService')
await rep.create('ApprovalRequests').entries({
salesOrder: '4711', netAmount: 25000, currency_code: 'EUR', type_code: 'DISC', region: 'EMEA',
notes: [ { text: 'Customer asked for 60 days payment terms' } ]
})
  • Customers comes from S/4HANA in production (CR9). A path such as customer.name only 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.

Root transaction for the approve request with nested db and service calls, commit or rollback, and side notes on cds.tx, cds.spawn, req.on succeeded and SQLite
// 1) inside a handler: nothing to do – already transactional
this.on('approve', ApprovalRequests, async req => {
await UPDATE(req.subject).with({ status: 'A' })
await INSERT.into(Decisions).entries({ request_ID: req.params[0].ID, outcome: 'A' })
})   // an error anywhere -> both statements rolled back

// 2) outside requests (scripts, tests, jobs): an explicit root transaction
const today = new Date().toISOString().slice(0, 10)
await cds.tx(async () => {
await UPDATE(ApprovalRequests).set({ status: 'R' })
.where `status = 'N' and deadline < ${today}`
})   // committed when the function resolves, rolled back if it throws

// 3) background work with its own transaction and context
cds.spawn({ every: 60 * 60 * 1000 /* ms */ }, async () => { /* hourly reminder for due requests */ })

// 4) after the commit: notifications that must not run for rolled-back work
req.on('succeeded', () => notifyRep(req.data))

Situation

Use

Normal handler code

the automatic request transaction

Script, test, startup code, CLI

cds.tx(async tx => …) – new root

Work that must survive a failure of the request (audit of a failed attempt)

cds.tx – separate root, committed on its own

Scheduled or long work after the response

cds.spawn(…)

E-mail / push after a successful commit

req.on('succeeded'); reliable delivery → outbox, page 10

  • 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 through cds.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.

Approve button sends POST to ApprovalRequests(ID)/ManagerService.approve; before handler checks status, on handler updates status, inserts decision and emits RequestDecided; comparison of bound and unbound operations

8.1 Declare them in CDS

// srv/manager-service.cds
using { sap.capire.orderapproval as db } from '../db/schema';

service ManagerService @(requires: 'Manager') {            // → /odata/v4/manager
entity ApprovalRequests as projection on db.ApprovalRequests { … }   // as on page 03
actions {
action approve ();                                    // bound: one request
action reject  (reason : String(255));                // bound, with a parameter
};
entity Decisions as projection on db.Decisions;

event RequestDecided { ID : UUID; outcome : String(1); reason : String(255); }   // added here, Part 9
}

// srv/rep-service.cds (excerpt, page 03)
service RepService @(requires: 'Rep') {
function openCount () returns Integer;                    // unbound, read only
}

8.2 Implement them in Node.js

// srv/manager-service.js
const cds = require('@sap/cds')

module.exports = class ManagerService extends cds.ApplicationService {
init () {
const { ApprovalRequests } = this.entities

this.before(['approve', 'reject'], ApprovalRequests, async req => {
const r = await SELECT.one.from(req.subject).columns('status')
if (!r) return req.reject(404, 'Approval request not found')
if (r.status !== 'N')
return req.reject(409, `Request is already ${r.status === 'A' ? 'approved' : 'rejected'}`)
})
this.before('reject', ApprovalRequests, req => {         // CR3: no rejection without a reason
if (!req.data.reason?.trim()) return req.reject(400, 'Enter a reason for the rejection', 'reason')
})

this.on('approve', ApprovalRequests, req => this.decide(req, 'A'))
this.on('reject',  ApprovalRequests, req => this.decide(req, 'R', req.data.reason))
return super.init()
}

async decide (req, outcome, reason = null) {
const { ApprovalRequests, Decisions } = this.entities
const [{ ID }] = req.params
await UPDATE(ApprovalRequests, ID).with({ status: outcome, reason })    // decision reason (page 02)
await INSERT.into(Decisions).entries({ request_ID: ID, outcome, comment: reason })  // createdBy = manager
await this.emit('RequestDecided', { ID, outcome, reason })              // Part 9
return SELECT.one.from(ApprovalRequests, ID)                            // updated row for Fiori
}
}

// srv/rep-service.js – the unbound function (see the class skeleton in Part 2)
openCount () {
const { ApprovalRequests } = this.entities
return SELECT.one.from(ApprovalRequests).columns('count(*) as count').where({ status: 'N' })
.then(r => r.count)      // @restrict on RepService limits rows to the rep's region (page 07)
}

Call

HTTP (OData V4)

bound action

POST /odata/v4/manager/ApprovalRequests(ID=<uuid>)/ManagerService.approve with body {}

bound action with a parameter

POST …/ApprovalRequests(ID=<uuid>)/ManagerService.reject with { "reason": "Margin below 5 %" }

bound action with draft-enabled entity

key includes IsActiveEntity=true – page 06

unbound function

GET /odata/v4/rep/openCount()

unbound action (if you add one)

POST /odata/v4/<service>/<action> with the parameters as JSON body

from code

await mgr.send({ event: 'reject', entity: 'ApprovalRequests', params: [{ ID }], data: { reason } }) – runs handlers and checks

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.

annotate ManagerService.ApprovalRequests with @flow.status: status actions {
approve @from: [ #New ] @to: #Approved;
reject  @from: [ #New ] @to: #Rejected;
};
  • Status flows use the enum type Status of page 02 (New, Approved, Rejected). Node.js supports them out of the box; Java needs the com.sap.cds:cds-feature-flow dependency in srv/pom.xml. @to: $flow.previous returns to the status before the last transition.
  • Fiori elements shows bound actions as buttons once you add @UI.LineItem / @UI.Identification entries; 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.

// emitter (in ManagerService.decide, see Part 8)
await this.emit('RequestDecided', { ID, outcome, reason })

// subscriber, e.g. in srv/notification-service.js
module.exports = class NotificationService extends cds.Service {
async init () {
const mgr = await cds.connect.to('ManagerService')
mgr.on('RequestDecided', async msg => {           // msg is a cds.Event: msg.event, msg.data, msg.headers
const { ID, outcome } = msg.data
console.log(`Request ${ID} decided: ${outcome}`)  // e.g. send e-mail to the rep
})
return super.init()
}
}

Question

Answer

Who receives the event?

every handler registered with srv.on('<event>') on the emitting service; event handlers run concurrently

What does msg contain?

a cds.Event: event, data, headers – no req.reject, no reply

When is it sent to other apps?

when the event is configured for messaging (cds.requires.messaging) – then CAP publishes it to SAP Event Mesh / Advanced Event Mesh, by default after the commit (outbox). → see CAP › 10 · Messaging & Events

Difference to this.send?

send = request, expects a reply, can fail the caller; emit = fire-and-forget notification

  • CR10's OrderApproved event 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 return super.init()

generic CRUD handlers are missing; requests fail or return nothing

always end init() with it

Missing await on a query

query never runs, or runs after commit – "my update is lost"

await every query; lint with no-floating-promises in TypeScript

String concatenation in where

SQL injection risk

objects or tagged templates without ( )

Read status, then update (race)

two managers approve the same request at the same time

conditional UPDATE … where({ ID, status: 'N' }) and check the count, .forUpdate(), or ETags

Throwing plain Error for business rules

HTTP 500, no field highlight

req.reject(4xx, msg, target)

One query per row in after READ

N+1 queries, slow lists

one query with in, or nested projection

Async work in after('each')

handler must be synchronous; promise ignored

after('READ') with await

Calling remote APIs before validation ends

remote side effect although the request fails

validate in before, call remote at the end or via outbox

cds.tx inside handlers out of habit

separate root transaction – not rolled back with the request

use the request transaction; cds.tx only on purpose

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

@requires / @restrict first (page 07)

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 with cds.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