Defining Services in SAP CAP

by | Mar 12, 2020 | SAP CAP

Home » SAP » SAP CAP » Defining Services in SAP CAP

Preface – This post is part of the SAP CAPM series.

Introduction

A service or a metadata service is used to define the data and its structure. It includes all the data models with annotation as well as associations and navigations. In this article we will explore more about Defining Services in SAP CAP.

Defining Services in SAP CAP

In CAP, we have already defined multiple entities with association. Later we have added annotations too using Aspects. In service definition, we write all the entities within another entity and give it the name of a service. Here we have created a service in file “service.cd”.

entity EmployeeService {
enity Employee {
key ID : UUID;
name  : String;
Role : Association to Manager;
}
entity Manager {
key ID : UUID;
name   : String;
Role  : Association to many Role on Employee.Manager = $self;
}
}

 

To separate the entity sets from the service, unlike the example mentioned above, we will call the domain modals in our services. Hence, all the models will be as usual defined within a model cds e.g.  schema.cds and then it would be called from a Service using CQL (CAP Query Language).

Example:

using { empInfo as info } from 'db/schema';


entity EmployeeService{


entity Employee as SELECT from info.Employees{ *,
Employees.firstname ||' '|| Employees.lastname as name : String,
manager.name as manager,
} excluding { salary, currency};
entity Manager as projection on empInfo.Manager
where Manager.Department = 'IT'
order by name;
}

 

It is recommended to use one service per use case. It helps us to maintain proper authentication and checks.

Example:

using { empInfo as info } from './db/schema';
/** Serves end users browsing Employee and Insert Employee Details */ 
service EmployeeService{
@readonly  entity Employee as SELECT from info.Employees{ *,
firstName, lastname
};
@requires: 'authenticated-user'@insertonly entity Salary as projection on info.Salary;


}
/** Serves registered users managing their salary and leave */
service UsersService {
@readonly entity Salary as projection on info.Salary
where EmployeeID = $user; // limit to own ones
action cancelLeave ( ID: Salary.ID, reason:String );
}


/** Serves administrators managing everything */
@requires: 'authenticated-user'
service AdminService {  entity Employee   as projection on info.Employees;
entity Salary as projection info.Salary;
}

 

Author

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Author