Coder Social home page Coder Social logo

sap / cloud-sdk-js Goto Github PK

View Code? Open in Web Editor NEW
159.0 17.0 50.0 110.34 MB

Use the SAP Cloud SDK for JavaScript / TypeScript to reduce development effort when building applications on SAP Business Technology Platform that communicate with SAP solutions and services such as SAP S/4HANA Cloud, SAP SuccessFactors, and many others.

License: Apache License 2.0

JavaScript 0.42% TypeScript 26.65% CAP CDS 0.04% Dockerfile 0.01% CSS 0.32% HTML 72.57%
sap-cloud-sdk sap-cloud-platform sap-business-technology-platform sap-btp odata openapi

cloud-sdk-js's Introduction

SAP Cloud SDK for JavaScript Logo

build REUSE status Fosstars security rating

SAP Cloud SDK

An SDK to reduce your development effort when building side-by-side extension applications on SAP Business Technology Platform that integrate with SAP solutions and services such as SAP S/4HANA, SAP SuccessFactors, and many others.

Announcement - Upgrade Strategy

We have released version 3 of the SAP Cloud SDK for JavaScript on npm. Check out the upgrade guide for detailed instructions. The upgrade effort should be around 1 day for an average project and should not take more than a week for larger projects.

It is recommended to upgrade to version 3 as version 2.x will not be actively maintained, with the exception of critical security vulnerabilities for up to 6 months.

Please share your ideas, suggestions or improvements in our GitHub discussion.

Looking for documentation?

Check our API documentation and getting started guide on our documentation portal.

Table of Contents

Packages

This project publishes multiple packages and is managed using turborepo.

@sap-cloud-sdk/http-client

This package contains the generic http-client functionality with built-in connectivity with executeHttpRequest(). The generic http-client adds SAP infrastructure specific functionality on top of a standard HTTP Client.

To install the SAP Cloud SDK http-client in your project, run:

$ npm install @sap-cloud-sdk/http-client

@sap-cloud-sdk/connectivity

This package contains all Cloud Foundry connectivity service related methods like getDestination() and registerDestination().

To install the SAP Cloud SDK conectivity in your project, run:

$ npm install @sap-cloud-sdk/connectivity

@sap-cloud-sdk/odata-v2

This package contains all OData version 2 specific functionality, like the request builders for create/update operations, predefined filter functions, batch. Package @sap-cloud-sdk/odata-v4 contains the same functionality for OData verison 4.

To install the SAP Cloud SDK odata-v2 in your project, run:

$ npm install @sap-cloud-sdk/odata-v2

Similarly, to install the SAP Cloud SDK odata-v4, use:

$ npm install @sap-cloud-sdk/odata-v4

@sap-cloud-sdk/generator

The SAP Cloud SDK generator is a command line interface (CLI) that allows you to create clients for your own OData services or other SAP systems besides SAP S/4HANA based on their service specifications.

To install the SAP Cloud SDK generator in your project, run:

$ npm install @sap-cloud-sdk/generator

@sap-cloud-sdk/test-util

The test-util package makes writing tests for your SAP Business Technology Platform application more convenient.

To install the SAP Cloud SDK test-util as development dependencies in your project, run:

$ npm install -D @sap-cloud-sdk/test-util

How to switch to the Open Source version of the SAP Cloud SDK

Please ignore this section, if you have never used the SAP Cloud SDK with a version < 1.18.0. If you are using an old version of the SAP Cloud SDK, you might want to read how to migrate to this Open Source version of the SAP Cloud SDK.

Related Projects

SAP Cloud SDK CLI

The SAP Cloud SDK command line interface (CLI) is deprecated. We have provided sample projects with example applications to show how you can integrate the SAP Cloud SDK into your projects.

SAP Cloud SDK Sample Projects

We have created multiple sample projects which showcase the use of the SAP Cloud SDK for TypeScript/JavaScript in different scenarios. Each project outlines the configurations needed to execute it locally and to deploy the project to SAP Business Technology Platform.

Virtual Data Model (VDM)

In addition to the Open Source parts of this project, we also publish the SAP Cloud SDK Virtual Data Model (VDM) - JavaScript / TypeScript clients for the latest versions of the published OData services of SAP S/4HANA Cloud under the SAP Developer license. Those are not included in this project, but rely on modules from this project.

To install an OData client for an SAP S/4HANA service run:

$ npm install @sap/cloud-sdk-vdm-<service name>-service

In the example above, service name is the name of the service you want to use, e. g. for the business partner service, run: npm install @sap/cloud-sdk-vdm-business-partner-service.

Project "Piper"

Continuous delivery is a method to develop software with short feedback cycles. It is applicable to projects both for SAP Business Technology Platform and SAP on-premise platforms. SAP implements tooling for continuous delivery in the open-source project "Piper". The goal of project "Piper" is to substantially ease setting up continuous delivery in your project using SAP technologies.

Feedback

Feel free to leave your feedback in form of GitHub issues for bugs and feature requests. If you have broader questions, we are active on StackOverflow too.

Contribute

Want to contribute? Check out our contribution guide and follow our code of conduct.

Links

License

This project is licensed under the terms of the Apache 2.0 license as noted in the license file.

This project depends on libraries licensed under the SAP Developer license agreement. This limits the use of those dependencies to development purposes only.

cloud-sdk-js's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cloud-sdk-js's Issues

Generator: TypeScript error for required properties in complex types

Description
Complex types with non-nullable properties seem to lead to TypeScript type errors when working with the @sap-cloud-sdk/generator version 1.25.0. This did not occur with version 1.24.0.

To Reproduce

  1. Get the EDMX-specification for the Attachments ODATA API from SAP S/4HANA Cloud Package: https://api.sap.com/api/API_CV_ATTACHMENT_SRV/overview.

  2. Generate a service module from this specification using the @sap-cloud-sdk/generator version 1.25.0. You can, for instance, follow these steps or this introduction.
    generate-odata-client --inputDir specifications --outputDir generator-modules

  3. Use the generated TypeScript service module in a TypeScript project (e.g. import it in a file index.ts):
    import * as attachmentService from './generator-modules/cv-attachment-service';

  4. Transpile the project code to JavaScript.
    tsc index.ts

  5. Result: There is an error message indicating missing required properties.
    grafik
    These steps work for other specification files containing complex types with required properties as well.

Expected behavior
The service module should transpile without errors.

Used Versions:

  • node version: 10.19.0
  • npm version: 6.14.1
  • SAP Cloud SDK: 1.25.0
  • TypeScript: 3.9.6

Did I miss something? Is there a workaround?

Many thanks in advance and best regards,
ja-ne

Error while creating a project with sap-cloud-sdk init

I'm trying to initialize a project with sap-cloud-sdk init
It's giving the following error:

sap-cloud-sdk init test
The target directory (test) does not contain a package.json.
Should a new nest.js project be initialized in the target directory? (y|n): y
Building application scaffold... !
» Error: Command failed with exit code 1: npx -p @nestjs/cli nest new . --skip-install --package-manager npm

To Reproduce
sap-cloud-sdk init test

Expected behavior
It should create a project template

Used Versions:
@sap-cloud-sdk/cli/0.1.9 win32-x64 node-v12.16.1

The manual OData call to C4C works fine, while same call via SDK doesn't

Describe the bug

Querying IndividualCustomers from C4C
To do this we tried out two variations:
1. Querying the ODATA API directly using a lambda function in Kyma (see file get-indiv-customers.js). Using the $expand syntax it is possible to list all the current customer’s addresses, i.e. this works as expected (see file response-indiv-customers-native.json)
2. Using the CloudSDK to query C4C. In this case the syntax is slightly different (see file get-indiv-customers-sdk.js). In this case we always get back an empty array of addresses, even if the IndividualCustomer has addresses in C4C (see file response-indiv-customers-sdk.json). We observe this behavior for all of the IndividualCustomer child entities we have tested.

Thanks for your help!

To Reproduce
Please note that to use the Cloud SDK Nazar has set up a node.js module which is installed as a dependency in the lambda function. The library he set up is available at https://github.com/PTA-Kyma/pta-kyma-c4-odata.git (to install: @nazarkulyk/pta-kyma-c4-odata)

Expected behavior
The call returns data with Expand

Used Versions:
We'll

Code Examples
If applicable, add code snippets as examples to help explain your problem. Please remove sensitive information as it will be shown in the internet.

Currency Conversion - Issues with building docu locally

I followed the steps described here to clone the SDK documentation. I was able to access the files and create a PR. However, ever since I have signed the CLA, I am unable to build the documentation locally by using npm install and npm start,

Important information:
Here's the code for npm install:

C:\Users\I333344\git\cloud-sdk>npm install
npm WARN @docusaurus/[email protected] requires a peer of @docusaurus/core@^2.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN @docusaurus/[email protected] requires a peer of @docusaurus/core@^2.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN @docusaurus/[email protected] requires a peer of @docusaurus/core@^2.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN @docusaurus/[email protected] requires a peer of @docusaurus/core@^2.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN @docusaurus/[email protected] requires a peer of @docusaurus/core@^2.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN @docusaurus/[email protected] requires a peer of @docusaurus/core@^2.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN @docusaurus/[email protected] requires a peer of @docusaurus/core@^2.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN @docusaurus/[email protected] requires a peer of @docusaurus/[email protected] but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of typescript@>=2.8.0 || >= 3.2.0-dev || >= 3.3.0-dev || >= 3.4.0-dev || >= 3.5.0-dev || >= 3.6.0-dev || >= 3.6.0-beta || >= 3.7.0-dev || >= 3.7.0-beta but none is installed. You must install peer dependencies yourself.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\webpack-dev-server\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\watchpack-chokidar2\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

audited 2021 packages in 16.664s

165 packages are looking for funding
run npm fund for details

found 0 vulnerabilities

When I do npm start, I get some 78 rejection ids.

Impact / Priority
It isn't critical since I can see the file changes on my PR but I would like to see an actual preview since there is some docusaurus formatting as well, which I want to check for correctness.

Affected development phase: Release

Impact: Impaired

**Timeline:
Local Host Build.txt
** GoLive ASAP

Project Details
Currency Conversion Library on Cloud SDK. The file in which the content was to be added was already created for us. We only edited the relevant file.

Bug with a generated service containing the "Moment" import

Describe the bug
There is a problem with a generated service containing the "Moment" import

To Reproduce
Steps to reproduce the behavior:

git clone https://github.com/CharlesDuboisSAP/cloud-sdk-team-calendar.git
git pull origin fix
git chekout fix
npm install

place the time-off edmx in the generator-input folder

npm run generate

open src\generated\ec-time-off-service\HolidayAssignmentRequestBuilder.ts

Expected behavior
no errors inside my generated service

Screenshots

the problematic file
image

the error
image

GetByKeyRequestBuilder anf FieldType
image

Used Versions:

  • node version v12.18.0
  • npm version 6.14.4
  • SAP Cloud SDK version 1.26.1

everything but cds stuff was updated:

 @sap/cds                                          ^3.13.0  →   ^4.1.5 
 @sap/cds-services                                  1.14.0  →   1.27.1 
 @sap-cloud-sdk/core                               ^1.18.0  →  ^1.26.1
 @sap/cloud-sdk-vdm-workforce-timesheet-service    ^1.18.0  →  ^1.19.2
 @sap/hdi-deploy                                     3.7.x  →   3.11.x
 express                                           ^4.16.4  →  ^4.17.1
 hdb                                               ^0.17.0  →  ^0.18.1
 ts-node                                            ^8.0.3  →  ^8.10.2
 typescript                                      ^3.3.4000  →   ^3.9.7
 @sap-cloud-sdk/generator                          ^1.18.0  →  ^1.26.1
 @types/chai                                        ^4.2.0  →  ^4.2.12
 @types/express                                    ^4.16.1  →  ^4.17.7
 @types/mocha                                       ^5.2.6  →   ^8.0.1
 @types/sinon                                      ^7.0.13  →   ^9.0.4
 @types/sinon-chai                                  ^3.2.3  →   ^3.2.4
 chai-http                                          ^4.2.1  →   ^4.3.0
 dotenv                                             ^8.0.0  →   ^8.2.0
 js-yaml                                           ^3.13.0  →  ^3.14.0
 mocha                                              ^5.2.0  →   ^8.1.1
 mocha-junit-reporter                              ^1.18.0  →   ^2.0.0
 node-mocks-http                                    ^1.7.3  →   ^1.8.1
 nodemon                                          ^1.18.10  →   ^2.0.4
 nyc                                               ^15.0.0  →  ^15.1.0
 sinon                                              ^7.4.1  →   ^9.0.2
 sinon-chai                                         ^3.3.0  →   ^3.5.0
 sqlite3                                            ^4.0.7  →   ^5.0.0

Log file

± |fix U:2 ?:3 ✗| → npm run ci-build
> [email protected] ci-build /home/i531196/dev/tmp/cloud-sdk-team-calendar
> npx tsc && npm run cds-deploy:local && cp -r src/app db srv dist/
src/generated/ec-time-off-service/HolidayAssignmentRequestBuilder.ts:23:7 - error TS2322: Type 'Moment' is not assignable to type 'FieldType'.
  Property 'isoWeeksInISOWeekYear' is missing in type 'import("/home/i531196/dev/tmp/cloud-sdk-team-calendar/node_modules/moment/moment").Moment' but required in type 'moment.Moment'.
23       date: date
         ~~~~
  node_modules/@sap-cloud-sdk/core/node_modules/moment/ts3.1-typings/moment.d.ts:549:5
    549     isoWeeksInISOWeekYear(): number;
            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    'isoWeeksInISOWeekYear' is declared here.
  node_modules/@sap-cloud-sdk/core/node_modules/@sap-cloud-sdk/util/dist/types.d.ts:5:5
    5     [key: string]: T;
          ~~~~~~~~~~~~~~~~~
    The expected type comes from this index signature.
Found 1 error.
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! [email protected] ci-build: `npx tsc && npm run cds-deploy:local && cp -r src/app db srv dist/`
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the [email protected] ci-build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR!     /home/i531196/.npm/_logs/2020-08-06T13_50_55_727Z-debug.log

Please check the following points

  • Have you provided detailed description about your issue?
  • Have you shared all the necessary information to help the cloud-sdk developer reproduce the issue?
  • Have you provided the expected behaviour?
  • Have you attached some useful screenshots?
  • Have you provided the node/npm/cloud-sdk versions?
  • Have you shared your code snippets as a minial example?
  • Have you provided you log file or related error messages?
  • Have you searched for related issues on Stackoverflow or answers.sap.com?

Changing log format doesn't work

I’ve created a new project from scratch using the SAP Cloud SDK archetype. In the project the logback.xml file is configured as this:
01
If I run the project I see the following log:
02
Now I would like to change the log format and for this reason I slightly modified the logback.xml file as this:
03
Unfortunately, running the app again I still see the same log. It seems that the logback.xml file is not taken into account.
04
Is there anything missing?
Simmaco

Error using sap-cloud-sdk with vue.js (process.on is not a function)

Hey guys,
I'm currently evaluating several odata-clients for vue.js and encountered the following problem using the cloud-sdk for js.

My test-repository:
https://github.com/nexzgg/vue3-typescript

The Problem:
I generated my odata-client from an odata-metadata.xml (like u can see in the picture)
image

Afterwards i tried to show some data within a table.
image

The Problem is, i always run into this error.
image

I found out that the node-module "node-libs-browser" is used somewhere in the backround from cloud-sdk-logger.js and process.on is not defined here.
image

Am i doing something wrong or is this a bug?

Kind regards,
Julian.

Batch Csrf token error

We are facing issues using the cloud sdk to access an on premise system through the cloud connector.

The first request (to fetch the x-csrf-token) returns without a body and causes an error and the actual post never happens.

If I fetch the token myself I am able to pass it in the batch as a header.

The get request needs to be able to handle an empty body.

an easy way to reproduce it is to use
executeHttpRequest() and only pass the odata service (without an entity in the url)

a simple get request should fail.
kind regards

David

generate-odata-client cause uncaughtException: Cannot find module 'execa'

After update to 1.29.0 version i get an error on generating odata client localy with npm.

Steps to reproduce the behavior:

  1. create package.json like that:
{
  "name": "xxx",
  "version": "1.0.4",
  "private": true,
  "dependencies": {
    "@sap-cloud-sdk/core": "^1.29.0",
    "@sap-cloud-sdk/generator": "^1.29.0"
  },
  "scripts": {
    "generate": "generate-odata-client -i service --outputDir ./ --versionInPackageJson=1.0.4 --forceOverwrite"
  },
  "devDependencies": {},
  "engines": {
    "node": "^12.14.0",
    "npm": "^6.14.0"
  }
}
  1. execute npm i && npm run generate
  2. See error
2020-10-08T08:46:31.343Z] ERROR    uncaughtException: Cannot find module 'execa'
Require stack:
- /Users/odata-example/node_modules/@sap-cloud-sdk/generator/dist/generator.js
- /Users/odata-example/node_modules/@sap-cloud-sdk/generator/dist/generator-cli.js
Error: Cannot find module 'execa'
Require stack:
- /Users/odata-example/node_modules/@sap-cloud-sdk/generator/dist/generator.js
- /Users/odata-example/node_modules/@sap-cloud-sdk/generator/dist/generator-cli.js
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:902:15)
    at Function.Module._load (internal/modules/cjs/loader.js:747:27)
    at Module.require (internal/modules/cjs/loader.js:974:19)
    at require (internal/modules/cjs/helpers.js:88:18)
    at Object.<anonymous> (/Users/odata-example/node_modules/@sap-cloud-sdk/generator/dist/generator.js:47:13)
    at Module._compile (internal/modules/cjs/loader.js:1085:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
    at Module.load (internal/modules/cjs/loader.js:950:32)
    at Function.Module._load (internal/modules/cjs/loader.js:791:14)
    at Module.require (internal/modules/cjs/loader.js:974:19)

Workarround is to add execa to dependencies. But please correct this dependancy on generator package

"dependencies": {
    "execa": "^4.0.3",
    "@sap-cloud-sdk/core": "^1.29.0",
    "@sap-cloud-sdk/generator": "^1.29.0"
  }

Generator: Deprecated nested dependencies

Npm warns about two deprecated packages associated with @sap/edm-converters which is a dependency of @sap-cloud-sdk/generator:

npm WARN deprecated [email protected]: request has been deprecated, see https://github.com/request/request/issues/3142
npm WARN deprecated [email protected]: this library is no longer supported

Is there something that can be done about this?

I know this may not be the most suitable place for this question but the only one I could think of since I could not find contact information for @sap/edm-converters.

Thanks in advance.

Can cloud-sdk be used on the client side, e.g. in an Angular application?

When I add "@sap-cloud-sdk/core" to an Angular project it fails to compile, missing a bunch of libraries, such as "Can't resolve 'tls' " needed for @sap/xsenv/lib.

Other missing modules are e.g. 'fs', 'http', 'https', which leads me to thinking, this library is only for the backend / node.js environment.

Is using this SDK in a frontend app a supported scenario at all?

Cannot read property 'split' of undefined when running generator for SAP Business One Service Layer Metadata

Describe the bug

In the branch collection-issue of my test project sap-business-one-odata-cap I've added "@sap-cloud-sdk/generator": "^1.21.1" and the script:

generate-odata-client --inputDir srv/external --outputDir srv/odata-client --forceOverwrite

but when running this script I get the following error:

(node:39117) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'split' of undefined
    at /Users/gwolf/Documents/Projects/cap/sap-business-one-odata-cap/node_modules/@sap-cloud-sdk/generator/dist/parser/service-parser.js:395:49
    at Array.map (<anonymous>)
    at navigationProperties (/Users/gwolf/Documents/Projects/cap/sap-business-one-odata-cap/node_modules/@sap-cloud-sdk/generator/dist/parser/service-parser.js:394:49)
    at /Users/gwolf/Documents/Projects/cap/sap-business-one-odata-cap/node_modules/@sap-cloud-sdk/generator/dist/parser/service-parser.js:329:35
    at Array.map (<anonymous>)
    at transformEntities (/Users/gwolf/Documents/Projects/cap/sap-business-one-odata-cap/node_modules/@sap-cloud-sdk/generator/dist/parser/service-parser.js:323:21)
    at transformServiceMetadata (/Users/gwolf/Documents/Projects/cap/sap-business-one-odata-cap/node_modules/@sap-cloud-sdk/generator/dist/parser/service-parser.js:76:19)
    at parseService (/Users/gwolf/Documents/Projects/cap/sap-business-one-odata-cap/node_modules/@sap-cloud-sdk/generator/dist/parser/service-parser.js:46:12)
    at /Users/gwolf/Documents/Projects/cap/sap-business-one-odata-cap/node_modules/@sap-cloud-sdk/generator/dist/parser/service-parser.js:39:16
    at Array.map (<anonymous>)
(node:39117) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
(node:39117) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

To Reproduce
Steps to reproduce the behavior:

  1. checkout the branch collection-issue
  2. run npm i
  3. run npm run generate-odata-client
  4. See error

Expected behavior
Also the SAP Business One Service Layer Metadata should be supported.

Used Versions:

  • node version v12.16.1
  • npm version 6.14.5
  • SAP Cloud SDK version 1.21.1

OData $count operation

Hello there,
wouldn't be nice to implement the count() operation for VDM entities?
Although for server pagination this might not be required, the total count of entity values is very much useful in many other scenarios, especially in UIs that require table paging.

Best option will be to implement the count() method in the requestBuilder, so that it can be used as fluently as other API methods (top, skip, filter, etc).

As of now, the count can be easily obtained by shooting a separated http call for the required entity, and appending $count parameter to the call.

All the best,
Roberto.

Calling function import from SAP Cloud SDK returns an empty object

Describe the bug
Calling a function import from SAP Cloud SDK returns an empty object, even though the call is successful.
You can reproduce the issue by using the following git repository.
https://github.com/miyasuta/sdk-function-import-test

To Reproduce
Steps to reproduce the behavior:

  1. Develop a custom odata service which includes a function import.
  2. In a Cloud SDK app, generate an odata client using below command as explained here.
    sap-cloud-sdk generate-odata-client -i service-specification/ -o odata-client/
  3. Call the function import from the Cloud SDK app.
  4. When the function import gets called, it falls into then() block, meaning that the call was successful.
    However, the response object is empty.

Expected behavior
Response object should be filled with returned data.

Screenshots
Calling the OData function import directly
image

Calling function import from Cloud SDK app (delivery data should be returned between {})
image

Used Versions:

  • node version via node -v: 12.16.1
  • npm version via npm -v: 6.14.4
  • SAP Cloud SDK version you used as dependency: 1.31.0

Code Examples
My controller code is as below.

import { Controller, Get } from '@nestjs/common';
import { functionImports } from 'odata-client/catalog-service';


@Controller('get-delivery')
export class GetDeliveryController {
    @Get()
    getDeliveryInfo() {
        return new Promise((resolve, reject) => {
            functionImports.getDeliveryDate({})
            .execute({
                url: 'http://localhost:4004'                
            })
            .then(res => {
                resolve('Function call successful: ' + JSON.stringify(res))
            })
            .catch(error => {
                resolve('Error occurred: ' + JSON.stringify(error))
            })
        })
    }
}

Log file
No error has occurred.

Additional context
None

Please check the following points

  • [X ] Have you provided detailed description about your issue?
  • [X ] Have you shared all the necessary information to help the cloud-sdk developer reproduce the issue?
  • [ X] Have you provided the expected behaviour?
  • [ X] Have you attached some useful screenshots?
  • [ X] Have you provided the node/npm/cloud-sdk versions?
  • [ X] Have you shared your code snippets as a minial example?
  • Have you provided you log file or related error messages?
  • [ X] Have you searched for related issues on Stackoverflow or answers.sap.com?

How to do deep insert function with Cloud SDK (Upsert / Batch)

Hi Expert,

I have a requirement to create a Success Factor extension with SAP UI5 (frontend) + nodejs (middleware) + SF api (data model). 
After we have spoken to SAP expert, to ease all the necessary steps to perform "Principle Propogation" with beare token call from Success Factor -> Sap Cloud Platform (Cloud Foundry) -> Propagate to RESTFUL services (via api call) hosted in CF, the authorisation is called via Success Factor => SAP IAS server. 

What I have done is to download the OData definition (EDMX file) from API Hub and generated the functions via the npx generate-odata-client --inputDir service-specs --outputDir generated --forceOverwrite command. The system is generated correctly.

We are currently able to follow most of the tutorial from https://sap.github.io/cloud-sdk/docs/js/features/odata/overview for both "C" - Post, "R" - Get, "U" - Put and "D" - Delete accordingly. But when we tried to follow the example given in the blog for Batch Requests# ( retrieve requests and changesets ) , we are not able to follow as the batch and changeset function is not defined in our generated class. Can you kindly advice is there anywhere which we can do "UPSERT" or "BATCH" function using SDK ? and if you can provide some example, it will be great help.

Example of batch and changeset for businessPartnerAddress (sample) but this is not generated as part of the npx generate command.

updateAddresses(businessPartnerAddresses: BusinessPartnerAddress[])
:Promise<BusinessPartnerAddress[]> {
const updateRequests = businessPartnerAddresses.map(
address => BusinessPartnerAddress
.requestBuilder()
.update(address)
);

const [updateChangesetResponse] = await batch(changeset(...updateRequests))
.execute(destination);

return (updateChangesetResponse as WriteResponses)
.responses
.map(
response => response.as(BusinessPartnerAddress)
);
}

Authorization error at consumption of the on-premise odata service (cloud-sdk for js)

Describe the bug
Authorization error at consumption of the on-premise odata service in a cap application deployed to the SAP CF live tenant that uses the custom odata client library generated by the cloud sdk generator via the "DestinationNameAndJwt" interface.

To Reproduce
Steps to reproduce the behavior:

  1. Set up:
  • a cap app to read data from the external on-premise odata service;
  • approuter
  • express.js in the srv module - to pass a user jwt to a handler of a sevice provider in the cap app
  • odata client library generated by the cloud sdk generator
  • uaa service
  • destination service
  • connectivity service
  • destination to the on-premise system with the Basic authentication
  • cloud connector in the CF env to the SAP internal on-premise system
  1. Execute
    const osEntity = await sdkEntity.requestBuilder().getAll().execute({ destinationName: destinationName, jwt: userToken })

  2. Confirm ...
    DestinationNameAndJwt_debug_1
    DestinationNameAndJwt_debug_3
    DestinationNameAndJwt_debug_2
    DestinationNameAndJwt_debug_1

  3. See error
    Error: Request failed with status code 401

Expected behavior
To get data from the on-premise system via the exposed by a service provider link in a cap app

Screenshots
If applicable, add screenshots to help explain your problem.

Used Versions:

  • node version via node -v - I don't know the node version used in SAP SCP CF
  • npm version via npm -v- I don't know the npm version used in SAP SCP CF
  • SAP Cloud SDK version you used as dependency - "@sap-cloud-sdk/core": "^1.20.1"
    Code Examples

const cds = require('@sap/cds')

function getUserJWT (req) {
	if(typeof(req._) !== 'undefined') {
		return retrieveJwt(req._.req)
	} else {
		return ""
	}
}
module.exports = async function (){

    const { Entity: sdkEntity } = require('./odata-client/odata-service')
	const destinationName = 'dest_name'
	
	this.on('READ', 'sdkEntity', async (req) => {

		var userToken = getUserJWT(req)	
		
		try{
			const osEntity = await sdkEntity
			.requestBuilder()
			.getAll()
			.execute({ destinationName: destinationName, jwt: userToken}) // [!Error]([url](url)) is fired
			
			let mappedEntity = await osEntity.map(bp => serializeEntity(bp, 
                         sdkEntity))
			
			return mappedEntity
		} catch (e) {
			debugger;
			console.error("Error: " + e.message)
			console.log("Stack: " + e.stack)
		}
	})

Log file
If applicable, add your log file or related error message. Again, please remove your sensitive information.

Additional context
Add any other context about the problem here.

Please check the following points

  • Have you provided detailed description about your issue?
  • Have you shared all the necessary information to help the cloud-sdk developer reproduce the issue?
  • Have you provided the expected behaviour?
  • Have you attached some useful screenshots?
  • Have you provided the node/npm/cloud-sdk versions?
  • Have you shared your code snippets as a minial example?
  • Have you provided you log file or related error messages?
  • Have you searched for related issues on Stackoverflow or answers.sap.com?

Cant generate odata package with 1.29.0 because of casing

I was able to successfully generate client from our C4C tenant c4codata where we have same entities with different casing in names. But with 1.29.0 its not possible any more.

Command for generation is:

generate-odata-client -i service --outputDir ./ --versionInPackageJson=1.0.4 --forceOverwrite

Error i do get is:

2020-10-08T08:23:55.965Z] ERROR    (generator): Error: Failed to generate js files: Error: Command failed with exit code 2: tsc
ActivityTextLanguageCodeRequestBuilder.ts(7,42): error TS1261: Already included file name '/app/src/ActivityTextLanguageCode.ts' differs from file name '/app/src/ActivityTextlanguageCode.ts' only in casing.
ActivityTextlanguageCode.ts(6,56): error TS1149: File name '/app/src/ActivityTextlanguageCodeRequestBuilder.ts' differs from already included file name '/app/src/ActivityTextLanguageCodeRequestBuilder.ts' only in casing.
SalesQuotetimeZoneCode.ts(6,54): error TS1149: File name '/app/src/SalesQuotetimeZoneCodeRequestBuilder.ts' differs from already included file name '/app/src/SalesQuoteTimeZoneCodeRequestBuilder.ts' only in casing.
SurveyInformationDescriptionlanguageCode.ts(6,72): error TS1149: File name '/app/src/SurveyInformationDescriptionlanguageCodeRequestBuilder.ts' differs from already included file name '/app/src/SurveyInformationDescriptionLanguageCodeRequestBuilder.ts' only in casing.
index.ts(1462,15): error TS1149: File name '/app/src/SalesQuotetimeZoneCode.ts' differs from already included file name '/app/src/SalesQuoteTimeZoneCode.ts' only in casing.
index.ts(1671,15): error TS1149: File name '/app/src/SurveyInformationDescriptionlanguageCode.ts' differs from already included file name '/app/src/SurveyInformationDescriptionLanguageCode.ts' only in casing.

Please help me with that, how can i allow filename case sensitive filenames on generation stage?

Javascript sdk Batch with filter

Describe the bug
I ran into issues while trying to pass filters to a batch 'GET' requests.
The sap system return Malformed syntax error

I already found the error it seems that the filters are getting parsed wrong in odata when passing the filter using the URL we have to add spaces between the commands

ex:
?$filter=name eq 'myname'

however in batch the spaces need to be replaced by a plus sign.
ex:
?$filter=name+eq+'myname'

To Reproduce

The error should be very easy to reproduce just add a filter to a batch request

Support entity type as parameter/return type for function/action import

When using the generator with an SAP Business One Edmx file, the following error message is shown:

Tries to get a action/function parameter with type SAPB1.Document which is not a Edm type.

because currently the sdk does not support entity type as parameter for function/action import.

AC:

  • The generator should not fail when detecting unsupported function/action import. Ignoring such cases might be a quick win.
  • Support entity type as parameter/return type for function/action import

cloud sdk version: 1.31.1-22d161e0.22
odata version: v4

Cannot generate SAP Business One OData Client Library with SAP Cloud SDK

Describe the bug
I have an error when trying to generate SAP Business One OData Client Library with SAP Cloud SDK

To Reproduce
I’m following the tutorial Generate Custom OData Client Library with SAP Cloud SDK's Generator for JavaScript: https://developers.sap.com/tutorials/cloudsdk-js-generator.html

Steps to reproduce the behavior:

  1. Take the EDMX file attached here (changed extension to txt to be able to attach it here)
    B1API.edmx.txt
  2. Create a folder called service-spefication
  3. Copy the attached EDMX file into that folder
  4. Execute generate-odata-client -i service-specification/ -o odata-client/
  5. Error shown in the screen capture

B1CloudSDKError

  • The SAP Business One Odata APIs are Odata v4 APIs.
    A single EDMX file contains all the entities of the APIs, all in one.

Used Versions:

  • SAP Cloud SDK version you used as dependency
    @sap-cloud-sdk/cli/0.1.12 win32-x64 node-v12.19.0

generate-odata-client results in Unexpected token 'export'

Describe the bug

Execution of

generate-odata-client --inputDir /in --outputDir /out

fails with ERROR uncaughtException: Unexpected token 'export'

To Reproduce

Steps to reproduce the behavior:

  1. Install npm install -g @sap-cloud-sdk/generator
  2. Execute generate-odata-client --inputDir /in --outputDir /out
  3. See error in terminal

Expected behavior

Get generated output.

Used Versions:

  • node version v13.6.0
  • npm version 6.13.4
  • "@sap-cloud-sdk/generator": "1.27.0"

Log file

[2020-08-27T12:13:16.337Z] ERROR  uncaughtException: Unexpected token 'export'

/usr/local/lib/node_modules/@sap-cloud-sdk/generator/node_modules/uuid/dist/esm-browser/index.js:1

export { default as v1 } from './v1.js';

^^^^^^


SyntaxError: Unexpected token 'export'

  at wrapSafe (internal/modules/cjs/loader.js:1060:16)

  at Module._compile (internal/modules/cjs/loader.js:1108:27)

  at Object.Module._extensions..js (internal/modules/cjs/loader.js:1164:10)

  at Module.load (internal/modules/cjs/loader.js:993:32)

  at Function.Module._load (internal/modules/cjs/loader.js:892:14)

  at Module.require (internal/modules/cjs/loader.js:1033:19)

  at require (internal/modules/cjs/helpers.js:72:18)

  at Object.<anonymous> (/usr/local/lib/node_modules/@sap-cloud-sdk/generator/node_modules/@sap-cloud-sdk/core/dist/odata/v2/odata-batch-change-set.js:5:14)

  at Module._compile (internal/modules/cjs/loader.js:1144:30)

  at Object.Module._extensions..js (internal/modules/cjs/loader.js:1164:10)

Use SAP Cloud SDK in UI5 app controller Directly

Is your feature request related to a problem? Please describe.
In UI5 contoller , we can not import SAP cloud sdk (SDK), so we can not use SDK in UI5 controller directly

Describe the solution you'd like

We can import SDK in UI5 controller and use them directly .

Describe alternatives you've considered
Currently No .

Additional context
No

WhiteSource security vulnerability finding regarding lodash 4.17.15

We received such feedback regarding a WhiteSource finding:

Hi colleagues,

Recently our project encountered a WhiteSource security vulnerability (WS-2020-0070) of NodeJS component "lodash-4.17.15".

Can you please help fix it?
Related Cloud SDK component: @sap-cloud-sdk/util
Version: 1.20.0

403 on onPremise connector with CSRF + Cookie

We are facing issues using the cloud sdk to access a OData service through the cloud connector.
The issues we are facing regards the creation of a new entity through an OData v2 request.
As documented, odata v2 client should handle the CSRF token, but I get a 403 unauthorized response.
If I use axios to handle the whole process, the only way to success it's to fetch the csrf with an HEAD call with X-CSRF-Token=Fetch header and then to pass back the csrf token from the server and the cookies the server is sending back with a set-cookie header on the response.
I'm speculating that the odata client doesn't set the cookies.

Disable csrf fetch request

Is your feature request related to a problem? Please describe.
I am using the sdk as an OData client for my CAP project. I do not have CSRF protection in my backend as it is not meant for users to do browsing. I assume there is no need for csrf protection when two apps talks to each other?

So it would be very nice if there was a configuration to disable the token fetching request that is sent before each request. When there are so many requests, this is even creating problems with destination service. Issuing lots of request creates a connection problem.

I checked the documentation and tutorials, unfortunately could not find any clue to do this.
Hope this description is good enoug.

Error on creating IndividualCustomer via CloudSDK/Kyma

Hi,

We are getting a TypeError when we attempt to create an IndividualCustomer using the CloudSDK. We're using a lambda function on our Kyma instance which has an environment variable to point to the C4C instance (via SAP cloud gateway, i.e. authentication is set up in the proxy).
If we create directly in the OData Test console in our C4C frontend it works fine. Doing a POST to the C4C URL directly from Postman works if you use a pre-script to do a GET and grab the csrf token.

Have posted the lambda function code and a log snippet.
Thanks for your help on this.

IND_log_2020-10-15.txt
IND_create-indiv-customer-sdk.txt

How do you do Dynamic Filter using SAP Cloud SDK

I have a requirement to create a Success Factor extension with SAP UI5 (frontend) + nodejs (middleware) + SF api (data model).

We are currently using the SAP Cloud SDK to construct all the queries by submitting requestBuilder().getAll(); There is a requirement which we need to build to perform filter dynamically according to the parameters passed in from the body, we can't use pre-defined selection. Can you kindly advice how can we do it ? Can we use customQueryString to do this ? If yes, can you advice how can we use to build "Or" and "And" condition for the filter ?

Sample Code :
const cust_TransportHeaderRequestBuilder = Cust_TransportHeader.requestBuilder().getAll();
cust_TransportHeaderRequestBuilder.filter(
//Claim Date, Claim Receipt No, Claim Status
// Cust_BenefitClaims.CUST_RECEIPT_DATE.equals(moment(req.query.cust_ReceiptDate)),
Cust_TransportHeader.EXTERNAL_CODE.equals(ExternalCode),
Cust_TransportHeader.CUST_CLAIM_STATUS.notEquals("Rejected"),
Cust_TransportHeader.CUST_CLAIM_STATUS.notEquals("Draft"),

    // Cust_BenefitClaims.CUST_RECEIPT_NO.equals(moment(req.query.cust_ReceiptNo)),
)

Method Tried :
*The predefine method works like a champ

cust_PtfMainRequestBuilder.filter(
     new Filter("cust_ClaimStatus", "ne", "Rejected"),
     new Filter("cust_ClaimStatus", "ne", "Draft")
)

But when I tried to construct it dynamically, it's not taking in array but rather than argument.

filterArray = [];
filterArray.push(new Filter("cust_ClaimStatus", "ne", "Rejected");
filterArray.push(new Filter("cust_ClaimStatus", "ne", "Draft");

  • This will failed.
    cust_PtfMainRequestBuilder.filter(filterArray);

Failed request error message is not descriptive

Is your feature request related to a problem? Please describe.
I use SAP Cloud SDK with combination of SAP CAP (not Typescript, but Javascript). More precisely, I use @sap/cloud-sdk-vdm-planned-independent-requirement-service module. So I try to create entity in external on-premise system in this kind of way (code is shorten a little bit for simplicity):
const result = await PlannedIndepRqmt.requestBuilder().create(newEntity).execute(this.credentials);
Also, this code spot is surrounded with try - catch to handle errors. Whenever I got error from external system I catch exception with two attributes: message and stack (like on screenshot from debugger below). If you check message attribute you will see that it is not descriptive enough (second screenshot): so from it I know that request has failed, but I don't know. Although if you check stack attribute there is real cause of error is hidden (last screenshot)

image
image
image

Describe the solution you'd like
Probably I miss something (function, class, etc.), but I don't know how to get the real cause of issue from here. I don't think that getting string from stack and parse it to object is a good idea. I noticed, that if you use this create in batch, it will return you response where all the information for request is accessible, so now I can retrieve root error message. Can you, please, advice me how can I retrieve error message from external system or probably provide some additional functionality for this?

Thanks a lot!

Possible GPL-3.0 compliance issue

Describe the bug
I am not an expert in software licenses. I'm just a tool author. I scanned this repo using ShiftLeft Scan and it has identified possible license compliance issue with this repo which I am sharing here.

This repo uses madge as a dev dependency. madge uses graphviz as a direct dependency.

graphviz is currently published as GPL-3.0 in npmjs. In the source code, the author has tried to clarify and change the license to MIT but forgot to re-publish the package under MIT.
glejeune/node-graphviz@ca6394b

The graphviz continues to use GPL-2.0 and later in some headers such as https://github.com/glejeune/node-graphviz/blob/master/lib/ext/gvpr/dot2js.g

As it stands, there is a lack of clarity regards to the exact license of graphviz. Due to the transitive nature of GPL, the exact license of cloud-sdk and therefore all apps using the sdk is unclear atm.

Please consider workarounds to help address this concern.

Batch request fails with CAP

Describe the bug
I am using the "SDK's Generator for JavaScript" to generate OData client for a service generated by using CAP (following this blog post).
After I change the default service path from VALUE_IS_UNDEFINED to my service path (/sitn-admin-srv) I could use all the operations without any problem.
However, when I use the batch request (following this blog post), the request has reached to the server fine, but I got warnings in the server side;
[2020-10-19T13:35:50.287Z | WARNING | 1854218]: 'sitn' is not an entity set, a singleton, an action import, or a function import
where my service path is sitn-admin-srv.

When I set the _defaultServicePath to empty string in the entity level (file is SituationTemplateMetaData.ts), then batch request works fine, but of course all the single operations are being made to the root level and I get 404 errors for the single operations.

Maybe the batch request concatenates the default service path twice? Or am I doing something wrong?

To Reproduce
Steps to reproduce the behavior:

  1. Get any OData service (like bookshop app)
  2. Generate client library using the generator
  3. Change the default paths in generated files
    export const defaultSitnAdminSrvServicePath = '/<serice-path>'; in BatchRequest.ts and static _defaultServicePath = '/<service-path>'; in <entity>.ts
  4. Single requests will work, but batch request will get a warning like above.
  5. Leave the service path empty in the entity file, batch request will work but the single requests will get 404.

I can also provide you my code, or collabrate further if there is a need.

Used Versions:

  • node version via node -v: v12.16.0
  • npm version via npm -v: 6.13.7
  • SAP Cloud SDK version you used as dependency: `-- @sap-cloud-sdk/[email protected]
  • Cli: `-- @sap-cloud-sdk/[email protected]

generator produces uncompilable files in version 1.21.0

Describe the bug
When generating an OData Client using the @sap-cloud-sdk/generator in version 1.21.0, compilation of the generated VDM files fails. Works fine in version 1.20.1 and earlier.

To Reproduce
Place the attached edmx.xml in folder edmx inside a sap-cloud-sdk project and run sap-cloud-sdk generate-odata-client -i edmx -o src/vdm
When running tsc, there will be lots of argument mismatches (see compilation_errors.txt).

When switching the globally installed @sap-cloud-sdk/generator back to 1.20.1, everything works as expected.

Versions in use:
Node: 10.18.0
NPM: 6.14.2
compilation_errors.txt
edmx.xml.txt

TSC: 3.9.2
@sap-cloud-sdk/[email protected]
@sap-cloud-sdk/[email protected]

Multi Tenancy with the Thread Context

Hi Experts,

I've ever get tenant and user info via TenantAccessor and PrincipalAccessor, but it's not that stable - by which I mean after a night it won't return any value anymore.

I think there must be something wrong how I use the library, as there's no sample application / detailed guide, I want to search help here:

  1. I'm using this link as reference, as mentioned in the document 'RequestFilter' is used to get Thread Context. Then how should I enable such a filter? for now I add below segment in my web.xml:
<filter>
 <display-name>RequestAccessorFilter</display-name>
 <filter-name>RequestAccessorFilter</filter-name>
 <filter-class>com.sap.cloud.sdk.cloudplatform.servlet.RequestAccessorFilter</filter-class>
</filter>
<filter-mapping>
 <filter-name>RequestAccessorFilter</filter-name>
 <url-pattern>/*</url-pattern>
</filter-mapping>

and following dependency in my pom.xml:

<dependency>
    <groupId>com.sap.cloud.sdk.cloudplatform</groupId>
    <artifactId>servlet</artifactId>
</dependency>

is this enough for the filter to be enabled?

  1. to get tenant and user information, I have code like below:
import com.sap.cloud.sdk.cloudplatform.tenant.TenantAccessor;
import com.sap.cloud.sdk.cloudplatform.security.principal.PrincipalAccessor;
import com.sap.cloud.sdk.cloudplatform.thread.ThreadContextAccessor;
...

PrintWriter out = response.getWriter();
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
out.print(Encode.forHtml(
"TenantAccessor: "+ TenantAccessor.getCurrentTenant().getTenantId()) + 
"; PrincipalAccessor: " + PrincipalAccessor.getCurrentPrincipal() + 
";ThreadContextAccessor: " + ThreadContextAccessor.getCurrentContext().toString());
...

with the following pom.xml:

<dependency>
 <groupId>com.sap.cloud.sdk.cloudplatform</groupId>
 <artifactId>tenant</artifactId>
</dependency>
<dependency>
 <groupId>com.sap.cloud.sdk.cloudplatform</groupId>
 <artifactId>security</artifactId>
</dependency>

just want to know am I including the right dependency? do I need to include dependency

tenant-scp-cf
security-scp-cf

or just
scp-cf
instead?

Kindly let me know if there're already some documents / sample code about this feature.

Thanks and regards,

Blan

--config file.json - paths in file.json are relative to current execution path, not relative to location of file.j

Describe the bug
The output of --help clearly states that the paths inside the config file are relative to the folder where the config file is stored:

  -c, --config                       Instead of specifying the options on the
                                     command line, you can also provide a path
                                     to single .json file holding these options.
                                     The file must be a valid .json file where
                                     the keys correspond to the command line
                                     flags without dashes. Paths will be
                                     interpreted relative to the config file.

now, if I place the file

{
    "inputDir": "",
    "outputDir": "client",
    "clearOutputDir": true
}

in the folder srv/external and run generate-odata-cloent -c srv/external/file.json inside the folder containing srv, it tries to find metadata files ewerywhere in the folder containing src.

If, OTOH, the file contains this:

{
    "inputDir": "srv/external",
    "outputDir": "srv/external/client",
    "clearOutputDir": true
}

run generate-odata-cloent -c srv/external/file.json, then client generator finds the metadata files contained in srv/external.

To Reproduce
Steps to reproduce the behavior: see above

Expected behavior
Either the --help output should be changed to say "paths are interpreted relative to the path where generate-odata-client is executed" or the behavouur should be changed to the one described in --help

Used Versions:

  • node version via node -v
    v12.19.0
  • npm version via npm -v
    6.14.8
  • generate-odata-client --version
    1.30.0

Please check the following points

  • Have you provided detailed description about your issue?
  • Have you shared all the necessary information to help the cloud-sdk developer reproduce the issue?
  • Have you provided the expected behaviour?
  • [-] Have you attached some useful screenshots?
  • Have you provided the node/npm/cloud-sdk versions?
  • Have you shared your code snippets as a minial example?
  • [-] Have you provided you log file or related error messages?
  • [-] Have you searched for related issues on Stackoverflow or answers.sap.com?

SDK util setLogLevel seems to do nothing

Describe the bug
I'm creating a NodeJS application on Cloud Foundry and I am noticing a lot of warning & info messages in the log.

While browsing through the API page of the @sap/cloud-sdk-util package I found the setLogLevel method which I thought would do exactly what I need/want. But after some fiddling around with it I can't get it to remove the warnings in the log.

I have quickly set up a public repo to show my code. I removed some files for generating the odata client files.

To Reproduce
Steps to reproduce the behavior:

  1. use the SetLogLevel method of the SDK util package
  2. Check the logs on Cloud Foundry
  3. See a lot of info and warning messages in the log

Expected behavior
Expected to only see errors in the log

Screenshots
The log on CF:
image

A screenshot of my code:
image

Used Versions:

  • node v10.19.0
  • npm v6.13.4
  • SAP Cloud SDK v1.17.2

Code Examples
See public repo above

Please check the following points

  • Have you provided detailed description about your issue?
  • Have you shared all the necessary information to help the cloud-sdk developer reproduce the issue?
  • Have you provided the expected behaviour?
  • Have you attached some useful screenshots?
  • Have you provided the node/npm/cloud-sdk versions?
  • Have you shared your code snippets as a minial example?
  • Have you provided you log file or related error messages?
  • Have you searched for related issues on [Stackoverflow]
    Link to answers.sap.com issue: https://answers.sap.com/questions/13068848/setloglevel-on-sap-cloud-sdk-logger.html?childToView=13070715#comment-13070715

Requirements for logging in a multi-tenancy environment

Hello SAP Cloud SDK team,

Is your feature request related to a problem? Please describe.
In a multi-tenancy environment, it is important for us to recognize where the logging outputs are coming from.

Describe the solution you'd like
We need the ability to set Kibana metadata fields (correlation_id, tenant_id, tenant_subdomain, remote_user, #cf (Custom Fields), ...) for the logging outputs on the various functionalities/classes within the SAP Cloud SDK.
For example, it should be possible to set these Kibana metadata fields individually for each request (RequestBuilder).

Best regards
Jens

Parameter to pass the subscriber subaccount for scenarios without user token

Is your feature request related to a problem? Please describe.

We are using the Cloud SDK for Javascript Destination API in background processes. In this scenario we do not have a user JWT from which the destination service can derive the subsrciber subaccount required as we are running in a multitenancy scenario.
Currently we are using a inoffical workaround

//This is just a workaround to read from subscriber subaccount "ccsetuppocsubsriber" without a user token be creating the following dummy url.
getDestinationFromDestinationService("xxxx", { iss: 'https://ccsetuppocsubsriber.example.com' } ).then( value => {
    console.log("Destination from subscriber tenant"  );
    console.log(value.url);    
} ).catch( rejected => {
    console.log("xxxx not found in subscriber tenant" );
});

Describe the solution you'd like
We would rather aspect a parameter in the API which allows to pass the subaccount which is as well documented as probably we are not the only consumer running it as part of a background job. Using a not documented feature has as well the risk that we can not rely on that it will always work

Describe alternatives you've considered

Stay with the workaround hoping it will not break

Error: Could not find navigation property ResourceGroup in entity type Resource when running generator for SAP Business One Service Layer Metadata

Describe the bug

The first issue with the SAP Business One Service Layer Metadata was fixed in #176. But now there is another issue.

In the branch collection-issue of my test project sap-business-one-odata-cap I've added "@sap-cloud-sdk/generator": "^1.22.0" and the script:

generate-odata-client --inputDir srv/external --outputDir srv/odata-client --forceOverwrite

but when running this script I get the following error:

(node:12328) UnhandledPromiseRejectionWarning: Error: Could not find navigation property ResourceGroup in entity type Resource.
    at /Users/gwolf/Documents/Projects/cap/sap-business-one-odata-cap/node_modules/@sap-cloud-sdk/generator/dist/parser/v4/edmx-to-vdm.js:23:19
    at Array.map (<anonymous>)
    at navigationProperties (/Users/gwolf/Documents/Projects/cap/sap-business-one-odata-cap/node_modules/@sap-cloud-sdk/generator/dist/parser/v4/edmx-to-vdm.js:20:48)
    at /Users/gwolf/Documents/Projects/cap/sap-business-one-odata-cap/node_modules/@sap-cloud-sdk/generator/dist/parser/v4/edmx-to-vdm.js:32:200
    at Array.map (<anonymous>)
    at transformEntitiesV4 (/Users/gwolf/Documents/Projects/cap/sap-business-one-odata-cap/node_modules/@sap-cloud-sdk/generator/dist/parser/v4/edmx-to-vdm.js:32:29)
    at transformServiceMetadata (/Users/gwolf/Documents/Projects/cap/sap-business-one-odata-cap/node_modules/@sap-cloud-sdk/generator/dist/parser/service-parser.js:78:19)
    at parseService (/Users/gwolf/Documents/Projects/cap/sap-business-one-odata-cap/node_modules/@sap-cloud-sdk/generator/dist/parser/service-parser.js:45:12)
    at /Users/gwolf/Documents/Projects/cap/sap-business-one-odata-cap/node_modules/@sap-cloud-sdk/generator/dist/parser/service-parser.js:38:16
    at Array.map (<anonymous>)
(node:12328) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
(node:12328) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

To Reproduce
Steps to reproduce the behavior:

  1. checkout the branch collection-issue
  2. run npm i
  3. run npm run generate-odata-client
  4. See error

Expected behavior
Also the SAP Business One Service Layer Metadata should be supported.

Used Versions:

  • node version v12.16.1
  • npm version 6.14.5
  • SAP Cloud SDK version 1.22.0

Catching Backend errors

Is your feature request related to a problem? Please describe.
Not being able to get hands on the error response provided by backend

Describe the solution you'd like
Basically, I go along these lines

myExtOdataV2service.entityset.reauestbuilder(). ... .execute(destination) 

and the request is sent correctly to the source system, which returns a (perfectly valid) error response as odata v2 json, which I need to grab and pass along.
Adding a catch() at the end of the above statement, I get an error object, containing the original json somewhere in the middle of the stacktrace string…
Sure, I could go and try to find it using regex or something, but is there a “proper” way to catch the original backend error in @sap-cloud-sdk?

Describe alternatives you've considered
Sure, I could go and try to find it using regex in the stacktrace.

Additional context
example stacktrace inside the catch

Create request failed!
    at Object.errorWithCause (XXX/srv/node_modules/@sap-cloud-sdk/util/dist/error.js:5:20)
    at XXX/srv/node_modules/@sap-cloud-sdk/core/dist/odata/v2/request-builder/create-request-builder.js:124:54
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
    at ...
Caused by:
Error: post request to https://*****_SRV failed! Personnel Number ******** : Incorrect data in ***
{"code":"***/***","message":{"lang":"en","value":"Personnel Number ******** : Incorrect data in ***"},"innererror":{"application":{"component_id":"","service_namespace":"/***/","service_id":"***","service_version":"0001"},"transactionid":"***","timestamp":"20201027150920.7447650","Error_Resolution":{"SAP_Transaction":"For backend administrators: run transaction /IWFND/ERROR_LOG on SAP Gateway hub system and search for entries with the timestamp above for more details","SAP_Note":"See SAP Note 1797736 for error analysis (https://service.sap.com/sap/support/notes/1797736)"},"errordetails":[{"code":"***/***","message":"Personnel Number ******** : Incorrect data in ***","longtext_url":"/sap/opu/odata/iwbep/message_text;o=LOCAL/","propertyref":"","severity":"error","target":""}]}}
    at Object.errorWithCause (XXX/srv/node_modules/@sap-cloud-sdk/util/dist/error.js:5:20)
    at constructError (XXX/srv/node_modules/@sap-cloud-sdk/core/dist/odata/common/request/odata-request.js:295:23)
    at XXX/srv/node_modules/@sap-cloud-sdk/core/dist/odata/common/request/odata-request.js:265:51
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
    at ...
Caused by:
Error: Request failed with status code 400
    at createError (XXX/srv/node_modules/axios/lib/core/createError.js:16:15)
    at settle (XXX/srv/node_modules/axios/lib/core/settle.js:17:12)
    at IncomingMessage.handleStreamEnd (XXX/srv/node_modules/axios/lib/adapters/http.js:236:11)
    at IncomingMessage.emit (events.js:326:22)
    at endReadableNT (_stream_readable.js:1223:12)
    at processTicksAndRejections (internal/process/task_queues.js:84:21)

Feature implementation
sorry for not providing a pull request, here is a quick solution:
@sap-cloud-sdk/util/dist/error.js

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.errorWithCause = void 0;
function errorWithCause(message, cause) {
    var newError = new Error(message);
    // Stack is a non-standard property according to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Custom_Error_Types
    if (newError.stack && cause.stack) {
        newError.stack = newError.stack + '\nCaused by:\n' + cause.stack;
    }
    // INSERT BEGIN -- @the-docta
    if (cause.isAxiosError) {
        // these are the fields set by axios in lib/core/enhanceError (as of 0.19.2)
        newError.isAxiosError = cause.isAxiosError
        newError.config = cause.config;
        newError.request = cause.request;
        newError.response = cause.response;
        if (cause.code) {
            newError.code = cause.code;
        }
    }
    // INSERT END -- @the-docta
    return newError;
}
exports.errorWithCause = errorWithCause;

New version (1.32.0) of @sap-cloud-sdk/core does not export `executeHttpRequest` function anymore

Describe the bug
Hi colleagues,

when installing the newest version (1.32.0) of the @sap-cloud-sdk/core package, the functions of the http-client module are not exported anymore.

We rely on the executeHttpRequest method which was exported until 1.31.0.
I did not find any related entry in the changelog and also the documentation suggests that this function should still be available.

When looking at https://github.com/SAP/cloud-sdk-js/blob/v1.32.0/packages/core/src/index.ts, I can also see that it is not exported anymore.

To Reproduce
Steps to reproduce the behavior:

  1. Install @sap-cloud-sdk/core in any node.js project.
  2. require('@sap-cloud-sdk/core').executeHttpRequest is not defined

Expected behavior
I'd expect the function to still be available.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.