cancel
Showing results for 
Search instead for 
Did you mean: 

CAP Services with dynamic datasource

peter_benicky
Associate
Associate
0 Kudos

Hello all,

we are using CAP service however we would like to change dynamically the datastore where data are located.
example:
HDI1: tableA
HDI2: tableA

in our CAP service we have defined entity for table A as cds.persistence.exists true annotation. We would like to have a service:

service api {
entity Aservice as projection on A;
}
and within 
this.on('*', async (_req, next) => {
we call getHanaParams and we would like to use the defined service above but using the HANA container returned by getHanaParams.
Note: we are not using multitenant approach.
Thanks Regards Peter



 

Accepted Solutions (0)

Answers (1)

Answers (1)

peter_benicky
Associate
Associate
0 Kudos

I have tried below code, looks like it is working properly:

module.exports = class TestService extends cds.ApplicationService {
  async init() {
    this.on('*', async (_req) => {
      let db:cds.Service;
      if (!cds.env?.requires[envJson.schema]) {
        cds.env.requires[envJson.schema] = {}
        // Here we will get HANA container credentials from MDS service and connect to it        
        db = await cds.connect.to(envJson.schema, { kind: "hana", impl: "@sap/cds-hana", credentials: envJson });
      } else {
        db = cds.services[envJson.schema];
      }
      return await db.run(_req.query);
  });

    return super.init() ;
  }
};