Connecting to Required Services
Services frequently consume other services, which could be local services served by the same process, or external services, for example consumed through OData. The latter include database services. In all cases use cds.connect to connect to such services, for example, from your:
Connecting to Required Services
cds. connect.to ()
Use cds.connect.to() to connect to services configured in a project's cds.requires configuration.
const ReviewsService = await cds.connect.to('ReviewsService')The method returns a Promise resolving to a Service instance which acts as a client proxy to the service's API, allowing you to call its methods and access its data using common cds.Service methods, e.g.:
let reviews = await ReviewsService.read ('Reviews')Arguments are as follows:
async function cds.connect.to (
name? : string, // reference to an entry in `cds.requires` config
options? : {
kind : string // reference to a preset in `cds.requires.kinds` config
impl : string // module name of the implementation
}
) : Promise<Service>Argument name is used to look up connect options from configured services, which are defined in the cds.requires section of your package.json or .cdsrc.json or .yaml files.
Argument options also allows to pass additional options such as credentials programmatically, and thus create services without configurations and service bindings, for example, you could connect to a local SQLite database in your tests like this:
const db2 = await cds.connect.to ({
kind: 'sqlite', credentials: { url: 'db2.sqlite' }
})cds. services
When connecting to a service using cds.connect.to(), the service instance is cached in cds.services under the service name. This means that subsequent calls to cds.connect.to() with the same service name will all return the same instance. As services constructed by cds.serve are registered with cds.services as well, a connect finds and returns them as local service connections.
You can also access cached service instance like this:
const { ReviewsService } = cds.servicesNote: If ad-hoc options are provided, the instance is not cached.
Configuring Required Services
To configure required remote services in Node.js, simply add respective entries to the cds.requires sections in your package.json or in .cdsrc.json or .yaml. These configurations are constructed as follows:
{"cds":{
"requires": {
"db": { "kind": "sqlite", "credentials": { "url":"db.sqlite" }},
"ReviewsService": {
"kind": "odata", "model": "@capire/reviews"
},
"OrdersService": {
"kind": "odata", "model": "@capire/orders"
},
}
}}cds:
requires:
db:
kind: sqlite
credentials:
url: db.sqlite
ReviewsService:
kind: odata,
model: @capire/reviews
OrdersService:
kind: odata,
model: @capire/ordersEntries in this section tell the service loader to not serve that service as part of your application, but expects a service binding at runtime in order to connect to the external service provider. The options are as follows:
cds.requires.<srv>.impl
Service implementations are ultimately configured in cds.requires like that:
"cds": { "requires": {
"some-service": { "impl": "some/node/module/path" },
"another-service": { "impl": "./local/module/path" }
}}Given that configuration, cds.connect.to('some-service') would load the specific service implementation from some/node/module/path. Prefix the module path in impl with ./ to refer to a file relative to your project root.
cds.requires.<srv>.kind
As service configurations inherit from each other along kind chains, we can refer to default configurations shipped with @sap/cds, as you commonly see that in our cap/samples, like so:
"cds": { "requires": {
"db": { "kind": "sqlite" },
"remote-service": { "kind": "odata" }
}}This is backed by these default configurations:
"cds": { "requires": {
"sqlite": { "impl": "[...]/sqlite/service" },
"odata": { "impl": "[...]/odata/service" },
}}Run
cds env get requiresto see all default configurations. Runcds env get requires.db.implto see the impl used for your database.
Given that configuration, cds.connect.to('db') would load the generic service implementation.
cds.requires.<srv>.model
Specify (imported) models for remote services in this property. This allows the service runtime to reflect on the external API and add generic features. The value can be either a single string referring to a CDS model source, resolved as absolute node module, or relative to the project root, or an array of such.
"cds": { "requires": {
"remote-service": { "kind": "odata", "model":"some/imported/model" }
}}Upon bootstrapping, all these required models will be loaded and compiled into the effective cds.model as well.
cds.requires.<srv>.service
If you specify a model, then a service definition for your required service must be included in that model. By default, the name of the service that is checked for is the name of the required service. This can be overwritten by setting service inside the required service configuration.
"cds": { "requires": {
"remote-service": { "kind": "odata", "model":"some/imported/model", "service": "BusinessPartnerService" }
}}The example specifies service: 'BusinessPartnerService', which results in a check for a service called BusinessPartnerService instead of remote-service in the model loaded from some/imported/model.
Service Bindings
A service binding connects an application with a cloud service. For that, the cloud service's credentials need to be injected in the CDS configuration:
{
"requires": {
"db": {
"kind": "hana",
"credentials": { /* from service binding */ }
}
}
}cds.requires.<srv>.credentials
All service binding information goes into this property. It's filled from the process environment when starting server processes, managed by deployment environments. Service bindings provide the details about how to reach a required service at runtime, that is, providing requisite credentials, most prominently the target service's url.
You specify the credentials to be used for a service by using one of the following:
- Process environment variables
- Command line options
- File system
- Auto binding
For example, in development, you can add them to a .env file as follows:
# .env file
cds.requires.remote-service.credentials = { "url":"http://...", ... }❗ Never add secrets or passwords to package.json or .cdsrc.json!
General rule of thumb: .credentials are always filled (and overridden) from process environment on process start.
Basic Mechanism
The CAP Node.js runtime expects to find the service bindings in cds.env.requires.
Configured required services constitute endpoints for service bindings.
json"cds": { "requires": { "ReviewsService": {...}, } }These are made available to the runtime via
cds.env.requires.jsconst { ReviewsService } = cds.env.requiresService Bindings essentially fill in
credentialsto these entries.jsconst { ReviewsService } = cds.env.requires ReviewsService.credentials = { url: "http://localhost:4005/reviews" }
The latter is appropriate in test suites. In productive code, you never provide credentials in a hard-coded way. Instead, use one of the options presented in the following sections.
In Cloud Foundry
Find general information about how to configure service bindings in Cloud Foundry:
- Deploying Services using MTA Deployment Descriptor
- Binding Service Instances to Cloud Foundry Applications
- Binding Service Instances to Applications using the Cloud Foundry CLI
Cloud Foundry uses auto configuration of service credentials through the VCAP_SERVICES environment variable.
Learn more about environment variables on Cloud Foundry and cf env.
Through VCAP_SERVICES env var
When deploying to Cloud Foundry, service bindings are provided in VCAP_SERVICES process environment variables, which is JSON-stringified array containing credentials for multiple services. The entries are matched to the entries in cds.requires as follows, in order of precedence:
- The service's
nameis matched against thenameproperty ofVCAP_SERVICEentries - The service's
nameis matched against thebinding_nameproperty - The service's
nameis matched against entries in thetagsarray - The service's
kindis matched against entries in thetagsarray - The service's
kindis matched against thelabelproperty, for example, 'hana' - The service's
kindis matched against thetypeproperty (The type property is only relevant for servicebinding.io bindings) - The service's
vcap.nameis matched against thenameproperty
All the config properties found in the first matched entry will be copied into the cds.requires.<srv>.credentials property.
Here are a few examples:
| CAP config | VCAP_SERVICES |
|---|---|
json | json |
json | json |
json | json |
If the vcap configuration contains multiple properties such as name, label, tags, plan, all properties have to match the corresponding VCAP_SERVICE attributes:
| CAP config | VCAP_SERVICES |
|---|---|
json | json |
CAP services often come with a default vcap configuration. In rare cases, the default configuration has to be deactivated which can be achieved by explicitly setting the service property vcap.<property> to false:
| CAP config | VCAP_SERVICES |
|---|---|
json | json |
To see the default configuration of a CAP service, use:
cds env get requires.<servicename>In Kubernetes / Kyma
CAP supports servicebinding.io service bindings and SAP BTP service bindings created by the SAP BTP Service Operator.
Specify a root directory for all service bindings using
SERVICE_BINDING_ROOTenvironment variable:yamlspec: containers: - name: bookshop-srv env: # ... - name: SERVICE_BINDING_ROOT value: /bindingsCreate service bindings
Use the
ServiceBindingcustom resource of the SAP BTP Service Operator to create bindings to SAP BTP services:yamlapiVersion: services.cloud.sap.com/v1alpha1 kind: ServiceBinding metadata: name: bookshop-xsuaa-binding spec: serviceInstanceName: bookshop-xsuaa-binding externalName: bookshop-xsuaa-binding secretName: bookshop-xsuaa-secretBindings to other services need to follow the servicebinding.io workload projection specification.
Mount the secrets of the service bindings underneath the root directory:
yamlspec: containers: - name: bookshop-srv # ... volumeMounts: - name: bookshop-auth mountPath: "/bindings/auth" readOnly: true volumes: - name: bookshop-auth secret: secretName: bookshop-xsuaa-secretThe
secretNameproperty refers to an existing Kubernetes secret, either manually created or by theServiceBindingresource. The name of the sub directory (authin the example) is recognized as the binding name.
CAP services receive their credentials from these bindings as if they were provided using VCAP_SERVICES.
Through environment variables
All values of a secret can be added as environment variables to a pod. A prefix can be prepended to each of the environment variables. To inject the values from the secret in the right place of your CDS configuration, you use the configuration path to the credentials object of the service as the prefix:
cds_requires_<your service>_credentials_
Please pay attention to the underscore ("_") character at the end of the prefix.
Example:
spec:
containers:
- name: app-srv
# ...
envFrom:
- prefix: cds_requires_db_credentials_
secretRef:
name: app-dbWARNING
For the configuration path, you must use the underscore ("_") character as delimiter. CAP supports dot (".") as well, but Kubernetes won't recognize variables using dots. Your service name mustn't contain underscores.
Through the file system
CAP can read configuration from a file system by specifying the root path of the configuration in the CDS_CONFIG environment variable.
Set CDS_CONFIG to the path that should serve as your configuration root, for example: /etc/secrets/cds.
Put the service credentials into a path that is constructed like this:
<configuration root>/requires/<your service>/credentials
Each file will be added to the configuration with its name as the property name and the content as the value. If you have a deep credential structure, you can add further sub directories or put the content in a file as a JSON array or object.
For Kubernetes, you can create a volume with the content of a secret and mount it on your container.
Example:
spec:
volumes:
- name: app-db-secret-vol
secret:
secretName: app-db
containers:
- name: app-srv
# ...
env:
- name: CDS_CONFIG
value: /etc/secrets/cds
volumeMounts:
- name: app-db-secret-vol
mountPath: /etc/secrets/cds/requires/db/credentials
readOnly: trueProvide Service Bindings (VCAP_SERVICES)
If your application runs in a different environment than Cloud Foundry, the VCAP_SERVICES env variable is not available. But it may be needed by some libraries, for example the SAP Cloud SDK.
By enabling the CDS feature features.emulate_vcap_services, the VCAP_SERVICES env variable will be populated from your configured services.
For example, you can enable it in the package.json file for your production profile:
{
"cds": {
"features": {
"[production]": {
"emulate_vcap_services": true
}
}
}
}WARNING
This is a backward compatibility feature.
It might be removed in a next major CAP version.
Each service that has credentials and a vcap.label property is put into the VCAP_SERVICES env variable. All properties from the service's vcap object will be taken over to the service binding.
The vcap.label property is pre-configured for some services used by CAP.
For example, for the XSUAA service you only need to provide credentials and the service kind:
{
"requires": {
"auth": {
"kind": "xsuaa",
"credentials": {
"clientid": "cpapp",
"clientsecret": "dlfed4XYZ"
}
}
}
}The VCAP_SERVICES variable is generated like this:
{
"xsuaa": [
{
"label": "xsuaa",
"tags": [ "auth" ],
"credentials": {
"clientid": "cpapp",
"clientsecret": "dlfed4XYZ"
}
}
]
}The generated value can be displayed using the command:
cds env get VCAP_SERVICES --process-envA list of all services with a preconfigured vcap.label property can be displayed with this command:
cds env | grep vcap.labelYou can include your own services by configuring vcap.label properties in your CAP configuration.
For example, in the package.json file:
{
"cds": {
"requires": {
"myservice": {
"vcap": {
"label": "myservice-label"
}
}
}
}
}The credentials can be provided in any supported way. For example, as env variables:
cds_requires_myservice_credentials_user=test-user
cds_requires_myservice_credentials_password=test-passwordThe resulting VCAP_SERVICES env variable looks like this:
{
"myservice-label": [
{
"label": "myservice-label",
"credentials": {
"user": "test-user",
"password": "test-password"
}
}
]
}Through .cdsrc-private.json File for Hybrid Testing
Learn more about hybrid testing using .cdsrc-private.json.
{
"requires": {
"ReviewsService": {
"credentials": {
"url": "http://localhost:4005/reviews"
}
},
"db": {
"credentials": {
"url": "db.sqlite"
}
}
}
}WARNING
Make sure that the .cdsrc-private.json file is not checked into your project.
Through process.env Variables
You could pass credentials as process environment variables, for example in ad-hoc tests from the command line:
export cds_requires_ReviewsService_credentials_url=http://localhost:4005/reviews
export cds_requires_db_credentials_database=sqlite.db
cds watch fioriIn .env Files for Local Testing
Add environment variables to a local .env file for repeated local tests:
cds.requires.ReviewsService.credentials = { "url": "http://localhost:4005/reviews" }
cds.requires.db.credentials.database = sqlite.dbNever check in or deploy such .env files!