Adding Custom Logic

Define, implement, deploy, and publish services to be consumed from applications, services and UIs.


Add Custom Logic

Overview of Service APIs

All services share a uniform, protocol-agnostic API. For example, local services as well as remote ones, even databases are services and are configured, bound, provided, and consumed in the same uniform ways.

image-20190922230447876 The Service APIs

The figure above highlights the four major APIs: (1) is mostly used during bootstrapping provided services, or when connecting to required ones. (2) and (3) are the synchronous and asynchronous APIs used by consumers to interact with a service. (4) is used to register custom event handlers. The implementations act as clients to other services, for example, reading and writing data from database services.

Event Handlers

Register event handlers to the services you provide. Add domain-specific custom logic not covered by the generic handlers. The easiest way to do so is by providing a service implementation function in an equally named .js file. Placed this file next to the .cds file containing the service definition, for example:


module.exports = cds.service.impl (srv => {

  const {Books} = cds.entities ('my.bookshop')

  // Reduce stock of ordered books
  srv.before ('submitOrder', async (req) => {
    const { amount, book } =
    const tx = cds.transaction(req)
    const affectedRows = await (
      UPDATE (Books) .set ('stock -=', amount)
      .where ('ID=', book, 'and stock >=', amount)
    if (affectedRows == 0)  return req.reject (409, "Sold out, sorry")
    // else insert order here...

  // Add discount to overstocked books
  srv.after ('READ','Books', (each) => {
    if (each.stock > 111)  each.title += ' -- 11% discount!'


See Also …

learn more about how to add event handlers learn more about request objects