diff --git a/.env b/.env deleted file mode 100644 index 01ade12c..00000000 --- a/.env +++ /dev/null @@ -1 +0,0 @@ -cds.features.snapi = y \ No newline at end of file diff --git a/.eslintrc b/.eslintrc index da867678..5d21a014 100644 --- a/.eslintrc +++ b/.eslintrc @@ -1,26 +1,31 @@ { - "extends": "eslint:recommended", - "env": { - "browser": true, - "node": true, - "es6": true, - "jest": true, - "mocha": true - }, - "parserOptions": { - "ecmaVersion": 2018 - }, - "globals": { - "SELECT": true, - "INSERT": true, - "UPDATE": true, - "DELETE": true, - "CREATE": true, - "DROP": true, - "cds": true - }, - "rules": { - "no-console": "off", - "require-atomic-updates": "off" - } + "extends": [ + "plugin:@sap/cds/recommended", + "eslint:recommended" + ], + "env": { + "browser": true, + "es2022": true, + "node": true, + "jest": true, + "mocha": true + }, + "globals": { + "SELECT": true, + "INSERT": true, + "UPSERT": true, + "UPDATE": true, + "DELETE": true, + "CREATE": true, + "DROP": true, + "CDL": true, + "CQL": true, + "cds": true + }, + "rules": { + "no-console": "off", + "require-atomic-updates": "off", + "require-await":"warn", + "no-unused-vars": ["warn", { "argsIgnorePattern": "_" }] + } } diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 00000000..58fede7a --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,5 @@ +blank_issues_enabled: false +contact_links: + - name: This channel is CLOSED. + about: Use SAP community instead + url: https://answers.sap.com/tags/9f13aee1-834c-4105-8e43-ee442775e5ce diff --git a/.github/ISSUE_TEMPLATE/question--feedback-or-bug-.md b/.github/ISSUE_TEMPLATE/question--feedback-or-bug-.md deleted file mode 100644 index 19f10800..00000000 --- a/.github/ISSUE_TEMPLATE/question--feedback-or-bug-.md +++ /dev/null @@ -1,10 +0,0 @@ ---- -name: Question, feedback or bug? -about: Use our community! -title: '' -labels: '' -assignees: '' - ---- - -Please use our community on https://answers.sap.com/tags/9f13aee1-834c-4105-8e43-ee442775e5ce diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 00000000..3f78b02f --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,8 @@ +version: 2 + +updates: +- package-ecosystem: npm + directory: / + versioning-strategy: increase-if-necessary + schedule: + interval: daily diff --git a/.github/workflows/node.js.yml b/.github/workflows/node.js.yml index c9fb33c2..a1d86fb8 100644 --- a/.github/workflows/node.js.yml +++ b/.github/workflows/node.js.yml @@ -5,9 +5,9 @@ name: CI on: push: - branches: [ master ] + branches: [ main ] pull_request: - branches: [ master ] + branches: [ main ] jobs: build: @@ -16,7 +16,7 @@ jobs: strategy: matrix: - node-version: [10.x, 12.x, 14.x] + node-version: [16.x, 14.x] steps: - uses: actions/checkout@v2 @@ -24,5 +24,6 @@ jobs: uses: actions/setup-node@v1 with: node-version: ${{ matrix.node-version }} - - run: npm install + - run: npm i -g npm@8 + - run: npm ci - run: npm test diff --git a/.gitignore b/.gitignore index 1951715e..c4d1b518 100644 --- a/.gitignore +++ b/.gitignore @@ -12,6 +12,11 @@ target/ *.mtar connection.properties default-env.json +.cdsrc-private.json packages/messageBox reviews/msg-box reviews/db/test.db + +*.openapi3.json +*.sqlite +*.db diff --git a/.mocharc.yml b/.mocharc.yml deleted file mode 100644 index 06f6886f..00000000 --- a/.mocharc.yml +++ /dev/null @@ -1 +0,0 @@ -parallel: true diff --git a/.npmrc b/.npmrc new file mode 100644 index 00000000..2279fba7 --- /dev/null +++ b/.npmrc @@ -0,0 +1,3 @@ +# Ensure we always use public packages, i.e. avoid using local registries from ~/.npmrc +@sap:registry=https://registry.npmjs.org/ +registry=https://registry.npmjs.org/ diff --git a/.tours/db-native.tour b/.tours/db-native.tour new file mode 100644 index 00000000..97b615e0 --- /dev/null +++ b/.tours/db-native.tour @@ -0,0 +1,117 @@ +{ + "$schema": "https://aka.ms/codetour-schema", + "title": "Database Functions", + "steps": [ + { + "title": "Introduction", + "description": "### Database Functions in CDS Models\n\nIn this tour, you'll learn how to add database-specific functions to CDS models in your application." + }, + { + "file": "bookshop/db/schema.cds", + "description": "#### Basic Schema\n\nWe want to add two fields to the `Authors` entity, one for the author's age and one for the span of years that she or he lived.\n\nThese two fields can be computed out of the existing `dateOfBirth` and `dateOfDeath` fields.", + "selection": { + "start": { + "line": 19, + "character": 1 + }, + "end": { + "line": 21, + "character": 1 + } + }, + "title": "Base fields in Author" + }, + { + "file": "bookshop/srv/admin-service.cds", + "description": "This is how the `Authors` entity gets exposed in an OData or REST service.\n\nIn the next step, you'll see how we extend this projection.", + "selection": { + "start": { + "line": 4, + "character": 1 + }, + "end": { + "line": 5, + "character": 1 + } + }, + "title": "Authors service" + }, + { + "file": "fiori/db/sqlite/index.cds", + "description": "#### SQLite Implementation\n\nHere's the first implementation for SQLite. It computes the two fields `age` and `lifetime` through SQLite's [strftime](https://sqlite.org/lang_datefunc.html) function.\n\nThrough the [`extend projection`](https://cap.cloud.sap/docs/cds/cdl#extend-view) clause you can add additional fields to projection entities. These are deployed as database views, which is why we can integrate the database functions in the first place.\n", + "selection": { + "start": { + "line": 7, + "character": 1 + }, + "end": { + "line": 11, + "character": 1 + } + }, + "title": "SQLite implementation" + }, + { + "file": "fiori/db/hana/index.cds", + "description": "#### SAP HANA Implementation\n\nThis is the second implementation for SAP HANA. It computes the same two fields `age` and `lifetime` through the [YEARS_BETWEEN](https://help.sap.com/viewer/7c78579ce9b14a669c1f3295b0d8ca16/Cloud/en-US/7c0d2c161ea34def86de3f5eadd6a0af.html) and [YEAR](https://help.sap.com/viewer/7c78579ce9b14a669c1f3295b0d8ca16/Cloud/en-US/20f5fac6751910148dabd3c6821f907d.html) functions of SAP HANA.\n\n#### File Layout and Code Structure\n\nNote the path of the `.cds` file we are in: it's in a subfolder of `db`, so that it's _not_ automatically picked up when we start the application. The same is true for the SQLite implementation: it's in a separate `db/sqlite/` folder as well. In the next step, you'll see how these files are loaded.\n\nAlso, we choose to implement all of that as an extension of the original bookshop here in the _fiori_ package. See the first [CAP Samples] code tour for more details on the different packages of this repository.", + "selection": { + "start": { + "line": 7, + "character": 1 + }, + "end": { + "line": 11, + "character": 1 + } + }, + "title": "SAP HANA implementation" + }, + { + "file": "fiori/package.json", + "description": "#### Configuration\n\nThe `cds.requires` section in `package.json` is a place to configure which of the `db/sqlite` and `db/hana` folders are used for which database.\n\nWe use [Node.js profiles](https://cap.cloud.sap/docs/node.js/cds-env#profiles) to separate the configuration.\nIn the `development` profile, you can see that `db/sqlite` is set as the model, while the `db/hana` folder is configured in the `production` profile. `db-ext` is a pseudo datasource, its name doesn't matter.\n\nSee [`cds.resolve`](https://cap.cloud.sap/docs/node.js/cds-compile#cds-resolve) to learn more about how models are found.", + "selection": { + "start": { + "line": 41, + "character": 1 + }, + "end": { + "line": 48, + "character": 1 + } + }, + "title": "Configuration" + }, + { + "file": "fiori/package.json", + "description": "#### Run with SQLite\n\nTo run with `development` and an in-memory SQLite database, you don't need to do anything special, because it's activated by default. Just run:\n\n>> cds watch fiori\n\nThen open [http://localhost:4004/admin/Authors](http://localhost:4004/admin/Authors) to see the two new fields.\n", + "line": 43, + "title": "Run with SQLite" + }, + { + "file": "fiori/package.json", + "description": "#### Deploy the CDS Model to SAP HANA\n\nTo 'activate' SAP HANA through the `production` profile, you can use the global `--production` flag:\n\n>> cd fiori; cds deploy --to hana --production\n\n[Learn more about SAP HANA deployment](https://cap.cloud.sap/docs/guides/databases#get-hana)\n\n#### Run the Application\n\n>> cd fiori; cds watch --production\n\nThe service on [http://localhost:4004/admin/Authors](http://localhost:4004/admin/Authors) is the same as before, but this time the `Authors` entity is backed by a database view with an SAP HANA function.\n\n#### More\n\nIf you don't see data, you can add some in the next step.", + "line": 46, + "title": "Run with SAP HANA" + }, + { + "file": "fiori/test/requests.http", + "description": "### Add More Data\n\nOptionally you can add some `Authors` data by clicking on the _Send Request_ link (provided by the [REST client](https://marketplace.visualstudio.com/items?itemName=humao.rest-client) extension).", + "line": 72, + "selection": { + "start": { + "line": 67, + "character": 1 + }, + "end": { + "line": 73, + "character": 1 + } + }, + "title": "Add Data" + }, + { + "title": "Wrap-up", + "description": "### Summary\n\nThat's it! You have seen: \n- How to integrate database-specific functions in a CDS model.\n- How to switch between the two implementations for SQLite and SAP HANA." + } + ] +} \ No newline at end of file diff --git a/.tours/samples.tour b/.tours/samples.tour new file mode 100644 index 00000000..18b193b8 --- /dev/null +++ b/.tours/samples.tour @@ -0,0 +1,139 @@ +{ + "$schema": "https://aka.ms/codetour-schema", + "title": "CAP Samples", + "steps": [ + { + "title": "Welcome", + "file": "README.md", + "description": "### Welcome to CAP Samples!\n\nThis tour leads you through a collection of samples for the [SAP Cloud Application Programming Model (CAP)](https://cap.cloud.sap).\nYou will learn which features of the programming model are demonstrated in which sample.\n\nLet's start!", + "line": 2, + "selection": { + "start": { + "line": 1, + "character": 1 + }, + "end": { + "line": 3, + "character": 108 + } + } + }, + { + "file": "hello/srv/world.cds", + "description": "### Hello World!\n\nThis is a simplistic [Hello World](https://cap.cloud.sap/docs/get-started/hello-world) service using [CDS](https://cap.cloud.sap/docs/cds/) and [cds.services](https://cap.cloud.sap/docs/node.js/api#services-api).", + "line": 2, + "selection": { + "start": { + "line": 1, + "character": 1 + }, + "end": { + "line": 4, + "character": 1 + } + }, + "title": "Hello World!" + }, + { + "file": "bookshop/db/schema.cds", + "description": "### A Bookshop!\n\nIntroduces:\n- [Project Setup](https://cap.cloud.sap/docs/get-started/) and [Layouts](https://cap.cloud.sap/docs/get-started/projects)\n- [Domain Modeling](https://cap.cloud.sap/docs/guides/domain-models)\n- [Defining Services](https://cap.cloud.sap/docs/guides/providing-services)\n- [Generic Providers](https://cap.cloud.sap/docs/guides/generic-providers)\n- [Adding Custom Logic](https://cap.cloud.sap/docs/guides/service-impl)\n- [Using Databases](https://cap.cloud.sap/docs/guides/databases)\n", + "line": 1, + "selection": { + "start": { + "line": 1, + "character": 1 + }, + "end": { + "line": 32, + "character": 1 + } + }, + "title": "Bookshop" + }, + { + "file": "common/index.cds", + "description": "### Extend and Reuse\n\nShowcases how to extend [@sap/cds/common](https://cap.cloud.sap/docs/cds/common) thereby covering:\n- Building [extension packages](https://cap.cloud.sap/docs/guides/domain-models#aspects-extensibility)\n- Providing [reuse packages](https://cap.cloud.sap/docs/get-started/projects#sharing-and-reusing-content)\n- [Verticalization](https://cap.cloud.sap/docs/cds/common#adapting-to-your-needs)\n- Using [Aspects](https://cap.cloud.sap/docs/cds/cdl#aspects)\n- Used in the [fiori app sample](#fiori)\n", + "line": 1, + "selection": { + "start": { + "line": 1, + "character": 1 + }, + "end": { + "line": 46, + "character": 1 + } + }, + "title": "Common" + }, + { + "file": "orders/db/schema.cds", + "description": "### Orders - Compositions and Serving Documents\n\nA standalone orders management service, demonstrating:\n- Using [Compositions](https://cap.cloud.sap/docs/cds/cdl#compositions) in [Domain Models](https://cap.cloud.sap/docs/guides/domain-models), along with\n- [Serving deeply nested documents](https://cap.cloud.sap/docs/guides/generic-providers#serving-structured-data)\n", + "line": 1, + "selection": { + "start": { + "line": 1, + "character": 1 + }, + "end": { + "line": 27, + "character": 1 + } + }, + "title": "Orders" + }, + { + "file": "reviews/db/schema.cds", + "description": "### Reviews - More Modularity\n\nShows how to implement a modular service to manage product reviews, including:\n- Consuming other services synchronously and asynchronously\n- Serving requests synchronously\n- Emitting events asynchronously\n- Grow as you go, with:\n- Mocking app services\n- Running service meshes\n- Late-cut Micro Services\n- As well as managed data, input validations, and authorization\n", + "line": 1, + "selection": { + "start": { + "line": 1, + "character": 1 + }, + "end": { + "line": 39, + "character": 1 + } + }, + "title": "Reviews" + }, + { + "title": "Bookstore", + "description": "### Bookstore - Reuse and UI\n\n- A [composite app, reusing and combining](https://cap.cloud.sap/docs/guides/reuse-and-compose) these packages:\n - [@capire/bookshop](bookshop)\n - [@capire/reviews](reviews)\n - [@capire/orders](orders)\n - [@capire/common](common)\n- [The Vue.js app](bookshop/app/vue) imported from bookshop is served as well\n- [The Vue.js app](reviews/app/vue) imported from reviews is served as well\n- [The Fiori app](orders/app) imported from orders is served as well\n- [OpenAPI export + Swagger UI](https://cap.cloud.sap/docs/advanced/openapi)" + }, + { + "file": "fiori/app/services.cds", + "description": "### Annotations for SAP Fiori Elements\n\nAdds an SAP Fiori elements application to bookstore, thereby introducing:\n- OData Annotations in `.cds` files\n- Support for Fiori Draft\n- Support for Value Helps\n- Serving SAP Fiori apps locally\n\nSee the [Serving Fiori UIs](https://cap.cloud.sap/docs/advanced/fiori) documentation for more information.", + "line": 1, + "selection": { + "start": { + "line": 1, + "character": 1 + }, + "end": { + "line": 13, + "character": 1 + } + }, + "title": "Fiori" + }, + { + "file": "package.json", + "description": "### All-in-one Monorepo\n\nEach sample sub directory essentially is a standard npm package, some with standard npm dependencies to other samples. The root folder's [package.json](package.json) has local links to the sub folders, such that an `npm install` populates a local `node_modules` folder acts like a local npm registry to the individual sample packages.\n", + "selection": { + "start": { + "line": 8, + "character": 1 + }, + "end": { + "line": 16, + "character": 1 + } + }, + "title": "Packages" + } + ], + "isPrimary": true, + "description": "Overview of CAP Samples for Node.js" +} diff --git a/.vscode/extensions.json b/.vscode/extensions.json index 240b1cf9..23f34ec2 100644 --- a/.vscode/extensions.json +++ b/.vscode/extensions.json @@ -4,14 +4,15 @@ // List of extensions which should be recommended for users of this workspace. "recommendations": [ - "SAPSE.vscode-cds", + "sapse.vscode-cds", "dbaeumer.vscode-eslint", "esbenp.prettier-vscode", "mechatroner.rainbow-csv", "humao.rest-client", "alexcvzz.vscode-sqlite", "hbenl.vscode-mocha-test-adapter", - "sdras.night-owl" + "sdras.night-owl", + "vsls-contrib.codetour" ], // List of extensions recommended by VS Code that should not be recommended for users of this workspace. "unwantedRecommendations": [ diff --git a/.vscode/launch.json b/.vscode/launch.json index d0f0e8eb..40d3ef3c 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -6,25 +6,51 @@ "configurations": [ { "name": "bookshop", - "command": "cds watch bookshop", - "request": "launch", + "command": "npx cds watch bookshop", "type": "node-terminal", - "skipFiles": ["/**"] + "request": "launch", + "skipFiles": [ + "/**", + "**/node_modules/**", + "**/cds/lib/lazy.js", + "**/cds/lib/req/cds-context.js", + "**/odata-v4/okra/**" + ] }, { - "name": "Fiori app", - "command": "cds watch fiori", - "request": "launch", + "name": "Fiori App", + "command": "npx cds watch fiori", "type": "node-terminal", - "skipFiles": ["/**"] - } + "request": "launch", + "skipFiles": [ + "/**", + "**/node_modules/**", + "**/cds/lib/lazy.js", + "**/cds/lib/req/cds-context.js", + "**/odata-v4/okra/**" + ] + }, + { + "name": "Debug Mocha Tests", + "type": "node", + "request": "attach", + "port": 9229, + "continueOnAttach": true, + "skipFiles": [ + "/**", + "**/node_modules/**", + "**/cds/lib/lazy.js", + "**/cds/lib/req/cds-context.js", + "**/odata-v4/okra/**", + ] + }, ], "inputs": [ { "type": "pickString", "id": "sample", "description": "Which sample do you want to start?", - "options": ["bookshop", "fiori", "reviews", "reviews/test/bookshop"], + "options": [ "bookshop", "fiori", "reviews", "reviews" ], "default": "bookshop" } ] diff --git a/.vscode/settings.json b/.vscode/settings.json index cc8b0364..7ed76f56 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,7 +1,27 @@ { "files.exclude": { + ".reuse/**": true, "**/.gitignore": true, - "**/.vscode": true + "**/.vscode": true, + "LICENSES/**": true }, - "files.watcherExclude": {} + "debug.javascript.terminalOptions": { + "skipFiles": [ + "/**", + "**/node_modules/**", + "**/cds/lib/lazy.js", + "**/cds/lib/req/cds-context.js", + "**/odata-v4/okra/**" + ] + }, + "mochaExplorer.debuggerConfig": "Debug Mocha Tests", + "mochaExplorer.parallel": true, + "eslint.validate": [ + "cds", + "csn", + "csv", + "csv (semicolon)", + "tsv", + "tab" + ] } diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..1653b640 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/LICENSES/Apache-2.0.txt b/LICENSES/Apache-2.0.txt index 4ed90b95..137069b8 100644 --- a/LICENSES/Apache-2.0.txt +++ b/LICENSES/Apache-2.0.txt @@ -1,208 +1,73 @@ Apache License - Version 2.0, January 2004 +http://www.apache.org/licenses/ -http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, -AND DISTRIBUTION +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - 1. Definitions. +1. Definitions. - +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. -"License" shall mean the terms and conditions for use, reproduction, and distribution -as defined by Sections 1 through 9 of this document. +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. - +"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. -"Licensor" shall mean the copyright owner or entity authorized by the copyright -owner that is granting the License. +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. - +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. -"Legal Entity" shall mean the union of the acting entity and all other entities -that control, are controlled by, or are under common control with that entity. -For the purposes of this definition, "control" means (i) the power, direct -or indirect, to cause the direction or management of such entity, whether -by contract or otherwise, or (ii) ownership of fifty percent (50%) or more -of the outstanding shares, or (iii) beneficial ownership of such entity. +"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. - +"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). -"You" (or "Your") shall mean an individual or Legal Entity exercising permissions -granted by this License. +"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. - +"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." -"Source" form shall mean the preferred form for making modifications, including -but not limited to software source code, documentation source, and configuration -files. +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. - +2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. -"Object" form shall mean any form resulting from mechanical transformation -or translation of a Source form, including but not limited to compiled object -code, generated documentation, and conversions to other media types. +3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. - +4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: -"Work" shall mean the work of authorship, whether in Source or Object form, -made available under the License, as indicated by a copyright notice that -is included in or attached to the work (an example is provided in the Appendix -below). + (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and - + (b) You must cause any modified files to carry prominent notices stating that You changed the files; and -"Derivative Works" shall mean any work, whether in Source or Object form, -that is based on (or derived from) the Work and for which the editorial revisions, -annotations, elaborations, or other modifications represent, as a whole, an -original work of authorship. For the purposes of this License, Derivative -Works shall not include works that remain separable from, or merely link (or -bind by name) to the interfaces of, the Work and Derivative Works thereof. + (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and - + (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. -"Contribution" shall mean any work of authorship, including the original version -of the Work and any modifications or additions to that Work or Derivative -Works thereof, that is intentionally submitted to Licensor for inclusion in -the Work by the copyright owner or by an individual or Legal Entity authorized -to submit on behalf of the copyright owner. For the purposes of this definition, -"submitted" means any form of electronic, verbal, or written communication -sent to the Licensor or its representatives, including but not limited to -communication on electronic mailing lists, source code control systems, and -issue tracking systems that are managed by, or on behalf of, the Licensor -for the purpose of discussing and improving the Work, but excluding communication -that is conspicuously marked or otherwise designated in writing by the copyright -owner as "Not a Contribution." + You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. - +5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. -"Contributor" shall mean Licensor and any individual or Legal Entity on behalf -of whom a Contribution has been received by Licensor and subsequently incorporated -within the Work. +6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. -2. Grant of Copyright License. Subject to the terms and conditions of this -License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, -no-charge, royalty-free, irrevocable copyright license to reproduce, prepare -Derivative Works of, publicly display, publicly perform, sublicense, and distribute -the Work and such Derivative Works in Source or Object form. +7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. -3. Grant of Patent License. Subject to the terms and conditions of this License, -each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, -no-charge, royalty-free, irrevocable (except as stated in this section) patent -license to make, have made, use, offer to sell, sell, import, and otherwise -transfer the Work, where such license applies only to those patent claims -licensable by such Contributor that are necessarily infringed by their Contribution(s) -alone or by combination of their Contribution(s) with the Work to which such -Contribution(s) was submitted. If You institute patent litigation against -any entity (including a cross-claim or counterclaim in a lawsuit) alleging -that the Work or a Contribution incorporated within the Work constitutes direct -or contributory patent infringement, then any patent licenses granted to You -under this License for that Work shall terminate as of the date such litigation -is filed. +8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. -4. Redistribution. You may reproduce and distribute copies of the Work or -Derivative Works thereof in any medium, with or without modifications, and -in Source or Object form, provided that You meet the following conditions: +9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. -(a) You must give any other recipients of the Work or Derivative Works a copy -of this License; and - -(b) You must cause any modified files to carry prominent notices stating that -You changed the files; and - -(c) You must retain, in the Source form of any Derivative Works that You distribute, -all copyright, patent, trademark, and attribution notices from the Source -form of the Work, excluding those notices that do not pertain to any part -of the Derivative Works; and - -(d) If the Work includes a "NOTICE" text file as part of its distribution, -then any Derivative Works that You distribute must include a readable copy -of the attribution notices contained within such NOTICE file, excluding those -notices that do not pertain to any part of the Derivative Works, in at least -one of the following places: within a NOTICE text file distributed as part -of the Derivative Works; within the Source form or documentation, if provided -along with the Derivative Works; or, within a display generated by the Derivative -Works, if and wherever such third-party notices normally appear. The contents -of the NOTICE file are for informational purposes only and do not modify the -License. You may add Your own attribution notices within Derivative Works -that You distribute, alongside or as an addendum to the NOTICE text from the -Work, provided that such additional attribution notices cannot be construed -as modifying the License. - -You may add Your own copyright statement to Your modifications and may provide -additional or different license terms and conditions for use, reproduction, -or distribution of Your modifications, or for any such Derivative Works as -a whole, provided Your use, reproduction, and distribution of the Work otherwise -complies with the conditions stated in this License. - -5. Submission of Contributions. Unless You explicitly state otherwise, any -Contribution intentionally submitted for inclusion in the Work by You to the -Licensor shall be under the terms and conditions of this License, without -any additional terms or conditions. Notwithstanding the above, nothing herein -shall supersede or modify the terms of any separate license agreement you -may have executed with Licensor regarding such Contributions. - -6. Trademarks. This License does not grant permission to use the trade names, -trademarks, service marks, or product names of the Licensor, except as required -for reasonable and customary use in describing the origin of the Work and -reproducing the content of the NOTICE file. - -7. Disclaimer of Warranty. Unless required by applicable law or agreed to -in writing, Licensor provides the Work (and each Contributor provides its -Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, either express or implied, including, without limitation, any warranties -or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR -A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness -of using or redistributing the Work and assume any risks associated with Your -exercise of permissions under this License. - -8. Limitation of Liability. In no event and under no legal theory, whether -in tort (including negligence), contract, or otherwise, unless required by -applicable law (such as deliberate and grossly negligent acts) or agreed to -in writing, shall any Contributor be liable to You for damages, including -any direct, indirect, special, incidental, or consequential damages of any -character arising as a result of this License or out of the use or inability -to use the Work (including but not limited to damages for loss of goodwill, -work stoppage, computer failure or malfunction, or any and all other commercial -damages or losses), even if such Contributor has been advised of the possibility -of such damages. - -9. Accepting Warranty or Additional Liability. While redistributing the Work -or Derivative Works thereof, You may choose to offer, and charge a fee for, -acceptance of support, warranty, indemnity, or other liability obligations -and/or rights consistent with this License. However, in accepting such obligations, -You may act only on Your own behalf and on Your sole responsibility, not on -behalf of any other Contributor, and only if You agree to indemnify, defend, -and hold each Contributor harmless for any liability incurred by, or claims -asserted against, such Contributor by reason of your accepting any such warranty -or additional liability. END OF TERMS AND CONDITIONS +END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. -To apply the Apache License to your work, attach the following boilerplate -notice, with the fields enclosed by brackets "[]" replaced with your own identifying -information. (Don't include the brackets!) The text should be enclosed in -the appropriate comment syntax for the file format. We also recommend that -a file or class name and description of purpose be included on the same "printed -page" as the copyright notice for easier identification within third-party -archives. +To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/README.md b/README.md index 01d8fdf1..1abd2f0f 100644 --- a/README.md +++ b/README.md @@ -7,14 +7,18 @@ Find here a collection of samples for the [SAP Cloud Application Programming Mod ### Preliminaries -1. [Install @sap/cds-dk](https://cap.cloud.sap/docs/get-started/) as documented in [capire](https://cap.cloud.sap) -2. _Optional:_ [Use Visual Studio Code](https://cap.cloud.sap/docs/get-started/in-vscode) +1. Ensure you have the latest LTS version of Node.js installed (see [Getting Started](https://cap.cloud.sap/docs/get-started/)) +2. Install [**@sap/cds-dk**](https://cap.cloud.sap/docs/get-started/) globally: + ```sh + npm i -g @sap/cds-dk + ``` + +3. _Optional:_ [Use Visual Studio Code](https://cap.cloud.sap/docs/get-started/tools#vscode) ### Download -Clone this repo as shown below, if you have [git](https://git-scm.com/downloads) installed, -otherwise [download as zip file](archive/master.zip). +If you've [Git](https://git-scm.com/downloads) installed, clone this repo as shown below, otherwise [download as ZIP file](archive/main.zip). ```sh git clone https://github.com/sap-samples/cloud-cap-samples samples @@ -39,21 +43,45 @@ cds watch bookshop After that open this link in your browser: [http://localhost:4004](http://localhost:4004) +When asked to log in, type `alice` as user and leave the password field blank, which is the [default user](https://cap.cloud.sap/docs/node.js/authentication#mocked). + ### Testing Run the provided tests with [_jest_](http://jestjs.io) or [_mocha_](http://mochajs.org), for example: + ```sh npx jest ``` > While mocha is a bit smaller and faster, jest runs tests in parallel and isolation, which allows to run all tests. +### Serve `npm` + +We've included a simple npm registry mock, which allows you to do an `npm install @capire/` locally. Use it as follows: + +1. Start the @capire registry: +```sh +npm run registry +``` +> While running this will have `@capire:registry=http://localhost:4444` set with npmrc. + +2. Install one of the @capire packages wherever you like, for example: + +```sh +npm add @capire/common @capire/bookshop +``` + + +## Code Tours + +Take one of the [guided tours](.tours) in VS Code through our CAP samples and learn which CAP features are showcased by the different parts of the repository. Just install the [CodeTour extension](https://marketplace.visualstudio.com/items?itemName=vsls-contrib.codetour) for VS Code. We'll add more code tours in the future. Stay tuned! + ## Get Support Check out the documentation at [https://cap.cloud.sap](https://cap.cloud.sap).
-In case you have a question, find a bug, or otherwise need support, please use our [community](https://answers.sap.com/tags/9f13aee1-834c-4105-8e43-ee442775e5ce). +In case you've a question, find a bug, or otherwise need support, use our [community](https://answers.sap.com/tags/9f13aee1-834c-4105-8e43-ee442775e5ce) to get more visibility. ## License -Copyright (c) 2020 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, version 2.0 except as noted otherwise in the [LICENSE](LICENSES/Apache-2.0.txt) file. +Copyright (c) 2022 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, version 2.0 except as noted otherwise in the [LICENSE](LICENSE) file. diff --git a/bookshop/.env b/bookshop/.env deleted file mode 100644 index 01ade12c..00000000 --- a/bookshop/.env +++ /dev/null @@ -1 +0,0 @@ -cds.features.snapi = y \ No newline at end of file diff --git a/bookshop/app/vue/app.js b/bookshop/app/vue/app.js index 3dd4a2b7..b637d115 100644 --- a/bookshop/app/vue/app.js +++ b/bookshop/app/vue/app.js @@ -3,44 +3,87 @@ const $ = sel => document.querySelector(sel) const GET = (url) => axios.get('/browse'+url) const POST = (cmd,data) => axios.post('/browse'+cmd,data) -const books = new Vue ({ +const books = Vue.createApp ({ - el:'#app', - - data: { + data() { + return { list: [], - book: { descr:'( click on a row to see details... )' }, - order: { amount:1, succeeded:'', failed:'' } + book: undefined, + order: { quantity:1, succeeded:'', failed:'' }, + user: undefined + } }, methods: { - search: ({target:{value:v}}) => books.fetch (v && '$search='+v), + search: ({target:{value:v}}) => books.fetch(v && '&$search='+v), - async fetch (_filter='') { - const columns = 'ID,title,author,price,stock', details = 'genre,currency' - const {data} = await GET(`/Books?$select=${columns}&$expand=${details}&${_filter}`) + async fetch (etc='') { + const {data} = await GET(`/ListOfBooks?$expand=genre,currency${etc}`) books.list = data.value }, - async inspect () { - const book = books.book = books.list [event.currentTarget.rowIndex-1] - book.imageSrc || await GET(`/Books/${book.ID}/image`) .then (({data}) => book.imageSrc = data ) - book.descr || await GET(`/Books/${book.ID}/descr/$value`) .then (({data}) => book.descr = data) - books.order = { amount:1 } + async inspect (eve) { + const book = books.book = books.list [eve.currentTarget.rowIndex-1] + const res = await GET(`/Books/${book.ID}?$select=descr,stock,image`) + Object.assign (book, res.data) + books.order = { quantity:1 } setTimeout (()=> $('form > input').focus(), 111) }, - submitOrder () { event.preventDefault() - const {book,order} = books, amount = parseInt (order.amount) || 1 - POST(`/submitOrder`, { amount, book: book.ID }) - .then (()=> books.order = { amount, succeeded: `Successfully orderd ${amount} item(s).` }) - .catch (e=> books.order = { amount, failed: e.response.data.error.message }) - GET(`/Books/${book.ID}/stock/$value`).then (res => book.stock = res.data) - } + async submitOrder () { + const {book,order} = books, quantity = parseInt (order.quantity) || 1 // REVISIT: Okra should be less strict + try { + const res = await POST(`/submitOrder`, { quantity, book: book.ID }) + book.stock = res.data.stock + books.order = { quantity, succeeded: `Successfully ordered ${quantity} item(s).` } + } catch (e) { + books.order = { quantity, failed: e.response.data.error ? e.response.data.error.message : e.response.data } + } + }, + async login() { + try { + const { data:user } = await axios.post('/user/login',{}) + if (user.id !== 'anonymous') books.user = user + } catch (err) { books.user = { id: err.message } } + }, + + async getUserInfo() { + try { + const { data:user } = await axios.get('/user/me') + if (user.id !== 'anonymous') books.user = user + } catch (err) { books.user = { id: err.message } } + }, } +}).mount('#app') + +books.getUserInfo() +books.fetch() // initially fill list of books + +document.addEventListener('keydown', (event) => { + // hide user info on request + if (event.key === 'u') books.user = undefined }) -// initially fill list of books -books.fetch() +axios.interceptors.request.use(csrfToken) +function csrfToken (request) { + if (request.method === 'head' || request.method === 'get') return request + if ('csrfToken' in document) { + request.headers['x-csrf-token'] = document.csrfToken + return request + } + return fetchToken().then(token => { + document.csrfToken = token + request.headers['x-csrf-token'] = document.csrfToken + return request + }).catch(_ => { + document.csrfToken = null // set mark to not try again + return request + }) + + function fetchToken() { + return axios.get('/', { headers: { 'x-csrf-token': 'fetch' } }) + .then(res => res.headers['x-csrf-token']) + } +} \ No newline at end of file diff --git a/bookshop/app/vue/index.html b/bookshop/app/vue/index.html index 51408d43..9795a65a 100644 --- a/bookshop/app/vue/index.html +++ b/bookshop/app/vue/index.html @@ -5,56 +5,71 @@ Capire Books - +
+
+
+
Tenant: {{ user.tenant }}
+
User: {{ user.id }}
+
Locale: {{ user.locale }}
+
+
+ + +
+
+

Capire Books

- +
+ - + +
Book Author Genre Rating Price
{{ book.title }} {{ book.author }} {{ book.genre.name }}{{ book.currency.symbol }} {{ book.price }} + {{ ('★'.repeat(Math.round(book.rating))+'☆☆☆☆☆').slice(0,5) }} ({{ book.numberOfReviews }}) + {{ book.currency && book.currency.symbol }} {{ book.price }}
-
- -
- -
+
+ -
- + +
+

{{ book.title }}

+

{{ book.descr }}

+
+
+ ( click on a row to see details... )
- -

{{ book.title }}

-

{{ book.descr }}

diff --git a/bookshop/db/data/_sap.capire.bookshop-Books.csv b/bookshop/db/data/_sap.capire.bookshop-Books.csv index cb3044aa..bfe13f2c 100644 --- a/bookshop/db/data/_sap.capire.bookshop-Books.csv +++ b/bookshop/db/data/_sap.capire.bookshop-Books.csv @@ -2,5 +2,5 @@ ID;title;descr;author_ID;stock;price;currency_code;genre_ID 201;Wuthering Heights;"Wuthering Heights, Emily Brontë's only novel, was published in 1847 under the pseudonym ""Ellis Bell"". It was written between October 1845 and June 1846. Wuthering Heights and Anne Brontë's Agnes Grey were accepted by publisher Thomas Newby before the success of their sister Charlotte's novel Jane Eyre. After Emily's death, Charlotte edited the manuscript of Wuthering Heights and arranged for the edited version to be published as a posthumous second edition in 1850.";101;12;11.11;GBP;11 207;Jane Eyre;"Jane Eyre /ɛər/ (originally published as Jane Eyre: An Autobiography) is a novel by English writer Charlotte Brontë, published under the pen name ""Currer Bell"", on 16 October 1847, by Smith, Elder & Co. of London. The first American edition was published the following year by Harper & Brothers of New York. Primarily a bildungsroman, Jane Eyre follows the experiences of its eponymous heroine, including her growth to adulthood and her love for Mr. Rochester, the brooding master of Thornfield Hall. The novel revolutionised prose fiction in that the focus on Jane's moral and spiritual development is told through an intimate, first-person narrative, where actions and events are coloured by a psychological intensity. The book contains elements of social criticism, with a strong sense of Christian morality at its core and is considered by many to be ahead of its time because of Jane's individualistic character and how the novel approaches the topics of class, sexuality, religion and feminism.";107;11;12.34;GBP;11 251;The Raven;"""The Raven"" is a narrative poem by American writer Edgar Allan Poe. First published in January 1845, the poem is often noted for its musicality, stylized language, and supernatural atmosphere. It tells of a talking raven's mysterious visit to a distraught lover, tracing the man's slow fall into madness. The lover, often identified as being a student, is lamenting the loss of his love, Lenore. Sitting on a bust of Pallas, the raven seems to further distress the protagonist with its constant repetition of the word ""Nevermore"". The poem makes use of folk, mythological, religious, and classical references.";150;333;13.13;USD;16 -252;Eleonora;"""Eleonora"" is a short story by Edgar Allan Poe, first published in 1842 in Philadelphia in the literary annual The Gift. It is often regarded as somewhat autobiographical and has a relatively ""happy"" ending.";150;555;14;USD;16 -271;Catweazle;Catweazle is a British fantasy television series, starring Geoffrey Bayldon in the title role, and created by Richard Carpenter for London Weekend Television. The first series, produced and directed by Quentin Lawrence, was screened in the UK on ITV in 1970. The second series, directed by David Reid and David Lane, was shown in 1971. Each series had thirteen episodes, most but not all written by Carpenter, who also published two books based on the scripts.;170;22;15;EUR;13 \ No newline at end of file +252;Eleonora;"""Eleonora"" is a short story by Edgar Allan Poe, first published in 1842 in Philadelphia in the literary annual The Gift. It is often regarded as somewhat autobiographical and has a relatively ""happy"" ending.";150;555;14;USD;15 +271;Catweazle;Catweazle is a British fantasy television series, starring Geoffrey Bayldon in the title role, and created by Richard Carpenter for London Weekend Television. The first series, produced and directed by Quentin Lawrence, was screened in the UK on ITV in 1970. The second series, directed by David Reid and David Lane, was shown in 1971. Each series had thirteen episodes, most but not all written by Carpenter, who also published two books based on the scripts.;170;22;150;JPY;13 \ No newline at end of file diff --git a/bookshop/db/init.js b/bookshop/db/init.js new file mode 100644 index 00000000..bfa0fc89 --- /dev/null +++ b/bookshop/db/init.js @@ -0,0 +1,24 @@ +/** + * In order to keep basic bookshop sample as simple as possible, we don't add + * reuse dependencies. This db/init.js ensures we still have a minimum set of + * currencies, if not obtained through @capire/common. + */ + +module.exports = async (tx)=>{ + + const has_common = tx.model.definitions['sap.common.Currencies']?.elements.numcode + if (has_common) return + + const already_filled = await tx.exists('sap.common.Currencies',{code:'EUR'}) + if (already_filled) return + + await tx.run (INSERT.into ('sap.common.Currencies') .columns ( + [ 'code', 'symbol', 'name' ] + ) .rows ( + [ 'EUR', '€', 'Euro' ], + [ 'USD', '$', 'US Dollar' ], + [ 'GBP', '£', 'British Pound' ], + [ 'ILS', '₪', 'Shekel' ], + [ 'JPY', '¥', 'Yen' ], + )) +} diff --git a/bookshop/db/schema.cds b/bookshop/db/schema.cds index 99fadb5a..ec8b119a 100644 --- a/bookshop/db/schema.cds +++ b/bookshop/db/schema.cds @@ -8,7 +8,7 @@ entity Books : managed { author : Association to Authors; genre : Association to Genres; stock : Integer; - price : Decimal(9,2); + price : Decimal; currency : Currency; image : LargeBinary @Core.MediaType : 'image/png'; } diff --git a/bookshop/index.cds b/bookshop/index.cds index 161677cd..7d683805 100644 --- a/bookshop/index.cds +++ b/bookshop/index.cds @@ -2,3 +2,4 @@ namespace sap.capire.bookshop; //> important for reflection using from './db/schema'; using from './srv/cat-service'; using from './srv/admin-service'; +using from './srv/user-service'; diff --git a/bookshop/index.js b/bookshop/index.js index 0f7a3ffa..7bffbe36 100644 --- a/bookshop/index.js +++ b/bookshop/index.js @@ -1 +1,2 @@ -exports.CatalogService = require('./srv/cat-service') +const { CatalogService } = require('./srv/cat-service') +module.exports = { CatalogService } diff --git a/bookshop/package.json b/bookshop/package.json index b1712e39..21b048d7 100644 --- a/bookshop/package.json +++ b/bookshop/package.json @@ -2,10 +2,17 @@ "name": "@capire/bookshop", "version": "1.0.0", "description": "A simple self-contained bookshop service.", + "files": [ + "app", + "srv", + "db", + "index.cds", + "index.js" + ], "dependencies": { - "@capire/common": "../common", - "@sap/cds": "^4", - "express": "^4.17.1" + "@sap/cds": ">=5.9", + "express": "^4.17.1", + "passport": ">=0.4.1" }, "scripts": { "genres": "cds serve test/genres.cds", @@ -14,9 +21,7 @@ }, "cds": { "requires": { - "db": { - "kind": "sql" - } + "db": "sql" } } } diff --git a/bookshop/readme.md b/bookshop/readme.md index 5b3e9144..6a14f968 100644 --- a/bookshop/readme.md +++ b/bookshop/readme.md @@ -5,10 +5,10 @@ This stand-alone sample introduces the essential tasks in the development of CAP ## Hypothetical Use Cases 1. Build a service that allows to browse _Books_ and _Authors_. -2. Books have assigned _Genres_ which are organized hierarchically. +2. Books have assigned _Genres_, which are organized hierarchically. 3. All users may browse books without login. 4. All entries are maintained by Administrators. -5. End users may order books (the actual order mgmt being out of scope) +5. End users may order books (the actual order mgmt being out of scope). ## Running the Sample @@ -20,12 +20,12 @@ npm run watch | Links to capire | Sample files / folders | | --------------------------------------------------------------------------------------------------------- | ------------------------------------ | -| [Project Setup and Layouts](https://cap.cloud.sap/docs/get-started/projects#sharing-and-reusing-content) | [`./`](./) | -| [Defining Domain Models](https://cap.cloud.sap/docs/guides/domain-models) | [`./db/schema.cds`](./db/schema.cds) | -| [Defining Services](https://cap.cloud.sap/docs/guides/providing-services) | [`./srv/*.cds`](./srv) | -| [Single-purposed Services](https://cap.cloud.sap/docs/guides/providing-services#single-purposed-services) | [`./srv/*.cds`](./srv) | -| [Generic Providers](https://cap.cloud.sap/docs/guides/providing-services) | http://localhost:4004 | -| Using Databases | [`./db/data/*.csv`](./db/data) | +| [Project Setup & Layouts](https://cap.cloud.sap/docs/get-started/projects#sharing-and-reusing-content) | [`./`](./) | +| [Domain Modeling with CDS](https://cap.cloud.sap/docs/guides/domain-models) | [`./db/schema.cds`](./db/schema.cds) | +| [Defining Services](https://cap.cloud.sap/docs/guides/services#defining-services) | [`./srv/*.cds`](./srv) | +| [Single-purposed Services](https://cap.cloud.sap/docs/guides/services#single-purposed-services) | [`./srv/*.cds`](./srv) | +| [Providing & Consuming Providers](https://cap.cloud.sap/docs/guides/providing-services) | http://localhost:4004 | +| [Using Databases](https://cap.cloud.sap/docs/guides/databases) | [`./db/data/*.csv`](./db/data) | | [Adding Custom Logic](https://cap.cloud.sap/docs/guides/service-impl) | [`./srv/*.js`](./srv) | -| Adding Tests | [`./test`](./test) | -| [Sharing for Reuse](https://cap.cloud.sap/docs/get-started/projects#sharing-and-reusing-content) | [`./index.cds`](./index.cds) | +| Adding Tests | [`./test`](./test) | +| [Sharing for Reuse](https://cap.cloud.sap/docs/guides/reuse-and-compose) | [`./index.cds`](./index.cds) | diff --git a/bookshop/srv/admin-service.cds b/bookshop/srv/admin-service.cds index 8939262f..ea9b0731 100644 --- a/bookshop/srv/admin-service.cds +++ b/bookshop/srv/admin-service.cds @@ -1,5 +1,5 @@ using { sap.capire.bookshop as my } from '../db/schema'; -service AdminService @(requires_:'admin') { +service AdminService @(requires:'admin') { entity Books as projection on my.Books; entity Authors as projection on my.Authors; } diff --git a/bookshop/srv/admin-service.js b/bookshop/srv/admin-service.js new file mode 100644 index 00000000..7a5d5804 --- /dev/null +++ b/bookshop/srv/admin-service.js @@ -0,0 +1,13 @@ +const cds = require('@sap/cds/lib') + +module.exports = class AdminService extends cds.ApplicationService { init(){ + this.before ('NEW','Authors', genid) + this.before ('NEW','Books', genid) + return super.init() +}} + +/** Generate primary keys for target entity in request */ +async function genid (req) { + const {ID} = await cds.tx(req).run (SELECT.one.from(req.target).columns('max(ID) as ID')) + req.data.ID = ID - ID % 100 + 100 + 1 +} diff --git a/bookshop/srv/cat-service.cds b/bookshop/srv/cat-service.cds index 07031ea6..916a9d2e 100644 --- a/bookshop/srv/cat-service.cds +++ b/bookshop/srv/cat-service.cds @@ -1,10 +1,21 @@ using { sap.capire.bookshop as my } from '../db/schema'; service CatalogService @(path:'/browse') { - @readonly entity Books as SELECT from my.Books {*, + /** For displaying lists of Books */ + @readonly entity ListOfBooks as projection on Books + excluding { descr }; + + /** For display in details pages */ + @readonly entity Books as projection on my.Books { *, author.name as author } excluding { createdBy, modifiedBy }; +<<<<<<< HEAD @requires_: 'authenticated-user' action submitOrder (book : Integer, amount: Integer); +======= + @requires: 'authenticated-user' + action submitOrder ( book: Books:ID, quantity: Integer ) returns { stock: Integer }; + event OrderedBook : { book: Books:ID; quantity: Integer; buyer: String }; +>>>>>>> 534af7ffee60e086c563dbaa450e86e5fca5cf2b } diff --git a/bookshop/srv/cat-service.js b/bookshop/srv/cat-service.js index 4352c5e7..3c557078 100644 --- a/bookshop/srv/cat-service.js +++ b/bookshop/srv/cat-service.js @@ -1,22 +1,29 @@ const cds = require('@sap/cds') -module.exports = async function (){ - const db = await cds.connect.to('db') // connect to database service - const { Books } = db.entities // get reflected definitions +class CatalogService extends cds.ApplicationService { init(){ + + const { Books } = cds.entities ('sap.capire.bookshop') + const { ListOfBooks } = this.entities // Reduce stock of ordered books if available stock suffices this.on ('submitOrder', async req => { - const {book,amount} = req.data - const n = await UPDATE (Books, book) - .with ({ stock: {'-=': amount }}) - .where ({ stock: {'>=': amount }}) - n > 0 || req.error (409,`${amount} exceeds stock for book #${book}`) + const {book,quantity} = req.data + if (quantity < 1) return req.reject (400,`quantity has to be 1 or more`) + let b = await SELECT `stock` .from (Books,book) + if (!b) return req.error (404,`Book #${book} doesn't exist`) + let {stock} = b + if (quantity > stock) return req.reject (409,`${quantity} exceeds stock for book #${book}`) + await UPDATE (Books,book) .with ({ stock: stock -= quantity }) + await this.emit ('OrderedBook', { book, quantity, buyer:req.user.id }) + return { stock } }) // Add some discount for overstocked books - this.after ('READ','Books', each => { - if (each.stock > 111) { - each.title += ` -- 11% discount!` - } + this.after ('READ', ListOfBooks, each => { + if (each.stock > 111) each.title += ` -- 11% discount!` }) -} + + return super.init() +}} + +module.exports = { CatalogService } diff --git a/bookshop/srv/user-service.cds b/bookshop/srv/user-service.cds new file mode 100644 index 00000000..09b7676f --- /dev/null +++ b/bookshop/srv/user-service.cds @@ -0,0 +1,15 @@ +/** + * Exposes user information + */ +service UserService { + /** + * The current user + */ + @odata.singleton entity me @cds.persistence.skip { + id : String; // user id + locale : String; + tenant : String; + } + + action login() returns me; +} diff --git a/bookshop/srv/user-service.js b/bookshop/srv/user-service.js new file mode 100644 index 00000000..2ecb68d9 --- /dev/null +++ b/bookshop/srv/user-service.js @@ -0,0 +1,9 @@ +const cds = require('@sap/cds') +module.exports = class UserService extends cds.Service { init(){ + this.on('READ', 'me', ({ tenant, user, locale }) => ({ id: user.id, locale, tenant })) + this.on('login', (req) => { + if (req.user._is_anonymous) + req._.res.set('WWW-Authenticate','Basic realm="Users"').sendStatus(401) + else return this.read('me') + }) +}} diff --git a/bookshop/test/requests.http b/bookshop/test/requests.http index 6c6428a0..cbd8faff 100644 --- a/bookshop/test/requests.http +++ b/bookshop/test/requests.http @@ -16,9 +16,9 @@ GET {{server}}/browse/$metadata ### ------------------------------------------------------------------------ # Browse Books as any user -GET {{server}}/browse/Books? +GET {{server}}/browse/ListOfBooks? # &$select=title,stock - # &$expand=currency + &$expand=genre # &sap-language=de {{me}} @@ -32,10 +32,24 @@ GET {{server}}/admin/Authors? # &sap-language=de Authorization: Basic alice: +### ------------------------------------------------------------------------ +# Create Author +POST {{server}}/admin/Authors +Content-Type: application/json;IEEE754Compatible=true +Authorization: Basic alice: + +{ + "ID": 112, + "name": "Shakespeeeeere", + "age": 22 +} + + ### ------------------------------------------------------------------------ # Create book POST {{server}}/admin/Books Content-Type: application/json;IEEE754Compatible=true +Authorization: Basic alice: { "ID": 2, @@ -53,6 +67,7 @@ Content-Type: application/json;IEEE754Compatible=true # Put image to books PUT {{server}}/admin/Books(2)/image Content-Type: image/png +Authorization: Basic alice: data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAANwAAADcCAYAAAAbWs+BAAAGwElEQVR4Ae3cwZFbNxBFUY5rkrDTmKAUk5QT03Aa44U22KC7NHptw+DRikVAXf8fzC3u8Hj4R4AAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAgZzAW26USQT+e4HPx+Mz+RRvj0e0kT+SD2cWAQK1gOBqH6sEogKCi3IaRqAWEFztY5VAVEBwUU7DCNQCgqt9rBKICgguymkYgVpAcLWPVQJRAcFFOQ0jUAsIrvaxSiAqILgop2EEagHB1T5WCUQFBBflNIxALSC42scqgaiA4KKchhGoBQRX+1glEBUQXJTTMAK1gOBqH6sEogKCi3IaRqAWeK+Xb1z9iN558fHxcSPS9p2ezx/ROz4e4TtIHt+3j/61hW9f+2+7/+UXbifjewIDAoIbQDWSwE5AcDsZ3xMYEBDcAKqRBHYCgtvJ+J7AgIDgBlCNJLATENxOxvcEBgQEN4BqJIGdgOB2Mr4nMCAguAFUIwnsBAS3k/E9gQEBwQ2gGklgJyC4nYzvCQwICG4A1UgCOwHB7WR8T2BAQHADqEYS2AkIbifjewIDAoIbQDWSwE5AcDsZ3xMYEEjfTzHwiK91B8npd6Q8n8/oGQ/ckRJ9vvQwv3BpUfMIFAKCK3AsEUgLCC4tah6BQkBwBY4lAmkBwaVFzSNQCAiuwLFEIC0guLSoeQQKAcEVOJYIpAUElxY1j0AhILgCxxKBtIDg0qLmESgEBFfgWCKQFhBcWtQ8AoWA4AocSwTSAoJLi5pHoBAQXIFjiUBaQHBpUfMIFAKCK3AsEUgLCC4tah6BQmDgTpPsHSTFs39p6fQ7Q770UsV/Ov19X+2OFL9wxR+rJQJpAcGlRc0jUAgIrsCxRCAtILi0qHkECgHBFTiWCKQFBJcWNY9AISC4AscSgbSA4NKi5hEoBARX4FgikBYQXFrUPAKFgOAKHEsE0gKCS4uaR6AQEFyBY4lAWkBwaVHzCBQCgitwLBFICwguLWoegUJAcAWOJQJpAcGlRc0jUAgIrsCxRCAt8J4eePq89B0ar3ZnyOnve/rfn1+400/I810lILirjtPLnC4guNNPyPNdJSC4q47Ty5wuILjTT8jzXSUguKuO08ucLiC400/I810lILirjtPLnC4guNNPyPNdJSC4q47Ty5wuILjTT8jzXSUguKuO08ucLiC400/I810lILirjtPLnC4guNNPyPNdJSC4q47Ty5wuILjTT8jzXSUguKuO08ucLiC400/I810l8JZ/m78+szP/zI47fJo7Q37vgJ7PHwN/07/3TOv/9gu3avhMYFhAcMPAxhNYBQS3avhMYFhAcMPAxhNYBQS3avhMYFhAcMPAxhNYBQS3avhMYFhAcMPAxhNYBQS3avhMYFhAcMPAxhNYBQS3avhMYFhAcMPAxhNYBQS3avhMYFhAcMPAxhNYBQS3avhMYFhAcMPAxhNYBQS3avhMYFhAcMPAxhNYBQS3avhMYFhg4P6H9J0maYHXuiMlrXf+vOfA33Turf3C5SxNItAKCK4lsoFATkBwOUuTCLQCgmuJbCCQExBcztIkAq2A4FoiGwjkBASXszSJQCsguJbIBgI5AcHlLE0i0AoIriWygUBOQHA5S5MItAKCa4lsIJATEFzO0iQCrYDgWiIbCOQEBJezNIlAKyC4lsgGAjkBweUsTSLQCgiuJbKBQE5AcDlLkwi0Akff//Dz6U+/I6U1/sUNr3bnytl3kPzi4bXb/cK1RDYQyAkILmdpEoFWQHAtkQ0EcgKCy1maRKAVEFxLZAOBnIDgcpYmEWgFBNcS2UAgJyC4nKVJBFoBwbVENhDICQguZ2kSgVZAcC2RDQRyAoLLWZpEoBUQXEtkA4GcgOByliYRaAUE1xLZQCAnILicpUkEWgHBtUQ2EMgJCC5naRKBVkBwLZENBHIC/4M7TXIv+3PS22d24qvdQfL3C/7N5P5i/MLlLE0i0AoIriWygUBOQHA5S5MItAKCa4lsIJATEFzO0iQCrYDgWiIbCOQEBJezNIlAKyC4lsgGAjkBweUsTSLQCgiuJbKBQE5AcDlLkwi0AoJriWwgkBMQXM7SJAKtgOBaIhsI5AQEl7M0iUArILiWyAYCOQHB5SxNItAKCK4lsoFATkBwOUuTCBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIDAvyrwDySEJ2VQgUSoAAAAAElFTkSuQmCC @@ -69,7 +84,7 @@ POST {{server}}/browse/submitOrder Content-Type: application/json {{me}} -{ "book":201, "amount":5 } +{ "book":201, "quantity":5 } ### ------------------------------------------------------------------------ @@ -78,4 +93,3 @@ GET {{server}}/browse/Genres? # &$filter=parent_ID eq null&$select=name # &$expand=children($select=name) {{me}} - diff --git a/bookstore/index.cds b/bookstore/index.cds new file mode 100644 index 00000000..ac2accff --- /dev/null +++ b/bookstore/index.cds @@ -0,0 +1,2 @@ +namespace sap.capire.bookshop; //> important for reflection +using from './srv/mashup'; diff --git a/bookstore/package.json b/bookstore/package.json new file mode 100644 index 00000000..7802fcef --- /dev/null +++ b/bookstore/package.json @@ -0,0 +1,34 @@ +{ + "name": "@capire/bookstore", + "version": "1.0.0", + "dependencies": { + "@capire/bookshop": "*", + "@capire/reviews": "*", + "@capire/orders": "*", + "@capire/common": "*", + "@capire/data-viewer": "*", + "@sap/cds": ">=5", + "express": "^4.17.1" + }, + "cds": { + "requires": { + "ReviewsService": { + "kind": "odata", + "model": "@capire/reviews" + }, + "OrdersService": { + "kind": "odata", + "model": "@capire/orders" + }, + "messaging": { + "[development]": { "kind": "file-based-messaging" }, + "[hybrid]": { "kind": "enterprise-messaging-shared" }, + "[production]": { "kind": "enterprise-messaging" } + }, + "db": { + "kind": "sql" + } + }, + "log": { "service": true } + } +} \ No newline at end of file diff --git a/bookstore/server.js b/bookstore/server.js new file mode 100644 index 00000000..26f5d843 --- /dev/null +++ b/bookstore/server.js @@ -0,0 +1,22 @@ +const cds = require ('@sap/cds') + +// Add mashup logic +cds.once('served', require('./srv/mashup')) + +// Add routes to UIs from imported packages +cds.once('bootstrap',(app)=>{ + app.serve ('/bookshop') .from ('@capire/bookshop','app/vue') + app.serve ('/reviews') .from ('@capire/reviews','app/vue') + app.serve ('/orders') .from('@capire/orders','app/orders') + app.serve ('/data') .from('@capire/data-viewer','app/viewer') +}) + +// Add Swagger UI +require('./srv/swagger-ui') + +// Returning cds.server +module.exports = cds.server + +// For didactic reasons in capire +const { ReviewsService, OrdersService } = cds.requires +if (!ReviewsService?.credentials && !OrdersService?.credentials) cds.requires.messaging = false diff --git a/bookstore/srv/mashup.cds b/bookstore/srv/mashup.cds new file mode 100644 index 00000000..7344ff1a --- /dev/null +++ b/bookstore/srv/mashup.cds @@ -0,0 +1,42 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Enhancing bookshop with Reviews and Orders provided through +// respective reuse packages and services +// + +using { sap.capire.bookshop.Books } from '@capire/bookshop'; + +// +// Extend Books with access to Reviews and average ratings +// +using { ReviewsService.Reviews } from '@capire/reviews'; +extend Books with { + reviews : Composition of many Reviews on reviews.subject = $self.ID; + + @Common.Label : '{i18n>Rating}' + rating : Decimal; + + @Common.Label : '{i18n>NumberOfReviews}' + numberOfReviews : Integer; +} + + +// +// Extend Orders with Books as Products +// +using { sap.capire.orders.Orders } from '@capire/orders'; +extend Orders with { + extend Items with { + book : Association to Books on product.ID = book.ID + } +} + + +// Add orders fiori app (in case of embedded orders service) +using from '@capire/orders/app/fiori'; + +// Add data browser +using from '@capire/data-viewer'; + +// Incorporate pre-build extensions from... +using from '@capire/common'; diff --git a/bookstore/srv/mashup.js b/bookstore/srv/mashup.js new file mode 100644 index 00000000..bd8aa0f9 --- /dev/null +++ b/bookstore/srv/mashup.js @@ -0,0 +1,58 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Mashing up bookshop services with required services... +// +module.exports = async()=>{ // called by server.js + + const cds = require('@sap/cds') + const CatalogService = await cds.connect.to ('CatalogService') + const ReviewsService = await cds.connect.to ('ReviewsService') + const OrdersService = await cds.connect.to ('OrdersService') + const db = await cds.connect.to ('db') + + // reflect entity definitions used below... + const { Books } = db.entities ('sap.capire.bookshop') + + // + // Delegate requests to read reviews to the ReviewsService + // Note: prepend is neccessary to intercept generic default handler + // + CatalogService.prepend (srv => srv.on ('READ', 'Books/reviews', (req) => { + console.debug ('> delegating request to ReviewsService') + const [id] = req.params, { columns, limit } = req.query.SELECT + return ReviewsService.read ('Reviews',columns).limit(limit).where({subject:String(id)}) + })) + + // + // Create an order with the OrdersService when CatalogService signals a new order + // + CatalogService.on ('OrderedBook', async (msg) => { + const { book, quantity, buyer } = msg.data + const { title, price } = await db.tx(msg).read (Books, book, b => { b.title, b.price }) + return OrdersService.tx(msg).create ('Orders').entries({ + OrderNo: 'Order at '+ (new Date).toLocaleString(), + Items: [{ product:{ID:`${book}`}, title, price, quantity }], + buyer, createdBy: buyer + }) + }) + + // + // Update Books' average ratings when ReviewsService signals updated reviews + // + ReviewsService.on ('reviewed', (msg) => { + console.debug ('> received:', msg.event, msg.data) + const { subject, count, rating } = msg.data + return UPDATE(Books,subject).with({ numberOfReviews:count, rating }) + }) + + // + // Reduce stock of ordered books for orders are created from Orders admin UI + // + OrdersService.on ('OrderChanged', (msg) => { + console.debug ('> received:', msg.event, msg.data) + const { product, deltaQuantity } = msg.data + return UPDATE (Books) .where ('ID =', product) + .and ('stock >=', deltaQuantity) + .set ('stock -=', deltaQuantity) + }) +} diff --git a/bookstore/srv/swagger-ui.js b/bookstore/srv/swagger-ui.js new file mode 100644 index 00000000..22fe3a18 --- /dev/null +++ b/bookstore/srv/swagger-ui.js @@ -0,0 +1,10 @@ + +// ----------------------------------------------------------------------- +// Adding Swagger UI - see https://cap.cloud.sap/docs/advanced/openapi +const cds = require ('@sap/cds') +try { + const cds_swagger = require ('cds-swagger-ui-express') + cds.once ('bootstrap', app => app.use (cds_swagger()) ) +} catch (err) { + if (err.code !== 'MODULE_NOT_FOUND') throw err +} diff --git a/bookstore/test/requests.http b/bookstore/test/requests.http new file mode 100644 index 00000000..c42b4bd4 --- /dev/null +++ b/bookstore/test/requests.http @@ -0,0 +1,81 @@ + +@bookshop = http://localhost:4004 +@reviews-service = {{bookshop}}/reviews +# Uncomment this when running a separate reviews service +# @reviews-service = http://localhost:4005/reviews + + + +################################################# +# +# Reviews Service +# + +GET {{reviews-service}}/Reviews + +### + +POST {{reviews-service}}/Reviews +Authorization: Basic {{$processEnv USER}}: +Content-Type: application/json + +{"subject":"201", "title":"boo", "rating":3 } + + + +################################################# +# +# Bookshop Services +# + +GET {{bookshop}}/browse/Books/201/reviews? +&$select=rating,date,title +&$top=3 + +### + +GET {{bookshop}}/browse/Books(201)? +&$select=ID,title,rating +&$expand=reviews + +### + +GET {{bookshop}}/browse/Books? + &$select=title,author&$expand=currency +Accept-Language: de + +################################################# +# +# Orders Service, incl. draft choreography +# +@newOrderID = e939604c-ab83-4d4f-bdb6-95fe30b3773e + +GET {{bookshop}}/orders/Orders + +### Create order, still inactive +POST {{bookshop}}/orders/Orders +Content-Type: application/json + +{"ID": "{{newOrderID}}"} + +### Get inactive order. We have to specify `IsActiveEntity`. +GET {{bookshop}}/orders/Orders(ID={{newOrderID}},IsActiveEntity=false) + +### Activate order using `.../.draftActivate` +POST {{bookshop}}/orders/Orders(ID={{newOrderID}},IsActiveEntity=false)/OrdersService.draftActivate +Content-Type: application/json + +### Get active order +GET {{bookshop}}/orders/Orders(ID={{newOrderID}},IsActiveEntity=true) + +### Create author +POST {{bookshop}}/admin/Authors +Content-Type: application/json +Authorization: Basic alice: + +{ + "ID": 200, + "name": "William Shakespeare", + "dateOfBirth": "1564-04-26", + "dateOfDeath": "1616-04-23" +} diff --git a/common/data/sap.common-Currencies_texts.csv b/common/data/sap.common-Currencies_texts.csv index 4d2ead51..4c46cefd 100644 --- a/common/data/sap.common-Currencies_texts.csv +++ b/common/data/sap.common-Currencies_texts.csv @@ -5,9 +5,11 @@ CAD;de;Kanadischer Dollar;Kanadischer Dollar AUD;de;Australischer Dollar;Australischer Dollar GBP;de;Pfund;Britische Pfund ILS;de;Schekel;Israelische Schekel +JPY;de;Yen;Japanische Yen EUR;fr;euro;de la Zone euro USD;fr;dollar;dollar des États-Unis CAD;fr;dollar canadien;dollar canadien AUD;fr;dollar australien;dollar australien GBP;fr;livre sterling;pound sterling -ILS;fr;Shekel;shekel israelien \ No newline at end of file +ILS;fr;Shekel;shekel israelien +JPY;fr;Yen;Yen japonais \ No newline at end of file diff --git a/common/index.cds b/common/index.cds index 39e42d28..cb89e28d 100644 --- a/common/index.cds +++ b/common/index.cds @@ -20,7 +20,7 @@ extend sap.common.Currencies with { * annotate sap.common.Countries with @cds.persistence.skip:false; */ -context sap.common_countries { +context sap.common.countries { extend sap.common.Countries { regions : Composition of many Regions on regions._parent = $self.code; diff --git a/common/package.json b/common/package.json index d5c6dc24..35e537aa 100644 --- a/common/package.json +++ b/common/package.json @@ -1,4 +1,8 @@ { "name": "@capire/common", - "version": "1.0.0" + "description": "Provides a pre-built extension package for std @sap/cds/common", + "version": "1.0.0", + "dependencies": { + "@sap/cds": "*" + } } diff --git a/data-viewer/app/viewer/app.js b/data-viewer/app/viewer/app.js new file mode 100644 index 00000000..51130af0 --- /dev/null +++ b/data-viewer/app/viewer/app.js @@ -0,0 +1,119 @@ +/* global Vue axios */ //> from vue.html +const GET = (url) => axios.get('/-data'+url) +const storageGet = (key, def) => localStorage.getItem('data-viewer:'+key) || def +const storageSet = (key, val) => localStorage.setItem('data-viewer:'+key, val) +const columnKeysFirst = (c1, c2) => { + if (c1.isKey && !c2.isKey) return -1 + if (!c1.isKey && c2.isKey) return 1 + if (c1.isKey && c2.isKey) return c1.name.localeCompare(c2.name) + return 0 // retain natural order of normal columns +} + +const vue = Vue.createApp ({ + + data() { return { + error: undefined, + dataSource: storageGet('data-source', 'db'), + skip: storageGet('skip', 0), + top: storageGet('top', 20), + entity: storageGet('entity') ? JSON.parse(storageGet('entity')) : undefined, + entities: [], + columns: [], + data: [], + rowDetails: {}, + rowKey: storageGet('rowKey') + }}, + + watch: { + dataSource: (v) => { storageSet('data-source', v); vue.fetchEntities() }, + skip: (v) => { storageSet('skip', v); if (vue.entity) vue.fetchData() }, + top: (v) => { storageSet('top', v); if (vue.entity) vue.fetchData() }, + }, + + methods: { + + async fetchEntities () { + let url = `/Entities` + if (vue.dataSource === 'db') url += `?dataSource=db` + const {data} = await GET(url) + vue.entities = data.value + vue.entities.forEach(entity => entity.columns.sort(columnKeysFirst)) + const entity = vue.entity && vue.entities.find(e => e.name === vue.entity.name) + if (entity) { // restore selection from previous fetch + vue.columns = entity.columns + await vue.fetchData(entity) + } else { + vue.entity = undefined + vue.columns = [] + vue.data = [] + vue.rowDetails = {} + } + }, + + async inspectEntity (eve) { + const entity = vue.entity = vue.entities [eve.currentTarget.rowIndex-1] + storageSet('entity', JSON.stringify(entity)) + vue.columns = vue.entities.find(e => e.name === entity.name).columns + return await this.fetchData() + }, + + async fetchData () { + let url = `/Data?entity=${vue.entity.name}&$skip=${vue.skip}&$top=${vue.top}` + if (vue.dataSource === 'db') url += `&dataSource=db` + + try { + const {data} = await GET(url) + // sort data along column order + const columnIndexes = {} + vue.columns.forEach((col, i) => columnIndexes[col.name] = i) + vue.data = data.value.map(d => d.record + .sort((r1, r2) => columnIndexes[r1.column] - columnIndexes[r2.column]) + .map(r => r.data) + ) + const row = vue.data.find(data => vue._makeRowKey(data) === vue.rowKey) + if (row) vue._setRowDetails(row) + else vue.rowDetails = {} + vue.error = undefined + } catch (err) { + vue.data = [] + vue.rowDetails = {} + if (err.response?.data?.error) { + vue.error = err.response.data.error + } else { + vue.error = { code:err.code, message:err.message } + } + } + + }, + + inspectRow (eve) { + vue.rowDetails = {} + const selectedRow = eve.currentTarget.rowIndex-1 + vue.rowKey = vue._makeRowKey(vue.data[selectedRow]) + storageSet('rowKey', vue.rowKey) + vue._setRowDetails(vue.data[selectedRow]) + }, + + _setRowDetails(row) { + vue.rowDetails = {} + row.forEach((line, colIndex) => { + vue.rowDetails[vue.columns[colIndex].name] = line + }) + }, + + _makeRowKey(row) { + // to identify a row, build a key string out of all key columns' values + return row + .filter((_, colIndex) => vue.columns[colIndex] && vue.columns[colIndex].isKey) + .reduce(((prev, next) => prev += next), '') + }, + + isActiveRow(row) { + return vue._makeRowKey(row) === vue.rowKey + } + + } +}) +.mount('#app') + +vue.fetchEntities() diff --git a/data-viewer/app/viewer/index.html b/data-viewer/app/viewer/index.html new file mode 100644 index 00000000..9fd723a1 --- /dev/null +++ b/data-viewer/app/viewer/index.html @@ -0,0 +1,95 @@ + + + + + Data Browser + + + + + + + + + +
+ +

Data Browser – {{ entity ? entity.name : '' }}

+ +
+ + +
+
+ + + + +
+
+ + + + + + + +
{{ col.name }}
{{ d }}
+
+
+ Error: {{ error.code ? error.code + ' – ' + error.message : error.message }} +
+

+
+ + + + + +
{{ value }}{{ key }}
+
+
+
+ +
+ + + diff --git a/data-viewer/index.cds b/data-viewer/index.cds new file mode 100644 index 00000000..d16b292c --- /dev/null +++ b/data-viewer/index.cds @@ -0,0 +1 @@ +using from './srv/data-service'; \ No newline at end of file diff --git a/data-viewer/package.json b/data-viewer/package.json new file mode 100644 index 00000000..e27369ac --- /dev/null +++ b/data-viewer/package.json @@ -0,0 +1,13 @@ +{ + "name": "@capire/data-viewer", + "version": "0.1.0", + "description": "A generic browser for data", + "dependencies": { + "@sap/cds": ">=5.0.4" + }, + "files": [ + "app", + "srv", + "index.cds" + ] +} diff --git a/data-viewer/srv/data-service.cds b/data-viewer/srv/data-service.cds new file mode 100644 index 00000000..d03cfce4 --- /dev/null +++ b/data-viewer/srv/data-service.cds @@ -0,0 +1,29 @@ +/** + * Exposes data + entity metadata + */ +@requires:'authenticated-user' +@odata service DataService @( path:'-data' ) { + + /** + * Metadata like name and columns/elements + */ + entity Entities @cds.persistence.skip { + key name : String; + columns: Composition of many { + name : String; + type : String; + isKey: Boolean; + } + } + + /** + * The actual data, organized by column name + */ + entity Data @cds.persistence.skip { + record : array of { + column : String; + data : String; + } + } + +} diff --git a/data-viewer/srv/data-service.js b/data-viewer/srv/data-service.js new file mode 100644 index 00000000..2cddc820 --- /dev/null +++ b/data-viewer/srv/data-service.js @@ -0,0 +1,58 @@ +const cds = require('@sap/cds') +const log = cds.log('data') + +class DataService extends cds.ApplicationService { init(){ + + this.on ('READ', 'Entities', req => { + const { dataSource } = req.req.query + const srvPrefixes = cds.db.model.all('service').map(srv => srv.name+'.') + const dataSourceFilter = dataSource === 'db' + ? e => e['@cds.persistence.skip'] !== true // for DB, excl. entities w/o persistence + : e => !!srvPrefixes.find(srvName => e.name.startsWith(srvName)) // only entities reachable from a service + + return cds.db.model.all('entity') + .filter (e => req.data && req.data.name ? e.name === req.data.name : true) // honor name filter from request, if any + .filter (e => !e.name.startsWith('DRAFT.')) // exclude synthetic stuff + .filter (e => !e.name.startsWith('DataService.')) // exclude this service + .filter (dataSourceFilter) + .sort((e1, e2) => e1.name.localeCompare(e2.name)) + .map(e => { + const columns = Object.entries(e.elements) + .filter(([_, el]) => !(el instanceof cds.Association)) // exclude assocs+compositions + .map(([name, el]) => { return { name, type: el.type, isKey:!!el.key }}) + return { name: e.name, columns } + }) + }) + + this.on ('READ', 'Data', async req => { + const { entity: entityName, dataSource: dataSourceName } = req.req.query + if (!entityName) return req.reject(400, `Must provide 'entity' query`) + const entity = cds.db.model.definitions[entityName] + if (!entity) return req.reject(404, 'No such entity: ' + entityName) + + const query = SELECT.from(entity) + query.SELECT.limit = req.query.SELECT.limit // forward $skip / $top + + const dataSource = findDataSource(dataSourceName, entityName) + const res = await dataSource.run(query) + return res.map((line) => { + const record = Object.entries(line).map(([column, data]) => {return {column, data}}) + return { record } + }) + }) + + return super.init() +}} + +module.exports = { DataService } + +function findDataSource(dataSourceName, entityName) { + for (let srv of Object.values(cds.services)) { // all connected services + if (!srv.name) continue // FIXME intermediate/pending in cds.services ? + if (dataSourceName === srv.name || entityName.startsWith(srv.name+'.')) { + log._debug && log.debug(`using ${srv.name} as data source`) + return srv + } + } + return cds.services.db // fallback +} diff --git a/etc/bookshop.drawio.svg b/etc/bookshop.drawio.svg new file mode 100644 index 00000000..0a2d0286 --- /dev/null +++ b/etc/bookshop.drawio.svg @@ -0,0 +1,261 @@ + + + + + + + + + + +
+
+
+ + User Profiles + +
+
+
+
+ + User Profiles + +
+
+ + + + + + + +
+
+
+ + Order Mgmt + +
+
+
+
+ + Order Mgmt + +
+
+ + + + + + + +
+
+
+ + Catalog + +
+
+
+
+ + Catalog + +
+
+ + + + + + + + + + + + + + + +
+
+
+ Books +
+
+
+
+ + Books + +
+
+ + + + + + +
+
+
+ Authors +
+
+
+
+ + Authors + +
+
+ + + + + + +
+
+
+ Genres +
+
+
+
+ + Genres + +
+
+ + + + + + +
+
+
+ Orders +
+
+
+
+ + Orders + +
+
+ + + + + + +
+
+
+ OrderItems +
+
+
+
+ + OrderItems + +
+
+ + + + + + + + + + + + + + + + + + +
+
+
+ Users +
+
+
+
+ + Users + +
+
+ + + + + + + + +
+
+
+ buyer +
+
+
+
+ + buyer + +
+
+ + + + + + +
+
+
+ Addresses +
+
+
+
+ + Addresses + +
+
+ + + + + + + +
+ + + + + Viewer does not support full SVG 1.1 + + + +
\ No newline at end of file diff --git a/etc/dark.drawio.svg b/etc/dark.drawio.svg new file mode 100644 index 00000000..6a8892e9 --- /dev/null +++ b/etc/dark.drawio.svg @@ -0,0 +1,172 @@ + + + + + + + +
+
+
+ @capire/ +
+ + bookshop + +
+
+
+
+ + @capire/... + +
+
+ + + + +
+
+
+ @capire/ +
+ + fiori + +
+
+
+
+ + @capire/... + +
+
+ + + + +
+
+
+ @capire/ +
+ + reviews + +
+
+
+
+ + @capire/... + +
+
+ + + + +
+
+
+ @capire/ +
+ + common + +
+
+
+
+ + @capire/... + +
+
+ + + + +
+
+
+ @capire/ +
+ + orders + +
+
+
+
+ + @capire/... + +
+
+ + + + + + + + + + + + +
+
+
+ @capire/ +
+ + suppliers + +
+
+
+
+ + @capire/... + +
+
+ + + + +
+
+
+ + S/4 + +
+
+
+
+ + S/4 + +
+
+ + + + + + +
+ + + + + Viewer does not support full SVG 1.1 + + + +
\ No newline at end of file diff --git a/etc/incidents.drawio.svg b/etc/incidents.drawio.svg new file mode 100644 index 00000000..afb0d10c --- /dev/null +++ b/etc/incidents.drawio.svg @@ -0,0 +1,281 @@ + + + + + + + +
+
+
+ S/4 HANA +
+
+
+
+ + S/4 HANA + +
+
+ + + + +
+
+
+ Business +
+ Partner +
+
+
+
+ + Business... + +
+
+ + + + +
+
+
+ + Incident Mgmt + +
+ Extension App +
+
+
+
+ + Incident Mgmt... + +
+
+ + + + +
+
+
+ Incidents +
+
+
+
+ + Incidents + +
+
+ + + + + + + +
+
+
+ Customers +
+
+
+
+ + Customers + +
+
+ + + + +
+
+
+ SuccessFactors +
+
+
+
+ + SuccessFactors + +
+
+ + + + +
+
+
+ Workforce +
+ Person +
+
+
+
+ + Workforce... + +
+
+ + + + +
+
+
+ Employee +
+ Timesheet +
+
+
+
+ + Employee... + +
+
+ + + + + + +
+
+
+ Messages +
+
+
+
+ + Messages + +
+
+ + + + + + + +
+
+
+ Service +
+ Worker +
+
+
+
+ + Service... + +
+
+ + + + + + + + +
+
+
+ Worker +
+ Availability +
+
+
+
+ + Worker... + +
+
+ + + + + + +
+
+
+ Backend Services +
+
+
+
+ + Backend Services + +
+
+ + + + +
+
+
+ Usage Views +
+
+
+
+ + Usage Views + +
+
+ + + + +
+
+
+ Extension Data +
+
+
+
+ + Extension Data + +
+
+ + +
+ + + + + Viewer does not support full SVG 1.1 + + + +
\ No newline at end of file diff --git a/etc/samples.drawio.svg b/etc/samples.drawio.svg new file mode 100644 index 00000000..125b0ed8 --- /dev/null +++ b/etc/samples.drawio.svg @@ -0,0 +1,4 @@ + + + +
Bookshop
Bookshop
Composite
App
Composite...
Reviews
Service
Reviews...
Code
Lists
Code...
Orders
Service
Orders...
Suppliers
Service
Suppliers...
S/4
S/4
Fiori
App
Fiori...
Viewer does not support full SVG 1.1
\ No newline at end of file diff --git a/fiori/.env b/fiori/.env deleted file mode 100644 index 01ade12c..00000000 --- a/fiori/.env +++ /dev/null @@ -1 +0,0 @@ -cds.features.snapi = y \ No newline at end of file diff --git a/fiori/app/_i18n/i18n.properties b/fiori/app/_i18n/i18n.properties index c1d0293f..c6e0d27d 100644 --- a/fiori/app/_i18n/i18n.properties +++ b/fiori/app/_i18n/i18n.properties @@ -6,15 +6,33 @@ Author = Author AuthorID = Author ID Stock = Stock Name = Name +Description = Description +Image = Image AuthorName = Author's Name DateOfBirth = Date of Birth DateOfDeath = Date of Death PlaceOfBirth = Place of Birth PlaceOfDeath = Place of Death +Age = Age +Lifetime = Lifetime Authors = Authors + Order = Order Orders = Orders +OrderNo = Order Number +OrderItems = Order Items +Customer = Customer +Product = Product +ProductID = Product ID +ProductTitle = Product Title +UnitPrice = Unit Price +Quantity = Quantity + Price = Price +Currency = Currency +Date = Date +Rating = Rating +NumberOfReviews = Number of Reviews Genre = Genre Genres = Genres diff --git a/fiori/app/_i18n/i18n_de.properties b/fiori/app/_i18n/i18n_de.properties index 365b45df..7724f685 100644 --- a/fiori/app/_i18n/i18n_de.properties +++ b/fiori/app/_i18n/i18n_de.properties @@ -6,6 +6,7 @@ Authors = Autoren Author = Autor AuthorID = ID des Autors AuthorName = Name des Autors +Age = Alter Name = Name Stock = Bestand Order = Bestellung diff --git a/fiori/app/admin-authors/fiori-service.cds b/fiori/app/admin-authors/fiori-service.cds new file mode 100644 index 00000000..9ca69224 --- /dev/null +++ b/fiori/app/admin-authors/fiori-service.cds @@ -0,0 +1,52 @@ +using {AdminService} from '@capire/bookshop'; + +annotate AdminService.Authors with @odata.draft.enabled; + +//////////////////////////////////////////////////////////////////////////// +// +// Authors Object Page +// +annotate AdminService.Authors with @(UI : { + HeaderInfo : { + TypeName : 'Author', + TypeNamePlural : 'Authors', + Description : {Value : lifetime} + }, + Facets : [ + { + $Type : 'UI.ReferenceFacet', + Label : '{i18n>Details}', + Target : '@UI.FieldGroup#Details' + }, + { + $Type : 'UI.ReferenceFacet', + Label : '{i18n>Books}', + Target : 'books/@UI.LineItem' + }, + ], + FieldGroup #Details : {Data : [ + {Value : placeOfBirth}, + {Value : placeOfDeath}, + {Value : dateOfBirth}, + {Value : dateOfDeath}, + { + Value : age, + Label : '{i18n>Age}' + }, + ]}, +}); + + +// Workaround to avoid errors for unknown db-specific calculated fields above +extend sap.capire.bookshop.Authors with { + virtual age : Integer; + virtual lifetime : String; +} + +annotate AdminService.Authors with { + age @Common.Label : '{i18n>Age}'; + lifetime @Common.Label : '{i18n>Lifetime}' +} + +// Workaround for Fiori popup for asking user to enter a new UUID on Create +annotate AdminService.Authors with { ID @Core.Computed; } diff --git a/fiori/app/admin-authors/webapp/Component.js b/fiori/app/admin-authors/webapp/Component.js new file mode 100644 index 00000000..05638a71 --- /dev/null +++ b/fiori/app/admin-authors/webapp/Component.js @@ -0,0 +1,7 @@ +sap.ui.define(["sap/fe/core/AppComponent"], function (AppComponent) { + "use strict"; + return AppComponent.extend("authors.Component", { + metadata: { manifest: "json" }, + }); +}); +/* eslint no-undef:0 */ diff --git a/fiori/app/admin-authors/webapp/i18n/i18n.properties b/fiori/app/admin-authors/webapp/i18n/i18n.properties new file mode 100644 index 00000000..9d2dafd7 --- /dev/null +++ b/fiori/app/admin-authors/webapp/i18n/i18n.properties @@ -0,0 +1,11 @@ +# This is the resource bundle of itelo +# __ldi.translation.uuid=c3431418-9caf-11e8-98d0-529269fb1459 + +# JCI app descriptor contains lower case TITLE +appTitle=Bookshop Authors + +# JCI app descriptor contains lower case DESCRIPTION +appSubTitle=Bookshop Authors + +# JCI app descriptor contains lower case DESCRIPTION +appDescription=Bookshop Authors diff --git a/fiori/app/admin-authors/webapp/manifest.json b/fiori/app/admin-authors/webapp/manifest.json new file mode 100644 index 00000000..38146256 --- /dev/null +++ b/fiori/app/admin-authors/webapp/manifest.json @@ -0,0 +1,141 @@ +{ + "_version": "1.28.0", + "sap.app": { + "id": "authors", + "type": "application", + "title": "Manage Authors", + "description": "Sample Application", + "i18n": "i18n/i18n.properties", + "applicationVersion": { + "version": "1.0.0" + }, + "dataSources": { + "AdminService": { + "uri": "admin/", + "type": "OData", + "settings": { + "odataVersion": "4.0" + } + } + }, + "sourceTemplate": { + "id": "ui5template.basicSAPUI5ApplicationProject", + "-id": "ui5template.smartTemplate", + "version": "1.40.12" + }, + "crossNavigation": { + "inbounds": { + "intent1": { + "signature": { + "parameters": { + "Books.author.ID":{ + "renameTo": "ID" + } + }, + "additionalParameters": "ignored" + }, + "semanticObject": "Authors", + "action": "display", + "title": "{{appTitle}}", + "info": "{{appInfo}}", + "subTitle": "{{appSubTitle}}", + "icon": "sap-icon://SAP-icons-TNT/user", + "indicatorDataSource": { + "dataSource": "AdminService", + "path": "Authors/$count", + "refresh": 1800 + } + } + } + } + }, + "sap.ui5": { + "dependencies": { + "minUI5Version": "1.81.0", + "libs": { + "sap.fe.templates": {} + } + }, + "models": { + "i18n": { + "type": "sap.ui.model.resource.ResourceModel", + "uri": "i18n/i18n.properties" + }, + "": { + "dataSource": "AdminService", + "settings": { + "synchronizationMode": "None", + "operationMode": "Server", + "autoExpandSelect": true, + "earlyRequests": true, + "groupProperties": { + "default": { + "submit": "Auto" + } + } + } + } + }, + "routing": { + "routes": [ + { + "pattern": ":?query:", + "name": "AuthorsList", + "target": "AuthorsList" + }, + { + "pattern": "Authors({key}):?query:", + "name": "AuthorsDetails", + "target": "AuthorsDetails" + } + ], + "targets": { + "AuthorsList": { + "type": "Component", + "id": "AuthorsList", + "name": "sap.fe.templates.ListReport", + "options": { + "settings": { + "entitySet": "Authors", + "initialLoad": true, + "navigation": { + "Authors": { + "detail": { + "route": "AuthorsDetails" + } + } + } + } + } + }, + "AuthorsDetails": { + "type": "Component", + "id": "AuthorsDetailsList", + "name": "sap.fe.templates.ObjectPage", + "options": { + "settings": { + "entitySet": "Authors" + } + } + } + } + }, + "contentDensities": { + "compact": true, + "cozy": true + } + }, + "sap.ui": { + "technology": "UI5", + "fullWidth": false, + "deviceTypes":{ + "desktop": true, + "tablet": true, + "phone": true + } + }, + "sap.fiori": { + "registrationIds": [], + "archeType": "transactional" + } +} diff --git a/fiori/app/admin/fiori-service.cds b/fiori/app/admin-books/fiori-service.cds similarity index 68% rename from fiori/app/admin/fiori-service.cds rename to fiori/app/admin-books/fiori-service.cds index 1aeddb9f..668e2548 100644 --- a/fiori/app/admin/fiori-service.cds +++ b/fiori/app/admin-books/fiori-service.cds @@ -1,4 +1,5 @@ -using AdminService from '@capire/bookshop'; +using { AdminService } from '@capire/bookstore'; +using from '../common'; // to help UI linter get the complete annotations //////////////////////////////////////////////////////////////////////////// // @@ -49,7 +50,7 @@ annotate AdminService.Books with @( annotate sap.capire.bookshop.Books with @fiori.draft.enabled; annotate AdminService.Books with @odata.draft.enabled; -annotate AdminService.Books_texts with @( +annotate AdminService.Books.texts with @( UI: { Identification: [{Value:title}], SelectionFields: [ locale, title ], @@ -61,12 +62,22 @@ annotate AdminService.Books_texts with @( } ); +annotate AdminService.Books.texts with { + ID @UI.Hidden; + ID_texts @UI.Hidden; +}; + // Add Value Help for Locales -annotate AdminService.Books_texts { - locale @ValueList:{entity:'Languages',type:#fixed} +annotate AdminService.Books.texts { + locale @( + ValueList.entity:'Languages', Common.ValueListWithFixedValues, //show as drop down, not a dialog + ) } -// In addition we need to expose Languages through AdminService +// In addition we need to expose Languages through AdminService as a target for ValueList using { sap } from '@sap/cds/common'; extend service AdminService { - entity Languages as projection on sap.common.Languages; + @readonly entity Languages as projection on sap.common.Languages; } + +// Workaround for Fiori popup for asking user to enter a new UUID on Create +annotate AdminService.Books with { ID @Core.Computed; } diff --git a/fiori/app/admin/webapp/Component.js b/fiori/app/admin-books/webapp/Component.js similarity index 63% rename from fiori/app/admin/webapp/Component.js rename to fiori/app/admin-books/webapp/Component.js index c3137017..d4bc7328 100644 --- a/fiori/app/admin/webapp/Component.js +++ b/fiori/app/admin-books/webapp/Component.js @@ -1,6 +1,6 @@ sap.ui.define(["sap/fe/core/AppComponent"], function(AppComponent) { "use strict"; - return AppComponent.extend("admin.Component", { + return AppComponent.extend("books.Component", { metadata: { manifest: "json" } }); }); diff --git a/fiori/app/admin/webapp/i18n/i18n.properties b/fiori/app/admin-books/webapp/i18n/i18n.properties similarity index 100% rename from fiori/app/admin/webapp/i18n/i18n.properties rename to fiori/app/admin-books/webapp/i18n/i18n.properties diff --git a/fiori/app/admin/webapp/manifest.json b/fiori/app/admin-books/webapp/manifest.json similarity index 97% rename from fiori/app/admin/webapp/manifest.json rename to fiori/app/admin-books/webapp/manifest.json index 25047c29..e3e095cb 100644 --- a/fiori/app/admin/webapp/manifest.json +++ b/fiori/app/admin-books/webapp/manifest.json @@ -1,14 +1,14 @@ { "_version": "1.8.0", "sap.app": { - "id": "admin", + "id": "books", "type": "application", "title": "Manage Books", "description": "Sample Application", "i18n": "i18n/i18n.properties", "dataSources": { "AdminService": { - "uri": "/admin/", + "uri": "admin/", "type": "OData", "settings": { "odataVersion": "4.0" @@ -73,6 +73,7 @@ "options": { "settings" : { "entitySet" : "Books", + "initialLoad": true, "navigation" : { "Books" : { "detail" : { diff --git a/fiori/app/appconfig/fioriSandboxConfig.json b/fiori/app/appconfig/fioriSandboxConfig.json new file mode 100644 index 00000000..1bc4eb93 --- /dev/null +++ b/fiori/app/appconfig/fioriSandboxConfig.json @@ -0,0 +1,168 @@ +{ + "services": { + "LaunchPage": { + "adapter": { + "config": { + "catalogs": [], + "groups": [ + { + "id": "Bookshop", + "title": "Bookshop", + "isPreset": true, + "isVisible": true, + "isGroupLocked": false, + "tiles": [ + { + "id": "BrowseBooks", + "tileType": "sap.ushell.ui.tile.StaticTile", + "properties": { + "title": "Browse Books", + "targetURL": "#Books-display" + } + }, + { + "id": "BrowseGenres", + "tileType": "sap.ushell.ui.tile.StaticTile", + "properties": { + "title": "Browse Genres (OData v2)", + "targetURL": "#Genres-display" + } + } + ] + }, + { + "id": "Administration", + "title": "Administration", + "isPreset": true, + "isVisible": true, + "isGroupLocked": false, + "tiles": [ + { + "id": "ManageBooks", + "tileType": "sap.ushell.ui.tile.StaticTile", + "properties": { + "title": "Manage Books", + "targetURL": "#Books-manage" + } + }, + { + "id": "ManageAuthors", + "tileType": "sap.ushell.ui.tile.StaticTile", + "properties": { + "title": "Manage Authors", + "targetURL": "#Authors-display" + } + }, + { + "id": "ManageOrders", + "tileType": "sap.ushell.ui.tile.StaticTile", + "properties": { + "title": "Manage Orders", + "targetURL": "#Orders-manage" + } + } + ] + } + ] + } + } + }, + "NavTargetResolution": { + "config": { + "enableClientSideTargetResolution": true + } + }, + "ClientSideTargetResolution": { + "adapter": { + "config": { + "inbounds": { + "BrowseBooks": { + "semanticObject": "Books", + "action": "display", + "title": "Browse Books", + "signature": { + "parameters": { + "Books.ID": { + "renameTo": "ID" + }, + "Authors.books.ID": { + "renameTo": "ID" + } + }, + "additionalParameters": "ignored" + }, + "resolutionResult": { + "applicationType": "SAPUI5", + "additionalInformation": "SAPUI5.Component=bookshop", + "url": "/browse/webapp" + } + }, + "BrowseAuthors": { + "semanticObject": "Authors", + "action": "display", + "title": "Browse Authors", + "signature": { + "parameters": { + "Books.author.ID":{ + "renameTo": "ID" + } + }, + "additionalParameters": "ignored" + }, + "resolutionResult": { + "applicationType": "SAPUI5", + "additionalInformation": "SAPUI5.Component=authors", + "url": "/admin-authors/webapp" + } + }, + "BrowseGenres": { + "semanticObject": "Genres", + "action": "display", + "title": "Browse Genres", + "signature": { + "parameters": { + "Genre.ID": { + "renameTo": "ID" + } + }, + "additionalParameters": "ignored" + }, + "resolutionResult": { + "applicationType": "SAPUI5", + "additionalInformation": "SAPUI5.Component=genres", + "url": "/genres/webapp" + } + }, + "ManageBooks": { + "semanticObject": "Books", + "action": "manage", + "title": "Manage Books", + "signature": { + "parameters": {}, + "additionalParameters": "allowed" + }, + "resolutionResult": { + "applicationType": "SAPUI5", + "additionalInformation": "SAPUI5.Component=books", + "url": "/admin-books/webapp" + } + }, + "ManageOrders": { + "semanticObject": "Orders", + "action": "manage", + "signature": { + "parameters": {}, + "additionalParameters": "allowed" + }, + "resolutionResult": { + "applicationType": "SAPUI5", + "additionalInformation": "SAPUI5.Component=orders", + "url": "/orders/webapp" + } + } + } + } + } + } + } +} diff --git a/fiori/app/browse/fiori-service.cds b/fiori/app/browse/fiori-service.cds index 4f947fd4..03ff198c 100644 --- a/fiori/app/browse/fiori-service.cds +++ b/fiori/app/browse/fiori-service.cds @@ -1,48 +1,57 @@ -using CatalogService from '@capire/bookshop'; +using CatalogService from '@capire/bookstore'; //////////////////////////////////////////////////////////////////////////// // // Books Object Page // -annotate CatalogService.Books with @( - UI: { - HeaderInfo: { - Description: {Value: author} - }, - HeaderFacets: [ - {$Type: 'UI.ReferenceFacet', Label: '{i18n>Description}', Target: '@UI.FieldGroup#Descr'}, - ], - Facets: [ - {$Type: 'UI.ReferenceFacet', Label: '{i18n>Details}', Target: '@UI.FieldGroup#Price'}, - ], - FieldGroup#Descr: { - Data: [ - {Value: descr}, - ] - }, - FieldGroup#Price: { - Data: [ - {Value: price}, - {Value: currency.symbol, Label: '{i18n>Currency}'}, - ] - }, - } -); +annotate CatalogService.Books with @(UI : { + HeaderInfo : { + TypeName : 'Book', + TypeNamePlural : 'Books', + Description : {Value : author} + }, + HeaderFacets : [{ + $Type : 'UI.ReferenceFacet', + Label : '{i18n>Description}', + Target : '@UI.FieldGroup#Descr' + }, ], + Facets : [{ + $Type : 'UI.ReferenceFacet', + Label : '{i18n>Details}', + Target : '@UI.FieldGroup#Price' + }, ], + FieldGroup #Descr : {Data : [{Value : descr}, ]}, + FieldGroup #Price : {Data : [ + {Value : price}, + { + Value : currency.symbol, + Label : '{i18n>Currency}' + }, + ]}, +}); //////////////////////////////////////////////////////////////////////////// // -// Books Object Page +// Books List Page // -annotate CatalogService.Books with @( - UI: { - SelectionFields: [ ID, price, currency_code ], - LineItem: [ - {Value: title}, - {Value: author, Label:'{i18n>Author}'}, - {Value: genre.name}, - {Value: price}, - {Value: currency.symbol, Label:' '}, - ] - }, -); +annotate CatalogService.Books with @(UI : { + SelectionFields : [ + ID, + price, + currency_code + ], + LineItem : [ + { + Value : ID, + Label : '{i18n>Title}' + }, + { + Value : author, + Label : '{i18n>Author}' + }, + {Value : genre.name}, + {Value : price}, + {Value : currency.symbol}, + ] +}, ); diff --git a/fiori/app/browse/webapp/manifest.json b/fiori/app/browse/webapp/manifest.json index 4a2e0a62..2fcf7676 100644 --- a/fiori/app/browse/webapp/manifest.json +++ b/fiori/app/browse/webapp/manifest.json @@ -1,28 +1,60 @@ { - "_version": "1.8.0", + "_version": "1.28.0", "sap.app": { "id": "bookshop", "type": "application", "title": "Browse Books", "description": "Sample Application", "i18n": "i18n/i18n.properties", + "applicationVersion": { + "version": "1.0.0" + }, "dataSources": { "CatalogService": { - "uri": "/browse/", + "uri": "browse/", "type": "OData", "settings": { "odataVersion": "4.0" } } }, - "-sourceTemplate": { + "sourceTemplate": { "id": "ui5template.basicSAPUI5ApplicationProject", "-id": "ui5template.smartTemplate", - "-version": "1.40.12" + "version": "1.40.12" + }, + "crossNavigation": { + "inbounds": { + "intent1": { + "signature": { + "parameters": { + "Books.ID":{ + "renameTo": "ID" + }, + "Authors.books.ID": { + "renameTo": "ID" + } + }, + "additionalParameters": "ignored" + }, + "semanticObject": "Books", + "action": "display", + "title": "{{appTitle}}", + "info": "{{appInfo}}", + "subTitle": "{{appSubTitle}}", + "icon": "sap-icon://course-book", + "indicatorDataSource": { + "dataSource": "CatalogService", + "path": "Books/$count", + "refresh": 1800 + } + } + } } }, "sap.ui5": { "dependencies": { + "minUI5Version": "1.81.0", "libs": { "sap.fe.templates": {} } @@ -68,6 +100,7 @@ "options": { "settings": { "entitySet": "Books", + "initialLoad": true, "navigation": { "Books": { "detail": { @@ -97,7 +130,12 @@ }, "sap.ui": { "technology": "UI5", - "fullWidth": false + "fullWidth": false, + "deviceTypes":{ + "desktop": true, + "tablet": true, + "phone": true + } }, "sap.fiori": { "registrationIds": [], diff --git a/fiori/app/common.cds b/fiori/app/common.cds index 614f03b3..3e5f748a 100644 --- a/fiori/app/common.cds +++ b/fiori/app/common.cds @@ -1,48 +1,57 @@ /* - Common Annotations shared by all apps + Common Annotations shared by all apps */ -using { sap.capire.bookshop as my } from '@capire/bookshop'; +using { sap.capire.bookshop as my } from '@capire/bookstore'; using { sap.common } from '@capire/common'; +using { sap.common.Currencies } from '@sap/cds/common'; //////////////////////////////////////////////////////////////////////////// // // Books Lists // annotate my.Books with @( - Common.SemanticKey: [title], - UI: { - Identification: [{Value:title}], - SelectionFields: [ ID, author_ID, price, currency_code ], - LineItem: [ - {Value: ID}, - {Value: title}, - {Value: author.name, Label:'{i18n>Author}'}, - {Value: genre.name}, - {Value: stock}, - {Value: price}, - {Value: currency.symbol, Label:' '}, - ] - } + Common.SemanticKey : [ID], + UI : { + Identification : [{ Value: title }], + SelectionFields : [ + ID, + author_ID, + price, + currency_code + ], + LineItem : [ + { Value: ID, Label: '{i18n>Title}' }, + { Value: author.ID, Label: '{i18n>Author}' }, + { Value: genre.name }, + { Value: stock }, + { Value: price }, + { Value: currency.symbol }, + ] + } ) { - author @ValueList.entity:'Authors'; + ID @Common: { + SemanticObject : 'Books', + Text: title, + TextArrangement : #TextOnly + }; + author @ValueList.entity : 'Authors'; }; +annotate Currencies with { + symbol @Common.Label : '{i18n>Currency}'; +} + //////////////////////////////////////////////////////////////////////////// // // Books Details // -annotate my.Books with @( - UI: { - HeaderInfo: { - TypeName: '{i18n>Book}', - TypeNamePlural: '{i18n>Books}', - Title: {Value: title}, - Description: {Value: author.name} - }, - } -); - +annotate my.Books with @(UI : {HeaderInfo : { + TypeName : '{i18n>Book}', + TypeNamePlural : '{i18n>Books}', + Title : { Value: title }, + Description : { Value: author.name } +}, }); //////////////////////////////////////////////////////////////////////////// @@ -50,13 +59,14 @@ annotate my.Books with @( // Books Elements // annotate my.Books with { - ID @title:'{i18n>ID}' @UI.HiddenFilter; - title @title:'{i18n>Title}'; - genre @title:'{i18n>Genre}' @Common: { Text: genre.name, TextArrangement: #TextOnly }; - author @title:'{i18n>Author}' @Common: { Text: author.name, TextArrangement: #TextOnly }; - price @title:'{i18n>Price}'; - stock @title:'{i18n>Stock}'; - descr @UI.MultiLineText; + ID @title: '{i18n>ID}'; + title @title: '{i18n>Title}'; + genre @title: '{i18n>Genre}' @Common: { Text: genre.name, TextArrangement: #TextOnly }; + author @title: '{i18n>Author}' @Common: { Text: author.name, TextArrangement: #TextOnly }; + price @title: '{i18n>Price}' @Measures.ISOCurrency : currency_code; + stock @title: '{i18n>Stock}'; + descr @title: '{i18n>Description}' @UI.MultiLineText; + image @title: '{i18n>Image}'; } //////////////////////////////////////////////////////////////////////////// @@ -64,42 +74,49 @@ annotate my.Books with { // Genres List // annotate my.Genres with @( - Common.SemanticKey: [name], - UI: { - SelectionFields: [ name ], - LineItem:[ - {Value: name}, - {Value: parent.name, Label: 'Main Genre'}, - ], - } + Common.SemanticKey : [name], + UI : { + SelectionFields : [name], + LineItem : [ + { Value: name }, + { + Value : parent.name, + Label: 'Main Genre' + }, + ], + } ); +annotate my.Genres with { + ID @Common.Text : name @Common.TextArrangement : #TextOnly; +} + //////////////////////////////////////////////////////////////////////////// // // Genre Details // -annotate my.Genres with @( - UI: { - Identification: [{Value:name}], - HeaderInfo: { - TypeName: '{i18n>Genre}', - TypeNamePlural: '{i18n>Genres}', - Title: {Value: name}, - Description: {Value: ID} - }, - Facets: [ - {$Type: 'UI.ReferenceFacet', Label: '{i18n>SubGenres}', Target: 'children/@UI.LineItem'}, - ], - } -); +annotate my.Genres with @(UI : { + Identification : [{ Value: name}], + HeaderInfo : { + TypeName : '{i18n>Genre}', + TypeNamePlural : '{i18n>Genres}', + Title : { Value: name }, + Description : { Value: ID } + }, + Facets : [{ + $Type : 'UI.ReferenceFacet', + Label : '{i18n>SubGenres}', + Target : 'children/@UI.LineItem' + }, ], +}); //////////////////////////////////////////////////////////////////////////// // // Genres Elements // annotate my.Genres with { - ID @title: '{i18n>ID}'; - name @title: '{i18n>Genre}'; + ID @title: '{i18n>ID}'; + name @title: '{i18n>Genre}'; } //////////////////////////////////////////////////////////////////////////// @@ -107,38 +124,42 @@ annotate my.Genres with { // Authors List // annotate my.Authors with @( - Common.SemanticKey: [name], - UI: { - Identification: [{Value:name}], - SelectionFields: [ name ], - LineItem:[ - {Value: ID}, - {Value: name}, - {Value: dateOfBirth}, - {Value: dateOfDeath}, - {Value: placeOfBirth}, - {Value: placeOfDeath}, - ], - } -); + Common.SemanticKey : [ID], + UI : { + Identification : [{ Value: name}], + SelectionFields : [name], + LineItem : [ + { Value: ID }, + { Value: dateOfBirth }, + { Value: dateOfDeath }, + { Value: placeOfBirth }, + { Value: placeOfDeath }, + ], + } +) { + ID @Common: { + SemanticObject : 'Authors', + Text: name, + TextArrangement : #TextOnly, + }; +}; //////////////////////////////////////////////////////////////////////////// // // Author Details // -annotate my.Authors with @( - UI: { - HeaderInfo: { - TypeName: '{i18n>Author}', - TypeNamePlural: '{i18n>Authors}', - Title: {Value: name}, - Description: {Value: dateOfBirth} - }, - Facets: [ - {$Type: 'UI.ReferenceFacet', Target: 'books/@UI.LineItem'}, - ], - } -); +annotate my.Authors with @(UI : { + HeaderInfo : { + TypeName : '{i18n>Author}', + TypeNamePlural : '{i18n>Authors}', + Title : { Value: name }, + Description : { Value: dateOfBirth } + }, + Facets : [{ + $Type : 'UI.ReferenceFacet', + Target : 'books/@UI.LineItem' + }, ], +}); //////////////////////////////////////////////////////////////////////////// @@ -146,12 +167,12 @@ annotate my.Authors with @( // Authors Elements // annotate my.Authors with { - ID @title:'{i18n>ID}' @UI.HiddenFilter; - name @title:'{i18n>Name}'; - dateOfBirth @title:'{i18n>DateOfBirth}'; - dateOfDeath @title:'{i18n>DateOfDeath}'; - placeOfBirth @title:'{i18n>PlaceOfBirth}'; - placeOfDeath @title:'{i18n>PlaceOfDeath}'; + ID @title: '{i18n>ID}'; + name @title: '{i18n>Name}'; + dateOfBirth @title: '{i18n>DateOfBirth}'; + dateOfDeath @title: '{i18n>DateOfDeath}'; + placeOfBirth @title: '{i18n>PlaceOfBirth}'; + placeOfDeath @title: '{i18n>PlaceOfDeath}'; } //////////////////////////////////////////////////////////////////////////// @@ -159,99 +180,105 @@ annotate my.Authors with { // Languages List // annotate common.Languages with @( - Common.SemanticKey: [code], - Identification: [{Value:code}], - UI: { - SelectionFields: [ name, descr ], - LineItem:[ - {Value: code}, - {Value: name}, - ], - } + Common.SemanticKey : [code], + Identification : [{ Value: code}], + UI : { + SelectionFields : [ + name, + descr + ], + LineItem : [ + { Value: code }, + { Value: name }, + ], + } ); //////////////////////////////////////////////////////////////////////////// // // Language Details // -annotate common.Languages with @( - UI: { - HeaderInfo: { - TypeName: '{i18n>Language}', - TypeNamePlural: '{i18n>Languages}', - Title: {Value: name}, - Description: {Value: descr} - }, - Facets: [ - {$Type: 'UI.ReferenceFacet', Label: '{i18n>Details}', Target: '@UI.FieldGroup#Details'}, - ], - FieldGroup#Details: { - Data: [ - {Value: code}, - {Value: name}, - {Value: descr} - ] - }, - } -); +annotate common.Languages with @(UI : { + HeaderInfo : { + TypeName : '{i18n>Language}', + TypeNamePlural : '{i18n>Languages}', + Title : { Value: name }, + Description : { Value: descr } + }, + Facets : [{ + $Type : 'UI.ReferenceFacet', + Label : '{i18n>Details}', + Target : '@UI.FieldGroup#Details' + }, ], + FieldGroup #Details : {Data : [ + { Value: code }, + { Value: name }, + { Value: descr } + ]}, +}); //////////////////////////////////////////////////////////////////////////// // // Currencies List // annotate common.Currencies with @( - Common.SemanticKey: [code], - Identification: [{Value:code}], - UI: { - SelectionFields: [ name, descr ], - LineItem:[ - {Value: descr}, - {Value: symbol}, - {Value: code}, - ], - } + Common.SemanticKey : [code], + Identification : [{ Value: code}], + UI : { + SelectionFields : [ + name, + descr + ], + LineItem : [ + { Value: descr }, + { Value: symbol }, + { Value: code }, + ], + } ); //////////////////////////////////////////////////////////////////////////// // // Currency Details // -annotate common.Currencies with @( - UI: { - HeaderInfo: { - TypeName: '{i18n>Currency}', - TypeNamePlural: '{i18n>Currencies}', - Title: {Value: descr}, - Description: {Value: code} - }, - Facets: [ - {$Type: 'UI.ReferenceFacet', Label: '{i18n>Details}', Target: '@UI.FieldGroup#Details'}, - {$Type: 'UI.ReferenceFacet', Label: '{i18n>Extended}', Target: '@UI.FieldGroup#Extended'}, - ], - FieldGroup#Details: { - Data: [ - {Value: name}, - {Value: symbol}, - {Value: code}, - {Value: descr} - ] - }, - FieldGroup#Extended: { - Data: [ - {Value: numcode}, - {Value: minor}, - {Value: exponent} - ] - }, - } -); +annotate common.Currencies with @(UI : { + HeaderInfo : { + TypeName : '{i18n>Currency}', + TypeNamePlural : '{i18n>Currencies}', + Title : { Value: descr }, + Description : { Value: code } + }, + Facets : [ + { + $Type : 'UI.ReferenceFacet', + Label : '{i18n>Details}', + Target : '@UI.FieldGroup#Details' + }, + { + $Type : 'UI.ReferenceFacet', + Label : '{i18n>Extended}', + Target : '@UI.FieldGroup#Extended' + }, + ], + FieldGroup #Details : {Data : [ + { Value: name }, + { Value: symbol }, + { Value: code }, + { Value: descr } + ]}, + FieldGroup #Extended : {Data : [ + { Value: numcode }, + { Value: minor }, + { Value: exponent } + ]}, +}); //////////////////////////////////////////////////////////////////////////// // // Currencies Elements // annotate common.Currencies with { - numcode @title:'{i18n>NumCode}'; - minor @title:'{i18n>MinorUnit}'; - exponent @title:'{i18n>Exponent}'; + numcode @title: '{i18n>NumCode}'; + minor @title: '{i18n>MinorUnit}'; + exponent @title: '{i18n>Exponent}'; } diff --git a/fiori/app/fiori-apps.html b/fiori/app/fiori-apps.html new file mode 100644 index 00000000..29f06140 --- /dev/null +++ b/fiori/app/fiori-apps.html @@ -0,0 +1,30 @@ + + + + + + + + Bookshop + + + + + + + + + + \ No newline at end of file diff --git a/fiori/app/genres/fiori-service.cds b/fiori/app/genres/fiori-service.cds new file mode 100644 index 00000000..908ffdcc --- /dev/null +++ b/fiori/app/genres/fiori-service.cds @@ -0,0 +1,8 @@ +using { sap.capire.bookshop } from '../../db/common'; + +annotate bookshop.GenreHierarchy { + ID @sap.hierarchy.node.for; + parent @sap.hierarchy.parent.node.for; + hierarchyLevel @sap.hierarchy.level.for; + drillState @sap.hierarchy.drill.state.for; +} diff --git a/fiori/app/genres/webapp/Component.js b/fiori/app/genres/webapp/Component.js new file mode 100644 index 00000000..a8c2a9d6 --- /dev/null +++ b/fiori/app/genres/webapp/Component.js @@ -0,0 +1,7 @@ +sap.ui.define(["sap/suite/ui/generic/template/lib/AppComponent"], (AppComponent) => + AppComponent.extend("genres.Component", { + metadata: { + manifest: "json", + }, + }) +); diff --git a/fiori/app/genres/webapp/i18n/i18n.properties b/fiori/app/genres/webapp/i18n/i18n.properties new file mode 100644 index 00000000..b42a7a23 --- /dev/null +++ b/fiori/app/genres/webapp/i18n/i18n.properties @@ -0,0 +1,4 @@ +#XTIT +appTitle=Genres +#XTXT +appDescription=Browse Genres diff --git a/fiori/app/genres/webapp/manifest.json b/fiori/app/genres/webapp/manifest.json new file mode 100644 index 00000000..25d5d8f9 --- /dev/null +++ b/fiori/app/genres/webapp/manifest.json @@ -0,0 +1,155 @@ +{ + "_version": "1.8.0", + "sap.app": { + "id": "genres", + "type": "application", + "i18n": "i18n/i18n.properties", + "applicationVersion": { + "version": "1.0.0" + }, + "title": "Browse Genres Hierarchy (OData v2)", + "description": "{{appDescription}}", + "tags": { + "keywords": [] + }, + "crossNavigation": { + "inbounds": { + "appShow": { + "title": "{{appTitle}}", + "semanticObject": "GenreHierarchy", + "action": "display", + "deviceTypes": { + "desktop": true, + "tablet": true, + "phone": true + }, + "icon": "sap-icon://settings", + "size": "1x1" + } + }, + "outbounds": {} + }, + "ach": "", + "resources": "resources.json", + "dataSources": { + "main": { + "uri": "/v2/browse", + "type": "OData", + "settings": { + "annotations": ["localAnnotations"], + "localUri": "localService/metadata.xml" + } + }, + "localAnnotations": { + "type": "ODataAnnotation", + "uri": "annotations/localAnnotations.xml", + "settings": { + "localUri": "annotations/localAnnotations.xml" + } + } + }, + "offline": false, + "sourceTemplate": { + "id": "ui5template.smartTemplate", + "version": "1.40.12" + } + }, + "sap.ui": { + "technology": "UI5", + "icons": { + "icon": "", + "favIcon": "", + "phone": "", + "phone@2": "", + "tablet": "", + "tablet@2": "" + }, + "deviceTypes": { + "desktop": true, + "tablet": true, + "phone": true + }, + "supportedThemes": ["sap_hcb", "sap_belize", "sap_belize_deep", "sap_fiori_3"] + }, + "sap.ui5": { + "resources": { + "js": [], + "css": [] + }, + "dependencies": { + "minUI5Version": "1.65.6", + "libs": {}, + "components": {} + }, + "models": { + "i18n": { + "type": "sap.ui.model.resource.ResourceModel", + "uri": "i18n/i18n.properties" + }, + "@i18n": { + "type": "sap.ui.model.resource.ResourceModel", + "uri": "i18n/i18n.properties" + }, + "json": { + "type": "sap.ui.model.json.JSONModel" + }, + "i18n|sap.suite.ui.generic.template.ListReport|Genres": { + "type": "sap.ui.model.resource.ResourceModel", + "uri": "i18n/ListReport/Genres/i18n.properties" + }, + "": { + "dataSource": "main", + "preload": true, + "settings": { + "useBatch": true, + "defaultBindingMode": "TwoWay", + "defaultCountMode": "Inline", + "refreshAfterChange": true, + "metadataUrlParams": { + "sap-value-list": "none" + } + } + } + }, + "contentDensities": { + "compact": true, + "cozy": true + } + }, + "sap.ui.generic.app": { + "_version": "1.3.0", + "settings": { + "forceGlobalRefresh": false, + "useColumnLayoutForSmartForm": false, + "showBasicSearch": false + }, + "pages": { + "ListReport|Genres": { + "entitySet": "GenreHierarchy", + "component": { + "name": "sap.suite.ui.generic.template.ListReport", + "list": true, + "settings": { + "condensedTableLayout": true, + "smartVariantManagement": true, + "tableType": "TreeTable", + "enableTableFilterInPageVariant": true, + "dataLoadSettings": { + "loadDataOnAppLaunch": "always" + } + } + } + } + } + }, + "sap.fiori": { + "registrationIds": [], + "archeType": "transactional" + }, + "sap.platform.hcp": { + "uri": "" + }, + "sap.platform.cf": { + "oAuthScopes": [] + } +} diff --git a/fiori/app/index.cds b/fiori/app/index.cds deleted file mode 100644 index 379e55ab..00000000 --- a/fiori/app/index.cds +++ /dev/null @@ -1,10 +0,0 @@ -/* - This model controls what gets served to Fiori frontends... -*/ - -using from './admin/fiori-service'; -using from './browse/fiori-service'; -using from './orders/fiori-service'; -using from './common'; - -using from '@capire/common'; diff --git a/fiori/app/orders/fiori-service.cds b/fiori/app/orders/fiori-service.cds deleted file mode 100644 index cced0972..00000000 --- a/fiori/app/orders/fiori-service.cds +++ /dev/null @@ -1,120 +0,0 @@ -using OrdersService from '@capire/orders/srv/orders-service'; - -annotate OrdersService.Books with { - price @Common.FieldControl: #ReadOnly; -} - - -//////////////////////////////////////////////////////////////////////////// -// -// Common -// -annotate OrdersService.OrderItems with { - book @( - Common: { - Text: book.title, - FieldControl: #Mandatory - }, - ValueList.entity:'Books', - ); - amount @( - Common.FieldControl: #Mandatory - ); -} - - -@odata.draft.enabled -annotate OrdersService.Orders with @( - UI: { - //////////////////////////////////////////////////////////////////////////// - // - // Lists of Orders - // - SelectionFields: [ createdAt, createdBy ], - LineItem: [ - {Value: createdBy, Label:'Customer'}, - {Value: createdAt, Label:'Date'} - ], - //////////////////////////////////////////////////////////////////////////// - // - // Order Details - // - HeaderInfo: { - TypeName: 'Order', TypeNamePlural: 'Orders', - Title: { - Label: 'Order number ', //A label is possible but it is not considered on the ObjectPage yet - Value: OrderNo - }, - Description: {Value: createdBy} - }, - Identification: [ //Is the main field group - {Value: createdBy, Label:'Customer'}, - {Value: createdAt, Label:'Date'}, - {Value: OrderNo }, - ], - HeaderFacets: [ - {$Type: 'UI.ReferenceFacet', Label: '{i18n>Created}', Target: '@UI.FieldGroup#Created'}, - {$Type: 'UI.ReferenceFacet', Label: '{i18n>Modified}', Target: '@UI.FieldGroup#Modified'}, - ], - Facets: [ - {$Type: 'UI.ReferenceFacet', Label: '{i18n>Details}', Target: '@UI.FieldGroup#Details'}, - {$Type: 'UI.ReferenceFacet', Label: '{i18n>OrderItems}', Target: 'Items/@UI.LineItem'}, - ], - FieldGroup#Details: { - Data: [ - {Value: currency_code, Label:'Currency'} - ] - }, - FieldGroup#Created: { - Data: [ - {Value: createdBy}, - {Value: createdAt}, - ] - }, - FieldGroup#Modified: { - Data: [ - {Value: modifiedBy}, - {Value: modifiedAt}, - ] - }, - }, -) { - createdAt @UI.HiddenFilter:false; - createdBy @UI.HiddenFilter:false; -}; - - - -//The enity types name is OrdersService.my_bookshop_OrderItems -//The annotations below are not generated in edmx WHY? -annotate OrdersService.OrderItems with @( - UI: { - HeaderInfo: { - TypeName: 'Order Item', TypeNamePlural: ' ', - Title: { - Value: book.title - }, - Description: {Value: book.descr} - }, - // There is no filterbar for items so the selctionfileds is not needed - SelectionFields: [ book_ID ], - //////////////////////////////////////////////////////////////////////////// - // - // Lists of OrderItems - // - LineItem: [ - {Value: book_ID, Label:'Book'}, - //The following entry is only used to have the assoication followed in the read event - {Value: book.price, Label:'Book Price'}, - {Value: amount, Label:'Quantity'}, - ], - Identification: [ //Is the main field group - //{Value: ID, Label:'ID'}, //A guid shouldn't be on the UI - {Value: book_ID, Label:'Book'}, - {Value: amount, Label:'Amount'}, - ], - Facets: [ - {$Type: 'UI.ReferenceFacet', Label: '{i18n>OrderItems}', Target: '@UI.Identification'}, - ], - }, -); \ No newline at end of file diff --git a/fiori/app/services.cds b/fiori/app/services.cds new file mode 100644 index 00000000..a27c8868 --- /dev/null +++ b/fiori/app/services.cds @@ -0,0 +1,10 @@ +/* + This model controls what gets served to Fiori frontends... +*/ + +using from './admin-authors/fiori-service'; +using from './admin-books/fiori-service'; +using from './browse/fiori-service'; +using from './genres/fiori-service'; +using from './common'; +using from '@capire/bookstore/srv/mashup'; diff --git a/fiori/db/common.cds b/fiori/db/common.cds new file mode 100644 index 00000000..38438e78 --- /dev/null +++ b/fiori/db/common.cds @@ -0,0 +1,14 @@ +namespace sap.capire.bookshop; + +using { sap.capire.bookshop } from '@capire/bookstore/srv/mashup'; + +entity GenreHierarchy : bookshop.Genres { + hierarchyLevel : Integer default 0; + drillState : String default 'leaf'; + parent : Association to GenreHierarchy; + children : Composition of many GenreHierarchy on children.parent = $self; +} + +extend service CatalogService with { + @readonly entity GenreHierarchy as projection on bookshop.GenreHierarchy; +} diff --git a/fiori/db/data/sap.capire.bookshop-GenreHierarchy.csv b/fiori/db/data/sap.capire.bookshop-GenreHierarchy.csv new file mode 100644 index 00000000..f0d3743e --- /dev/null +++ b/fiori/db/data/sap.capire.bookshop-GenreHierarchy.csv @@ -0,0 +1,16 @@ +ID;parent_ID;name;hierarchyLevel;drillState +10;;Fiction;0;expanded +11;10;Drama;1;leaf +12;10;Poetry;1;leaf +13;10;Fantasy;1;leaf +14;10;Science Fiction;1;leaf +15;10;Romance;1;leaf +16;10;Mystery;1;leaf +17;10;Thriller;1;leaf +18;10;Dystopia;1;leaf +20;;Non-Fiction;0;expanded +19;10;Fairy Tale;1;leaf +21;20;Biography;1;expanded +22;21;Autobiography;2;leaf +23;20;Essay;1;leaf +24;20;Speech;1;leaf diff --git a/fiori/db/hana/index.cds b/fiori/db/hana/index.cds new file mode 100644 index 00000000..866e8741 --- /dev/null +++ b/fiori/db/hana/index.cds @@ -0,0 +1,10 @@ +// +// Add Author.age and .lifetime with a DB-specific function +// + +using { AdminService } from '@capire/bookshop'; + +extend projection AdminService.Authors with { + YEARS_BETWEEN(dateOfBirth, dateOfDeath) as age: Integer, + YEAR(dateOfBirth) || ' – ' || YEAR(dateOfDeath) as lifetime : String +} diff --git a/fiori/db/schema.cds b/fiori/db/schema.cds deleted file mode 100644 index 5d4e2e82..00000000 --- a/fiori/db/schema.cds +++ /dev/null @@ -1,3 +0,0 @@ -// Proxy for importing schema from bookshop sample -using from '@capire/bookshop'; -namespace sap.capire.bookshop; diff --git a/fiori/db/sqlite/index.cds b/fiori/db/sqlite/index.cds new file mode 100644 index 00000000..7bdfc6bb --- /dev/null +++ b/fiori/db/sqlite/index.cds @@ -0,0 +1,10 @@ +// +// Add Author.age and .lifetime with a DB-specific function +// + +using { AdminService } from '@capire/bookshop'; + +extend projection AdminService.Authors with { + strftime('%Y',dateOfDeath)-strftime('%Y',dateOfBirth) as age: Integer, + strftime('%Y',dateOfBirth) || ' – ' || strftime('%Y',dateOfDeath) as lifetime : String +} diff --git a/fiori/index.cds b/fiori/index.cds new file mode 100644 index 00000000..1ea0235e --- /dev/null +++ b/fiori/index.cds @@ -0,0 +1 @@ +using from './db/common'; diff --git a/fiori/package.json b/fiori/package.json index fb3a21f8..187e4059 100644 --- a/fiori/package.json +++ b/fiori/package.json @@ -2,11 +2,11 @@ "name": "@capire/fiori", "version": "1.0.0", "dependencies": { - "@capire/bookshop": "../bookshop", - "@capire/orders": "../orders", - "@capire/common": "../common", - "@sap/cds": "^4", - "express": "^4.17.1" + "@capire/bookstore": "*", + "@sap/cds": ">=5", + "@sap/cds-odata-v2-adapter-proxy": "^1.9.0", + "express": "^4.17.1", + "passport": ">=0.4.1" }, "scripts": { "start": "cds run --in-memory?", @@ -14,9 +14,39 @@ }, "cds": { "requires": { + "ReviewsService": { + "kind": "odata", + "model": "@capire/reviews" + }, + "OrdersService": { + "kind": "odata", + "model": "@capire/orders" + }, + "messaging": { + "[production]": { + "kind": "enterprise-messaging" + }, + "[development]": { + "kind": "file-based-messaging" + }, + "[hybrid!]": { + "kind": "enterprise-messaging-shared" + } + }, "db": { "kind": "sql" + }, + "db-ext": { + "[development]": { + "model": "db/sqlite" + }, + "[production]": { + "model": "db/hana" + } } + }, + "hana": { + "deploy-format": "hdbtable" } } -} \ No newline at end of file +} diff --git a/fiori/server.js b/fiori/server.js new file mode 100644 index 00000000..b3ab5dde --- /dev/null +++ b/fiori/server.js @@ -0,0 +1,8 @@ +// install OData v2 adapter +const cds = require("@sap/cds") +const proxy = require('@sap/cds-odata-v2-adapter-proxy') +const opts = global.it ? { target:'auto' } : {} // for tests, set 'auto' to detect port dynamically +cds.on('bootstrap', app => app.use(proxy(opts))) // install proxy +cds.log('cov2ap','silent') // suppress anoying log outpout, e.g. for `npm run mocha -- --reporter nyan` + +module.exports = require('@capire/bookstore/server.js') diff --git a/fiori/srv/admin-service.cds b/fiori/srv/admin-service.cds deleted file mode 100644 index eb518438..00000000 --- a/fiori/srv/admin-service.cds +++ /dev/null @@ -1,3 +0,0 @@ -// Proxy for importing services from bookshop sample -using from '@capire/bookshop'; -annotate AdminService with @impl:'srv/admin-service.js'; diff --git a/fiori/srv/admin-service.js b/fiori/srv/admin-service.js deleted file mode 100644 index e8853182..00000000 --- a/fiori/srv/admin-service.js +++ /dev/null @@ -1,8 +0,0 @@ -const cds = require('@sap/cds') - -module.exports = cds.service.impl (async function() { - const {Books} = cds.entities - const {ID} = await SELECT.one.from(Books).columns('max(ID) as ID') - let newID = ID - ID % 100 + 100 - this.before ('NEW','Books', req => req.data.ID = ++newID) -}) diff --git a/hello/README.md b/hello/README.md new file mode 100644 index 00000000..eb999210 --- /dev/null +++ b/hello/README.md @@ -0,0 +1,15 @@ +# Hello World Getting Started Sample + +## Next Steps + +- To run the JavaScript implementation, open a new terminal and run `cds watch`. +- To run the TypeScript implementation, open a new terminal and run `cds-ts watch`. + +Then call the service at: http://localhost:4004/say/hello(to='world') + +## Learn More + +Learn more about: + +- [Hello World!](https://cap.cloud.sap/docs/get-started/hello-world) +- [Using TypeScript](https://cap.cloud.sap/docs/get-started/using-typescript) \ No newline at end of file diff --git a/hello/package.json b/hello/package.json index ef9c6602..ee2b4b01 100644 --- a/hello/package.json +++ b/hello/package.json @@ -2,6 +2,41 @@ "name": "@capire/hello-world", "version": "1.0.0", "scripts": { - "watch": "cds serve world.cds" + "test": "npx jest --silent", + "start": "cds serve srv/world.cds", + "start:ts": "cds-ts serve srv/world.cds" + }, + "dependencies": { + "@sap/cds": ">=5.0.4" + }, + "devDependencies": { + "@types/jest": "*", + "@types/node": "*", + "typescript": "^4.3.5" + }, + "eslintConfig": { + "extends": "eslint:recommended", + "env": { + "es2020": true, + "node": true, + "jest": true, + "mocha": true + }, + "globals": { + "SELECT": true, + "INSERT": true, + "UPDATE": true, + "DELETE": true, + "CREATE": true, + "DROP": true, + "CDL": true, + "CQL": true, + "CXL": true, + "cds": true + }, + "rules": { + "no-console": "off", + "require-atomic-updates": "off" + } } -} \ No newline at end of file +} diff --git a/hello/world.cds b/hello/srv/world.cds similarity index 100% rename from hello/world.cds rename to hello/srv/world.cds diff --git a/hello/srv/world.js b/hello/srv/world.js new file mode 100644 index 00000000..c5cd2495 --- /dev/null +++ b/hello/srv/world.js @@ -0,0 +1,7 @@ +module.exports = class say { + hello(req) { + let {to} = req.data + if (to === 'me') to = require('os').userInfo().username + return `Hello ${to}!` + } +} diff --git a/hello/srv/world.ts b/hello/srv/world.ts new file mode 100644 index 00000000..c62df0e8 --- /dev/null +++ b/hello/srv/world.ts @@ -0,0 +1,7 @@ +import type { Request } from "@sap/cds/apis/services" + +module.exports = class say { + hello(req: Request) { + return `Hello ${req.data.to} from a TypeScript file!` + } +} diff --git a/hello/test/hello-world-test.js b/hello/test/hello-world-test.js new file mode 100644 index 00000000..b2ea3ef1 --- /dev/null +++ b/hello/test/hello-world-test.js @@ -0,0 +1,13 @@ +const cds = require ('@sap/cds') +describe('Hello world!', () => { + + beforeAll (()=> process.env.CDS_TYPESCRIPT = true) + afterAll (()=> delete process.env.CDS_TYPESCRIPT) + const {GET} = cds.test.in(__dirname,'../srv').run('serve', 'world.cds') + + it('should say hello with class impl', async () => { + const {data} = await GET`/say/hello(to='world')` + expect(data.value).toMatch(/Hello world.*typescript.*/i) + }) + +}) diff --git a/hello/test.http b/hello/test/test.http similarity index 100% rename from hello/test.http rename to hello/test/test.http diff --git a/hello/world.js b/hello/world.js deleted file mode 100644 index ff1a370e..00000000 --- a/hello/world.js +++ /dev/null @@ -1,3 +0,0 @@ -module.exports = class say { - hello(req) { return `Hello ${req.data.to}!` } -} diff --git a/loggers/app/loggers.html b/loggers/app/loggers.html new file mode 100644 index 00000000..2d588e7b --- /dev/null +++ b/loggers/app/loggers.html @@ -0,0 +1,76 @@ + + + + + cds.log + + + + + + + +
+

Log Levels

+ + + + + + + + + + +
Module ID Log Level
{{ each.id }} +
+

Log Format:

+ [ + | + | + | + | + ] - log message ... +
+ + + + + diff --git a/loggers/package.json b/loggers/package.json new file mode 100644 index 00000000..4f76f7f2 --- /dev/null +++ b/loggers/package.json @@ -0,0 +1,22 @@ +{ + "name": "@capire/loggers", + "version": "1.0.0", + "description": "Simple sample on how to dynamically set cds.log levels and formats.", + "files": [ + "app", + "srv" + ], + "dependencies": { + "@sap/cds": ">=5.9", + "express": "^4.17.1" + }, + "scripts": { + "start": "cds run", + "watch": "cds watch" + }, + "cds": { + "requires": { + "db": "sql" + } + } +} diff --git a/loggers/readme.md b/loggers/readme.md new file mode 100644 index 00000000..c030f889 --- /dev/null +++ b/loggers/readme.md @@ -0,0 +1,11 @@ +# Dynamically Set `cds.log` Levels and Formats + +### Run + +```sh +cds watch +``` + +### Test + +Either using the UI through http://localhost:4004/loggers.html, or try the requests in `test/requests.http` diff --git a/loggers/srv/dummy.cds b/loggers/srv/dummy.cds new file mode 100644 index 00000000..7ed8e09d --- /dev/null +++ b/loggers/srv/dummy.cds @@ -0,0 +1,3 @@ +service Sue { + entity Dummy { key ID: UUID; title: String; } +} diff --git a/loggers/srv/loggers.cds b/loggers/srv/loggers.cds new file mode 100644 index 00000000..280ca33b --- /dev/null +++ b/loggers/srv/loggers.cds @@ -0,0 +1,20 @@ +@rest service LogService { + + @readonly entity Loggers : Logger {}; + entity Logger { + key id : String; + level : String; + } + + action format ( + timestamp : Boolean, + level : Boolean, + tenant : Boolean, + reqid : Boolean, + id : Boolean, + ); + + action debug (logger : String) returns Logger; + action reset (logger : String) returns Logger; + +} diff --git a/loggers/srv/loggers.js b/loggers/srv/loggers.js new file mode 100644 index 00000000..5fcd7226 --- /dev/null +++ b/loggers/srv/loggers.js @@ -0,0 +1,56 @@ +const cds = require ('@sap/cds/lib') +const LOG = cds.log('cds.log') + +module.exports = class LogService extends cds.Service { + init(){ + + this.on('GET','Loggers', (req)=>{ + let loggers = Object.values(cds.log.loggers).map (_logger) + let {$search} = req._.req.query + if ($search) { + const re = RegExp($search,'i') + loggers = loggers.filter (l => re.test(l.id) || re.test(l.level)) + } + return loggers.sort ((a,b) => a.id < b.id ? -1 : 1) + }) + + this.on('PUT','Logger', (req)=>{ + const {id} = req.params[0] || req.data + if (!id) return req.reject('No logger id specified in request') + return _logger (cds.log (id, req.data)) + }) + + this.on('debug', (req)=>{ + const {logger:id} = req.params[0] || req.data + if (!id) return req.reject('No logger id specified in request') + return _logger (cds.log (id, {level:'debug'})) + }) + + this.on('reset', (req)=>{ + const {logger:id} = req.params[0] || req.data + if (!id) return req.reject('No logger id specified in request') + return _logger (cds.log (id, {level:'info'})) + }) + + this.on('format', (req)=>{ + const $ = req.data; LOG.info('format:',$) + // Set format for new loggers constructed subsequently + cds.log.format = (id, level, ...args) => { + const fmt = [] + if ($.timestamp) fmt.push ('|', (new Date).toISOString()) + if ($.level) fmt.push ('|', _levels[level].padEnd(5)) + if ($.tenant) fmt.push ('|', cds.context && cds.context.tenant) + if ($.reqid) fmt.push ('|', cds.context && cds.context.id) + if ($.id) fmt.push ('|', id) + fmt[0] = '[', fmt.push ('] -', ...args) + return fmt + } + // Apply this format to all existing loggers + Object.values(cds.log.loggers).forEach (l => l.setFormat (cds.log.format)) + }) + } + +} + +const _logger = ({id,level}) => ({id, level:_levels[level] }) +const _levels = [ 'SILENT', 'ERROR', 'WARN', 'INFO', 'DEBUG', 'TRACE' ] diff --git a/loggers/test/requests.http b/loggers/test/requests.http new file mode 100644 index 00000000..904d44bf --- /dev/null +++ b/loggers/test/requests.http @@ -0,0 +1,18 @@ +http://localhost:4004/loggers.html +@body: = Content-Type: application/json\n\n + +### +GET http://localhost:4004/log/Loggers + +### +PUT http://localhost:4004/log/Logger/sqlite +{{body:}} { "level": "debug" } + +### +POST http://localhost:4004/log/debug(logger='sqlite') + +### +POST http://localhost:4004/log/reset(logger='sqlite') + +### Dummy request to see sqlite debug output +GET http://localhost:4004/sue/Dummy diff --git a/media/srv/media-service.js b/media/srv/media-service.js index f70d3b90..b656f03c 100644 --- a/media/srv/media-service.js +++ b/media/srv/media-service.js @@ -40,7 +40,7 @@ module.exports = srv => { req.reject(404, 'Media not found for the ID') return } - const decodedMedia = new Buffer( + const decodedMedia = Buffer.from( mediaObj.media.split(';base64,').pop(), 'base64' ) diff --git a/orders/.env b/orders/.env new file mode 100644 index 00000000..616dd8d0 --- /dev/null +++ b/orders/.env @@ -0,0 +1,2 @@ +cds.requires.messaging.kind = file-based-messaging +PORT = 4006 \ No newline at end of file diff --git a/orders/app/fiori.cds b/orders/app/fiori.cds new file mode 100644 index 00000000..017b806b --- /dev/null +++ b/orders/app/fiori.cds @@ -0,0 +1,97 @@ + + +//////////////////////////////////////////////////////////////////////////// +// +// Note: this is designed for the OrdersService being co-located with +// bookshop. It does not work if OrdersService is run as a separate +// process, and is not intended to do so. +// +//////////////////////////////////////////////////////////////////////////// + + + +using { OrdersService } from '../srv/orders-service'; + + +@odata.draft.enabled +annotate OrdersService.Orders with @( + UI: { + SelectionFields: [ createdBy ], + LineItem: [ + {Value: OrderNo, Label:'{i18n>OrderNo}'}, + {Value: buyer, Label:'{i18n>Customer}'}, + {Value: currency.symbol, Label:'{i18n>Currency}'}, + {Value: createdAt, Label:'{i18n>Date}'}, + ], + HeaderInfo: { + TypeName: '{i18n>Order}', TypeNamePlural: '{i18n>Orders}', + Title: { + Label: '{i18n>OrderNo}', //A label is possible but it is not considered on the ObjectPage yet + Value: OrderNo + }, + Description: {Value: createdBy} + }, + Identification: [ //Is the main field group + {Value: createdBy, Label:'{i18n>Customer}'}, + {Value: createdAt, Label:'{i18n>Date}'}, + {Value: OrderNo }, + ], + HeaderFacets: [ + {$Type: 'UI.ReferenceFacet', Label: '{i18n>Created}', Target: '@UI.FieldGroup#Created'}, + {$Type: 'UI.ReferenceFacet', Label: '{i18n>Modified}', Target: '@UI.FieldGroup#Modified'}, + ], + Facets: [ + {$Type: 'UI.ReferenceFacet', Label: '{i18n>Details}', Target: '@UI.FieldGroup#Details'}, + {$Type: 'UI.ReferenceFacet', Label: '{i18n>OrderItems}', Target: 'Items/@UI.LineItem'}, + ], + FieldGroup#Details: { + Data: [ + {Value: currency.code, Label:'{i18n>Currency}'} + ] + }, + FieldGroup#Created: { + Data: [ + {Value: createdBy}, + {Value: createdAt}, + ] + }, + FieldGroup#Modified: { + Data: [ + {Value: modifiedBy}, + {Value: modifiedAt}, + ] + }, + }, +) { + createdAt @UI.HiddenFilter:false; + createdBy @UI.HiddenFilter:false; + ID @UI.Hidden; +}; + + + +annotate OrdersService.Orders.Items with @( + UI: { + LineItem: [ + {Value: product_ID, Label:'{i18n>ProductID}'}, + {Value: title, Label:'{i18n>ProductTitle}'}, + {Value: price, Label:'{i18n>UnitPrice}'}, + {Value: quantity, Label:'{i18n>Quantity}'}, + ], + Identification: [ //Is the main field group + {Value: quantity, Label:'{i18n>Quantity}'}, + {Value: title, Label:'{i18n>Product}'}, + {Value: price, Label:'{i18n>UnitPrice}'}, + ], + Facets: [ + {$Type: 'UI.ReferenceFacet', Label: '{i18n>OrderItems}', Target: '@UI.Identification'}, + ], + }, +) { + quantity @( + Common.FieldControl: #Mandatory + ); + ID @UI.Hidden; + up_ @UI.Hidden; + +}; diff --git a/fiori/app/fiori.html b/orders/app/orders/index.html similarity index 50% rename from fiori/app/fiori.html rename to orders/app/orders/index.html index d011797c..5761894b 100644 --- a/fiori/app/fiori.html +++ b/orders/app/orders/index.html @@ -11,25 +11,9 @@ window["sap-ushell-config"] = { defaultRenderer: "fiori2", applications: { - "browse-books": { - title: "Browse Books", - description: "... testing FE v42", - additionalInformation: "SAPUI5.Component=bookshop", - applicationType : "URL", - url: "/browse/webapp", - navigationMode: "embedded" - }, - "manage-books": { - title: "Manage Books", - description: "... testing FE v42", - additionalInformation: "SAPUI5.Component=admin", - applicationType : "URL", - url: "/admin/webapp", - navigationMode: "embedded" - }, "manage-orders": { - title: "Order Books", - description: "... testing FE v42", + title: "Manage Orders", + description: "CAP Sample App", additionalInformation: "SAPUI5.Component=orders", applicationType : "URL", url: "/orders/webapp", @@ -40,12 +24,11 @@ - - + + + + + +
+ +

Capire Reviews

+ + + + + + + + + + + + + + + + +
Subject Rating Title Date
{{ review.subject }}{{ review.rating | stars }}{{ review.title }}{{ review.date | datetime }}
+ + + +
+ + + + + + {{ message.succeeded }} + {{ message.failed }} +
+
+ ( click on a row to see details... ) +
+ + +
+ + + + diff --git a/reviews/db/data/sap.capire.reviews-Reviews.csv b/reviews/db/data/sap.capire.reviews-Reviews.csv new file mode 100644 index 00000000..90112979 --- /dev/null +++ b/reviews/db/data/sap.capire.reviews-Reviews.csv @@ -0,0 +1,5 @@ +subject;rating;reviewer;title;text +201;5;bob;Intriguing;Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. +201;4;bob;Fascinating;Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Id diam maecenas ultricies mi eget mauris pharetra et. Risus at ultrices mi tempus imperdiet nulla malesuada pellentesque. Pulvinar mattis nunc sed blandit libero. Facilisis magna etiam tempor orci eu. Nec sagittis aliquam malesuada bibendum arcu. Eu consequat ac felis donec. Ultricies tristique nulla aliquet enim tortor at auctor urna nunc. Tortor posuere ac ut consequat semper viverra nam libero. Amet nisl suscipit adipiscing bibendum est ultricies integer quis auctor. Scelerisque purus semper eget duis at tellus. Elementum tempus egestas sed sed risus pretium. Arcu dictum varius duis at. Amet luctus venenatis lectus magna fringilla urna. Eget velit aliquet sagittis id consectetur purus ut faucibus. Vitae auctor eu augue ut lectus. Fermentum iaculis eu non diam phasellus vestibulum. +207;2;bob;What is this?;Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Libero justo laoreet sit amet cursus sit amet dictum. Nunc faucibus a pellentesque sit. Dis parturient montes nascetur ridiculus mus mauris vitae ultricies. Enim nunc faucibus a pellentesque. Commodo quis imperdiet massa tincidunt nunc pulvinar sapien. Cras ornare arcu dui vivamus. Facilisi etiam dignissim diam quis enim lobortis. Et molestie ac feugiat sed. Urna neque viverra justo nec ultrices dui. Ullamcorper a lacus vestibulum sed arcu non. Volutpat ac tincidunt vitae semper quis. Dignissim sodales ut eu sem. Feugiat in fermentum posuere urna nec. At augue eget arcu dictum varius. +251;3;bob;It's dark...;Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Suscipit tellus mauris a diam. Velit aliquet sagittis id consectetur purus ut. Viverra adipiscing at in tellus integer. Vitae elementum curabitur vitae nunc. Mattis ullamcorper velit sed ullamcorper morbi. Diam quis enim lobortis scelerisque. Auctor neque vitae tempus quam pellentesque nec nam aliquam. Semper auctor neque vitae tempus. Quis eleifend quam adipiscing vitae proin. Neque convallis a cras semper auctor neque vitae. Imperdiet massa tincidunt nunc pulvinar sapien et ligula. Sit amet consectetur adipiscing elit ut aliquam purus. Pretium quam vulputate dignissim suspendisse. \ No newline at end of file diff --git a/reviews/db/schema.cds b/reviews/db/schema.cds index e49f90ca..2af0c7d8 100644 --- a/reviews/db/schema.cds +++ b/reviews/db/schema.cds @@ -17,7 +17,7 @@ entity Reviews { liked : Integer default 0; // counter for likes as helpful review (count of all _likes belonging to this review) } -type Rating : Decimal(3,2) enum { +type Rating : Integer enum { Best = 5; Good = 4; Avg = 3; @@ -32,7 +32,6 @@ entity Likes { // Auto-fill reviewers and review dates annotate Reviews with { - reviewer @cds.on.insert:$user; - date @cds.on.insert:$now; - date @cds.on.update:$now; + reviewer @cds.on:{insert:$user}; + date @cds.on:{insert:$now,update:$now}; } diff --git a/reviews/index.cds b/reviews/index.cds index c126bf5e..ac2c4e7a 100644 --- a/reviews/index.cds +++ b/reviews/index.cds @@ -1 +1,2 @@ using from './srv/reviews-service'; +namespace sap.capire.reviews; diff --git a/reviews/package.json b/reviews/package.json index 970b956c..5325bc17 100644 --- a/reviews/package.json +++ b/reviews/package.json @@ -7,18 +7,17 @@ "index.cds" ], "dependencies": { - "@sap/cds": "^4", + "@sap/cds": ">=5", "express": "^4.17.1" }, - "scripts": { - "reviews-service": "cds watch", - "books-reviewed": "cds watch ../reviewed" - }, "cds": { "requires": { - "db": { - "kind": "sql" - } + "messaging": { + "[development]": { "kind": "file-based-messaging" }, + "[hybrid]": { "kind": "enterprise-messaging-shared" }, + "[production]": { "kind": "enterprise-messaging" } + }, + "db": { "kind": "sql" } } } } \ No newline at end of file diff --git a/reviews/readme.md b/reviews/readme.md index 5574f752..2fe87b4e 100644 --- a/reviews/readme.md +++ b/reviews/readme.md @@ -2,20 +2,23 @@ ## Run all-in-one -Open a terminal window and run the bookshop in it: +Open a terminal window and run the `fiori` app in it: + ```sh -npm run bookshop +npm run fiori ``` -## Run as separate services +## Run as Separate Services + +Open two terminal windows. In the first one start the reviews service stand-alone: -Open two terminal windows, and in the first one start the reviews service stand-alone: ```sh npm run reviews-service ``` -In the the second one start the bookshop: +In the second one start the `fiori` app: + ```sh -npm run bookshop +npm run fiori ``` diff --git a/reviews/srv/reviews-service.cds b/reviews/srv/reviews-service.cds index 027fb961..a264ba8f 100644 --- a/reviews/srv/reviews-service.cds +++ b/reviews/srv/reviews-service.cds @@ -2,29 +2,37 @@ using { sap.capire.reviews as my } from '../db/schema'; service ReviewsService { + // Sync API entity Reviews as projection on my.Reviews excluding { likes } action like (review: type of Reviews:ID); action unlike (review: type of Reviews:ID); + // Async API + event reviewed : { + subject : type of Reviews:subject; + count : Integer; + rating : Decimal; + } + // Input validation annotate Reviews with { subject @mandatory; title @mandatory; - rating @mandatory @assert.enum; + rating @assert.range; } } // Access control restrictions -annotate ReviewsService.Reviews with @restrict_:[ +annotate ReviewsService.Reviews with @restrict:[ { grant:'READ', to:'any' }, // everybody can read reviews { grant:'CREATE', to:'authenticated-user' }, // users must login to add reviews { grant:'UPDATE', to:'authenticated-user', where:'reviewer=$user' }, { grant:'DELETE', to:'admin' }, ]; -annotate ReviewsService with @restrict_:[ +annotate ReviewsService with @restrict:[ { grant:'like', to:'identified-user' }, { grant:'unlike', to:'identified-user', where:'user=$user' }, ]; diff --git a/reviews/srv/reviews-service.js b/reviews/srv/reviews-service.js index 0eec865f..b9b5c6c9 100644 --- a/reviews/srv/reviews-service.js +++ b/reviews/srv/reviews-service.js @@ -1,30 +1,29 @@ const cds = require ('@sap/cds') -module.exports = cds.service.impl (async function(){ +module.exports = cds.service.impl (function(){ // Get the CSN definition for Reviews from the db schema for sub-sequent queries // ( Note: we explicitly specify the namespace to support embedded reuse ) const { Reviews, Likes } = this.entities ('sap.capire.reviews') - const messaging = await cds.connect.to('messaging') this.before (['CREATE','UPDATE'], 'Reviews', req => { if (!req.data.rating) req.data.rating = Math.round(Math.random()*4)+1 }) // Emit an event to inform subscribers about new avg ratings for reviewed subjects - this.after (['CREATE','UPDATE','DELETE'], 'Reviews', async(_,req) => { + this.after (['CREATE','UPDATE','DELETE'], 'Reviews', async function(_,req) { const {subject} = req.data - const {rating} = await cds.transaction(req) .run ( - SELECT.one (['round(avg(rating),2) as rating']) .from (Reviews) .where ({subject}) + const { count, rating } = await cds.tx(req) .run ( + SELECT.one `round(avg(rating),2) as rating, count(*) as count` .from (Reviews) .where ({subject}) ) - global.it || console.log ('< emitting:', 'reviewed', { subject, rating }) - messaging.tx(req).emit ('reviewed', { subject, rating }) + global.it || console.log ('< emitting:', 'reviewed', { subject, count, rating }) + await this.emit ('reviewed', { subject, count, rating }) }) // Increment counter for reviews considered helpful this.on ('like', (req) => { if (!req.user) return req.reject(400, 'You must be identified to like a review') const {review} = req.data, {user} = req - const tx = cds.transaction(req) + const tx = cds.tx(req) return tx.run ([ INSERT.into (Likes) .entries ({review_ID: review, user: user.id}), UPDATE (Reviews) .set({liked: {'+=': 1}}) .where({ID:review}) @@ -35,7 +34,7 @@ module.exports = cds.service.impl (async function(){ this.on ('unlike', async (req) => { if (!req.user) return req.reject(400, 'You must be identified to remove a former like of yours') const {review} = req.data, {user} = req - const tx = cds.transaction(req) + const tx = cds.tx(req) const affectedRows = await tx.run (DELETE.from (Likes) .where ({review_ID: review,user: user.id})) if (affectedRows === 1) return tx.run (UPDATE (Reviews) .set ({liked: {'-=': 1}}) .where ({ID:review})) }) diff --git a/samples.md b/samples.md index efa74a61..9caed0e8 100644 --- a/samples.md +++ b/samples.md @@ -1,28 +1,29 @@ # Overview of Samples -The list below gives an overview of the samples provided in subdirectories. -Each sub directory essentially is a individual npm package arranged in an [all-in-one monorepo](all-in-one-monorepo) umbrella setup. +The following list gives an overview of the samples provided in subdirectories. +Each sub directory essentially is an individual npm package arranged in an [all-in-one monorepo](#all-in-one-monorepo) umbrella setup. -## [hello](hello) +## [@capire/hello-world](hello) - A simplistic [Hello World](https://cap.cloud.sap/docs/get-started/hello-world) service using [CDS](https://cap.cloud.sap/docs/cds/) and [cds.services](https://cap.cloud.sap/docs/node.js/api#services-api). +- [Typescript support](https://cap.cloud.sap/docs/get-started/using-typescript) -## [bookshop](bookshop) +## [@capire/bookshop](bookshop) - [Getting Started](https://cap.cloud.sap/docs/get-started/in-a-nutshell) with CAP, briefly introducing: - [Project Setup](https://cap.cloud.sap/docs/get-started/) and [Layouts](https://cap.cloud.sap/docs/get-started/projects) -- [Domain Modelling](https://cap.cloud.sap/docs/guides/domain-models) +- [Domain Modeling](https://cap.cloud.sap/docs/guides/domain-models) - [Defining Services](https://cap.cloud.sap/docs/guides/providing-services) - [Generic Providers](https://cap.cloud.sap/docs/guides/generic-providers) - [Adding Custom Logic](https://cap.cloud.sap/docs/guides/service-impl) - [Using Databases](https://cap.cloud.sap/docs/guides/databases) -## [common](common) +## [@capire/common](common) -- Showcases how to extend [@sap/cds/common](https://cap.cloud.sap/docs/cds/common) thereby covering... +- Showcases how to extend [@sap/cds/common](https://cap.cloud.sap/docs/cds/common) thereby covering: - Building [extension packages](https://cap.cloud.sap/docs/guides/domain-models#aspects-extensibility) - Providing [reuse packages](https://cap.cloud.sap/docs/get-started/projects#sharing-and-reusing-content) - [Verticalization](https://cap.cloud.sap/docs/cds/common#adapting-to-your-needs) @@ -30,38 +31,58 @@ Each sub directory essentially is a individual npm package arranged in an [all-i - Used in the [fiori app sample](#fiori) -## [orders](orders) +## [@capire/orders](orders) -- Adds orders to the [bookshop](#bookshop), thereby demonstrating... +- A standalone orders management service, demonstrating: - Using [Compositions](https://cap.cloud.sap/docs/cds/cdl#compositions) in [Domain Models](https://cap.cloud.sap/docs/guides/domain-models), along with - [Serving deeply nested documents](https://cap.cloud.sap/docs/guides/generic-providers#serving-structured-data) -## [reviews](reviews) +## [@capire/reviews](reviews) -- Shows how to implement a modular service to manage product reviews, including... +- Shows how to implement a modular service to manage product reviews, including: - Consuming other services synchronously and asynchronously - Serving requests synchronously - Emitting events asynchronously -- Grow as you go, with... +- Grow as you go, with: - Mocking app services - Running service meshes - Late-cut Micro Services -- As well as managed data, input validations and authorization +- As well as managed data, input validations, and authorization -## [fiori](fiori) +## [@capire/bookstore](bookstore) -- [Adds a Fiori elements application](https://cap.cloud.sap/docs/guides/fiori/), introducing to... -- [OData Annotations](https://cap.cloud.sap/docs/guides/fiori#adding-odata-annotations) in `.cds` files -- Support for [Fiori Draft](https://cap.cloud.sap/docs/guides/fiori#draft) -- Support for [Value Helps](https://cap.cloud.sap/docs/guides/fiori#value-help) -- Serving Fiori apps locally -- Combining most of the other samples through [package reuse](https://cap.cloud.sap/docs/get-started/projects#sharing-and-reusing-content) +- A [composite app, reusing and combining](https://cap.cloud.sap/docs/guides/verticalize) these packages: + - [@capire/bookshop](bookshop) + - [@capire/reviews](reviews) + - [@capire/orders](orders) + - [@capire/common](common) + - [@capire/data-viewer](data-viewer) +- [The Vue.js app](bookshop/app/vue) imported from `bookshop` is served as well +- [The Vue.js app](reviews/app/vue) imported from `reviews` is served as well +- [The Vue.js app](data-viewer/app/data) imported from `data-viewer` is served as well +- [The Fiori app](orders/app) imported from `orders` is served as well +- [OpenAPI export + Swagger UI](https://cap.cloud.sap/docs/advanced/openapi) + +## [@capire/fiori](fiori) + +- Adds an SAP Fiori elements application to bookstore, thereby introducing: +- OData Annotations in `.cds` files +- Support for Fiori Draft +- Support for Value Helps +- Serving SAP Fiori apps locally +- Fiori Elements V2 + - OData V2 using CDS OData V2 Adapter Proxy + - List Report (type `TreeTable`) + - `@sap.hierarchy` annotations + +See the [Serving Fiori UIs](https://cap.cloud.sap/docs/advanced/fiori) documentation for more information. +
# All-in-one Monorepo -Each sample sub directory essentially is a standard npm package, some with standard npm dependencies to other samples. The root folder's [package.json](package.json) has local links to the sub folders, such that an `npm install` populates a local `node_modules` folder acts like a local npm registry to the individual sample packages. +Each sample sub directory essentially is a standard npm package, some with standard npm dependencies to other samples. The root folder's [package.json](package.json) has local links to the sub folders, such that an `npm install` populates a local `node_modules` folder and acts like a local npm registry to the individual sample packages. diff --git a/test/cds.js b/test/cds.js deleted file mode 100644 index bca7bf00..00000000 --- a/test/cds.js +++ /dev/null @@ -1,158 +0,0 @@ -const cds = module.exports = require('@sap/cds/lib') -if (!cds.test) { // monkey patching cds - - const { resolve, dirname } = require('path') - const cwd = process.cwd() - - // harmonizing jest and mocha - const is_mocha = !global.test - const is_jest = !!global.test - if (is_jest) { // it's jest - global.before = (msg,fn) => global.beforeAll(fn||msg) - global.after = (msg,fn) => global.afterAll(fn||msg) - } else { // it's mocha - global.beforeAll = global.before - global.afterAll = global.after - global.test = global.it - } - - // eslint-disable-next-line no-global-assign - require = (mod) => { - try { return module.require(mod) } - catch(e) { if (e.code === 'MODULE_NOT_FOUND') throw new Error (` - Failed to load required package '${mod}'. Please add it thru: - npm add -D ${mod === 'chai' ? 'chai chai-as-promised chai-subset' : mod} - `) } - } - - - - class Test { - - /** - * Launches a cds server with arbitrary port and returns a subclass which - * also acts as an axios lookalike, providing methods to send requests. - * @returns {Test} - */ - static run (cmd, ...args) { - - // Setting up test server - const console = global.console, logs=[] - const axios = require('axios').default - const test = {__proto__:Test.run, - - GET: (path,...etc) => axios.get (test.url+path,...etc) .catch(_error), - PUT: (path,...etc) => axios.put (test.url+path,...etc) .catch(_error), - POST: (path,...etc) => axios.post (test.url+path,...etc) .catch(_error), - PATCH: (path,...etc) => axios.patch (test.url+path,...etc) .catch(_error), - DEL: (path,...etc) => axios.delete (test.url+path,...etc) .catch(_error), - - get: (path,...etc) => axios.get (test.url+path,...etc) .catch(_error), - put: (path,...etc) => axios.put (test.url+path,...etc) .catch(_error), - post: (path,...etc) => axios.post (test.url+path,...etc) .catch(_error), - patch: (path,...etc) => axios.patch (test.url+path,...etc) .catch(_error), - delete: (path,...etc) => axios.delete (test.url+path,...etc) .catch(_error), - - } - - // launch cds server... - before (`launching ${cmd} ${args.join(' ')}...`, done => { - - // const cds = require('../index'), - const { isdir } = cds.utils - if (!args.length) { - let project = cmd; cmd = 'run' - if (isdir(project)) ; //> all fine - // Supporting .launch () - else if (isdir(resolve(project))) project = resolve(project) - else try { project = dirname (require.resolve(project+'/package.json')) } - catch(e) { throw cds.error (`Cannot resolve project folder for '${project}' in '${process.cwd()}'`) } - args.push (project, '--in-memory?') - } - - if (!process.env.CDS_TEST_VERBOSE) global.console = { __proto__: global.console, logs, - time: ()=>{}, timeEnd: (...args)=> logs.push(args), - debug: (...args)=> logs.push(args), - log: (...args)=> logs.push(args), - warn: (...args)=> logs.push(args), - error: (...args)=> logs.push(args), - dump(){ for (let each of logs) console.log (...each) }, - } - - // return done (new Error(11)) - process.env.PORT = '0' - const p = cds.exec (cmd, ...args) // TODO w/ @sap/cds@3.33.3: , '--port', '0') - if (p && 'catch' in p) p.catch (e => { - if (is_mocha) console.error(e) - done(e) - }) - - cds.once('listening', ({ server, url }) => { - Object.assign (test,{server,url}) - done() - }) - }) - - // shutdown cds server... - after (done => { - if (global.console !== console) global.console = console - if (cwd !== process.cwd()) process.chdir(cwd) - test.server ? test.server.close (done) : done() - process.emit('shutdown') - }) - - function _error (e) { - if (!e.response) throw e - if (!e.response.data) throw e - if (!e.response.data.error) throw e - const { code, message } = e.response.data.error - throw new Error (code && code !== 'null' ? `${code} - ${message}` : message) - } - - return test - } - - /** - * Serving projects from subfolders under the root specified by a sequence - * of path components which are concatenated with path.resolve(). - */ - in (...paths) { - process.chdir (resolve (...paths)) - return this - } - - /** - * Switch on/off console log output. - */ - verbose(v) { - process.env.CDS_TEST_VERBOSE = v - return this - } - - /** Lazily loads and returns an instance of chai */ - get chai() { - const chai = require('chai') - chai.use (require('chai-subset')) - chai.use (require('chai-as-promised')) - Object.defineProperty (this, 'chai', {value:chai}) - return chai - } - get expect(){ return this.chai.expect } - get assert(){ return this.chai.assert } - } - - - /** - * Test kit for jest or mocha testing, which can be used statically - * via the getters for chai, expect and assert or through a server - * started with cds.test(...). - * @type Test.run & Test - */ - Object.defineProperties (Test.run, Object.getOwnPropertyDescriptors (Test.prototype)) - Object.defineProperty (cds, 'test', {value:Test.run}) - const cds_load = cds.load; cds.load = (models,o)=>{ - if (typeof models === 'string') models = models.split(',') - return cds_load.call(cds,models,o) - } - -} diff --git a/test/cds.ql.test.js b/test/cds.ql.test.js index 010b6403..e3c76e42 100644 --- a/test/cds.ql.test.js +++ b/test/cds.ql.test.js @@ -1,95 +1,267 @@ -const cds = require('./cds'),{ expect } = cds.test -const CQL = ([cql]) => cds.parse.cql(cql) -const Foo = { name: 'Foo' } -const Books = { name: 'capire.bookshop.Books' } - -const { parse:cdr } = cds.ql - -// while jest has 'test' as alias to 'it', mocha doesn't -if (!global.test) global.test = it - describe('cds.ql → cqn', () => { - // + + const cds = require('@sap/cds/lib') + const { expect } = cds.test + const { cdr } = cds.ql + const Foo = { name: 'Foo' } + const Books = { name: 'capire.bookshop.Books' } + + const STAR = cdr ? '*' : { ref: ['*'] } + const skip = {to:{eql:()=>skip}} + const srv = new cds.Service let cqn - describe.skip(`BUGS + GAPS...`, () => { + expect.plain = (cqn) => !cqn.SELECT.one && !cqn.SELECT.distinct ? expect(cqn) : skip + expect.one = (cqn) => !cqn.SELECT.distinct ? expect(cqn) : skip - it('should consistently handle *', () => { - expect({ - SELECT: { from: { ref: ['Foo'] }, columns: ['*'] }, + describe.each(['SELECT', 'SELECT one', 'SELECT distinct'])(`%s...`, (each) => { + + let SELECT; beforeEach(()=> SELECT = ( + each === 'SELECT distinct' ? cds.ql.SELECT.distinct : + each === 'SELECT one' ? cds.ql.SELECT.one : + cds.ql.SELECT + )) + + test(`from Foo`, () => { + expect(cqn = SELECT `from Foo`) + .to.eql(SELECT.from `Foo`) + .to.eql(SELECT.from('Foo')) + .to.eql(SELECT.from(Foo)) + .to.eql(SELECT`Foo`) + .to.eql(SELECT('Foo')) + .to.eql(SELECT(Foo)) + expect.plain(cqn) + .to.eql(CQL`SELECT from Foo`) + .to.eql(srv.read `Foo`) + .to.eql(srv.read('Foo')) + .to.eql(srv.read(Foo)) + .to.eql({ + SELECT: { from: { ref: ['Foo'] } }, }) - .to.eql(CQL`SELECT * from Foo`) - .to.eql(CQL`SELECT from Foo{*}`) - .to.eql(SELECT('*').from(Foo)) - .to.eql(SELECT.from(Foo,['*'])) }) - - it('should consistently handle lists', () => { - const ID = 11, args = [`foo`, "'bar'", 3] - const cqn = CQL`SELECT from Foo where ID=11 and x in (foo,'bar',3)` - expect(SELECT.from(Foo).where(`ID=${ID} and x in (${args})`)).to.eql(cqn) - expect(SELECT.from(Foo).where(`ID=`, ID, `and x in`, args)).to.eql(cqn) - expect(SELECT.from(Foo).where({ ID, x:args })).to.eql(cqn) - }) - - }) - - - describe(`SELECT...`, () => { - test('from ( Foo )', () => { + if (each === 'SELECT') + test('SELECT ( Foo )', () => { expect({ SELECT: { from: { ref: ['Foo'] } }, }) .to.eql(CQL`SELECT from Foo`) - .to.eql(SELECT.from(Foo)) + .to.eql(SELECT(Foo)) }) - test('from ( ..., )', () => { - // Compiler - expect(CQL`SELECT from Foo[11]`).to.eql({ - SELECT: { - // REVISIT: add one:true? - from: { ref: [{ id: 'Foo', where: [{ val: 11 }] }] }, - }, + if (each === 'SELECT') + test('SELECT ( Foo ) .from ( Bar )', () => { + + expect({ + SELECT: { columns:[{ref:['Foo']}], from: { ref: ['Bar'] } }, + }) + .to.eql(CQL`SELECT Foo from Bar`) + .to.eql(SELECT `Foo` .from `Bar`) + .to.eql(SELECT `Foo` .from('Bar')) + .to.eql(SELECT('Foo').from('Bar')) + .to.eql(SELECT(['Foo']).from('Bar')) + .to.eql(SELECT(['Foo']).from('Bar')) + .to.eql(SELECT `Bar` .columns `Foo`) + .to.eql(SELECT `Bar` .columns ('Foo')) + .to.eql(SELECT `Bar` .columns (['Foo'])) + .to.eql(SELECT.from `Bar` .columns ('Foo')) + .to.eql(SELECT.from `Bar` .columns (['Foo'])) + + expect({ + SELECT: { columns:[ + {ref:['Foo']}, + {ref:['Boo']}, + ], from: { ref: ['Bar'] } }, + }) + .to.eql(CQL`SELECT Foo, Boo from Bar`) + .to.eql(SELECT `Foo, Boo` .from `Bar`) + .to.eql(SELECT `Foo, Boo` .from('Bar')) + .to.eql(SELECT('Foo','Boo').from('Bar')) + .to.eql(SELECT(['Foo','Boo']).from('Bar')) + .to.eql(SELECT `Bar` .columns `Foo, Boo`) + .to.eql(SELECT `Bar` .columns `{ Foo, Boo }`) + .to.eql(SELECT `Bar` .columns ('{ Foo, Boo }')) + .to.eql(SELECT `Bar` .columns ('Foo','Boo')) + .to.eql(SELECT `Bar` .columns (['Foo','Boo'])) + .to.eql(SELECT.from `Bar` .columns ('Foo','Boo')) + .to.eql(SELECT.from `Bar` .columns (['Foo','Boo'])) + + expect({ + SELECT: { columns:[ + {ref:['Foo']}, + {ref:['Boo']}, + {ref:['Moo']}, + ], from: { ref: ['Bar'] } }, + }) + .to.eql(CQL`SELECT Foo, Boo, Moo from Bar`) + .to.eql(SELECT `Foo, Boo, Moo` .from `Bar`) + .to.eql(SELECT `Foo, Boo, Moo` .from('Bar')) + .to.eql(SELECT('Foo','Boo','Moo').from('Bar')) + .to.eql(SELECT(['Foo','Boo','Moo']).from('Bar')) + .to.eql(SELECT `Bar` .columns `Foo, Boo, Moo`) + .to.eql(SELECT `Bar` .columns ('Foo','Boo','Moo')) + .to.eql(SELECT `Bar` .columns (['Foo','Boo','Moo'])) + .to.eql(SELECT.from `Bar` .columns ('Foo','Boo','Moo')) + .to.eql(SELECT.from `Bar` .columns (['Foo','Boo','Moo'])) + + + expect({ + SELECT: { one:true, columns:[{ref:['Foo']}], from: { ref: ['Bar'] } }, + }) + // .to.eql(CQL`SELECT one Foo from Bar`) + .to.eql(SELECT.one `Foo` .from `Bar`) + .to.eql(SELECT.one `Foo` .from('Bar')) + .to.eql(SELECT.one('Foo').from('Bar')) + .to.eql(SELECT.one(['Foo']).from('Bar')) + .to.eql(SELECT.one(['Foo']).from('Bar')) + .to.eql(SELECT.one('Bar',['Foo'])) + .to.eql(SELECT.one `Bar` .columns `Foo`) + .to.eql(SELECT.one('Bar').columns('Foo')) + .to.eql(SELECT.one('Bar').columns(['Foo'])) + .to.eql(SELECT.one.from('Bar',['Foo'])) + .to.eql(SELECT.one.from('Bar').columns('Foo')) + .to.eql(SELECT.one.from('Bar').columns(['Foo'])) + + expect({ + SELECT: { one:true, columns:[ + {ref:['Foo']}, + {ref:['Boo']}, + ], from: { ref: ['Bar'] } }, + }) + // .to.eql(CQL`SELECT Foo, Boo from Bar`) + .to.eql(SELECT.one `Foo, Boo` .from `Bar`) + .to.eql(SELECT.one `Foo, Boo` .from('Bar')) + .to.eql(SELECT.one('Foo','Boo').from('Bar')) + .to.eql(SELECT.one(['Foo','Boo']).from('Bar')) + .to.eql(SELECT.one('Bar',['Foo','Boo'])) + .to.eql(SELECT.one `Bar` .columns `Foo, Boo`) + .to.eql(SELECT.one('Bar').columns('Foo','Boo')) + .to.eql(SELECT.one('Bar').columns(['Foo','Boo'])) + .to.eql(SELECT.one.from('Bar',['Foo','Boo'])) + .to.eql(SELECT.one.from('Bar').columns('Foo','Boo')) + .to.eql(SELECT.one.from('Bar').columns(['Foo','Boo'])) + + expect({ + SELECT: { one:true, columns:[ + {ref:['Foo']}, + {ref:['Boo']}, + {ref:['Moo']}, + ], from: { ref: ['Bar'] } }, + }) + // .to.eql(CQL`SELECT Foo, Boo, Moo from Bar`) + .to.eql(SELECT.one `Foo, Boo, Moo` .from `Bar`) + .to.eql(SELECT.one `Foo, Boo, Moo` .from('Bar')) + .to.eql(SELECT.one('Foo','Boo','Moo').from('Bar')) + .to.eql(SELECT.one(['Foo','Boo','Moo']).from('Bar')) + .to.eql(SELECT.one('Bar',['Foo','Boo','Moo'])) + .to.eql(SELECT.one `Bar` .columns `Foo, Boo, Moo`) + .to.eql(SELECT.one('Bar').columns('Foo','Boo','Moo')) + .to.eql(SELECT.one('Bar').columns(['Foo','Boo','Moo'])) + .to.eql(SELECT.one.from('Bar',['Foo','Boo','Moo'])) + .to.eql(SELECT.one.from('Bar').columns('Foo','Boo','Moo')) + .to.eql(SELECT.one.from('Bar').columns(['Foo','Boo','Moo'])) + + }) + + if (each === 'SELECT') + test('from ( Foo )', () => { + expect({ + SELECT: { from: {ref: [{ id:'Foo', where: [{val:11}] }] }} + }) + .to.eql(srv.read`Foo[${11}]`) + .to.eql(SELECT`Foo[${11}]`) + + expect((cqn = SELECT`from Foo[ID=11]`)) + .to.eql(SELECT`from Foo[ID=${11}]`) + .to.eql(SELECT.from `Foo[ID=11]`) + .to.eql(SELECT.from `Foo[ID=${11}]`) + .to.eql(SELECT`Foo[ID=11]`) + expect.plain(cqn) + .to.eql(CQL`SELECT from Foo[ID=11]`) + .to.eql(srv.read`Foo[ID=11]`) + .to.eql({ + SELECT: { from: { + ref: [{ id: 'Foo', where: [{ ref: ['ID'] }, '=', { val: 11 }] }], + }}, }) - expect(CQL`SELECT from Foo[ID=11]`).to.eql({ - SELECT: { - // REVISIT: add one:true - from: { - ref: [{ id: 'Foo', where: [{ ref: ['ID'] }, '=', { val: 11 }] }], - }, - }, - }) + if (cdr) expect.plain (cqn) + .to.eql(SELECT`Foo[ID=${11}]`) + .to.eql(srv.read`Foo[ID=${11}]`) - // Runtime ds.ql - expect(SELECT.from(Foo, 11)) - .to.eql(SELECT.from(Foo, { ID: 11 })) - .to.eql(SELECT.from(Foo).byKey(11)) - .to.eql(SELECT.from(Foo).byKey({ ID: 11 })) - .to.eql(SELECT.one.from(Foo).where({ ID: 11 })) + // Following implicitly resolve to SELECT.one + expect(cqn = SELECT.from(Foo,11)) + .to.eql(SELECT.from(Foo,{ID:11})) + .to.eql(SELECT.from(Foo).byKey(11)) + .to.eql(SELECT.from(Foo).byKey({ID:11})) + if (cds.version >= '5.6.0') { + expect.one(cqn) + .to.eql({ + SELECT: { + one: true, + from: { ref: [{ id: 'Foo', where: [{ ref: ['ID'] }, '=', { val: 11 }] }] }, + }, + }) + } else { + expect.one(cqn) .to.eql({ - // REVISIT: should produce CQN as the ones above? SELECT: { one: true, from: { ref: ['Foo'] }, where: [{ ref: ['ID'] }, '=', { val: 11 }], }, }) + } - expect(CQL`SELECT from Foo[11]{a}`).to.eql({ + }) + + test('from Foo {...}', () => { + + expect(cqn = SELECT `*,a,b as c` .from `Foo`) + .to.eql(SELECT `*,a,b as c`. from(Foo)) + .to.eql(SELECT('*','a',{b:'c'}).from`Foo`) + .to.eql(SELECT('*','a',{b:'c'}).from(Foo)) + .to.eql(SELECT(['*','a',{b:'c'}]).from(Foo)) + .to.eql(SELECT.columns('*','a',{b:'c'}).from(Foo)) + .to.eql(SELECT.columns(['*','a',{b:'c'}]).from(Foo)) + .to.eql(SELECT.columns((foo) => { foo`.*`, foo.a, foo.b`as c` }).from(Foo)) + .to.eql(SELECT.columns((foo) => { foo('*'), foo.a, foo.b.as('c') }).from(Foo)) + .to.eql(SELECT.from(Foo).columns('*','a',{b:'c'})) + .to.eql(SELECT.from(Foo).columns(['*','a',{b:'c'}])) + .to.eql(SELECT.from(Foo).columns((foo) => { foo`.*`, foo.a, foo.b`as c` })) + .to.eql(SELECT.from(Foo).columns((foo) => { foo('*'), foo.a, foo.b.as('c') })) + .to.eql(SELECT.from(Foo,['*','a',{b:'c'}])) + .to.eql(SELECT.from(Foo, (foo) => { foo`.*`, foo.a, foo.b`as c` })) + .to.eql(SELECT.from(Foo, (foo) => { foo('*'), foo.a, foo.b.as('c') })) + + expect.plain(cqn) + .to.eql({ SELECT: { - // REVISIT: add one:true? - from: { ref: [{ id: 'Foo', where: [{ val: 11 }] }] }, - columns: [{ ref: ['a'] }], + from: { ref: ['Foo'] }, + columns: [ STAR, { ref: ['a'] }, { ref: ['b'], as: 'c' }], }, }) - expect(SELECT.from(Foo, 11, ['a'])) - .to.eql(SELECT.from(Foo, 11, (foo) => foo.a)) + cdr && expect.plain(cqn) + .to.eql(CQL`SELECT *,a,b as c from Foo`) + .to.eql(CQL`SELECT from Foo {*,a,b as c}`) + + // Test combination with key as second argument to .from + expect(cqn = SELECT.from(Foo, 11, ['a'])) + .to.eql(SELECT.from(Foo, 11, foo => foo.a)) + + if (cds.version >= '5.6.0') { + expect.one(cqn) + .to.eql({ + SELECT: { + one: true, + from: { ref: [{ id: 'Foo', where: [{ ref: ['ID'] }, '=', { val: 11 }]}] }, + columns: [{ ref: ['a'] }] + }, + }) + } else { + expect.one(cqn) .to.eql({ - // REVISIT: should produce CQN as the ones above? SELECT: { one: true, from: { ref: ['Foo'] }, @@ -97,173 +269,248 @@ describe('cds.ql → cqn', () => { where: [{ ref: ['ID'] }, '=', { val: 11 }], }, }) + } + }) - test('from ( ..., => {...})', () => { - // single *, prefix and postfix, as array and function - let parsed, fluid - expect((parsed = CQL`SELECT * from Foo`)).to.eql(CQL`SELECT from Foo{*}`) - //> .to.eql... FIXME: see skipped 'should handle * correctly' below - expect((fluid = SELECT('*').from(Foo))) - .to.eql(SELECT.from(Foo, ['*'])) - .to.eql(SELECT.from(Foo, (foo) => foo('*'))) - .to.eql(SELECT.from(Foo).columns('*')) - .to.eql(SELECT.from(Foo).columns((foo) => foo('*'))) - .to.eql({ - SELECT: { from: { ref: ['Foo'] }, columns: [cdr ? '*' : { ref: ['*'] }] }, + test('with nested expands', () => { + // SELECT from Foo { *, x, bar.*, car{*}, boo { *, moo.zoo } } + expect(cqn = + SELECT.from (Foo, foo => { + foo`*`, foo.x, foo.car`*`, foo.boo (b => { + b`*`, b.moo.zoo( + x => x.y.z + ) + }) }) - - if (cdr) expect(parsed).to.eql(fluid) - - // single column, prefix and postfix, as array and function - expect(CQL`SELECT a from Foo`) - expect(CQL`SELECT from Foo {a}`) - .to.eql(SELECT.from(Foo, ['a'])) - .to.eql(SELECT.from(Foo, (foo) => foo.a)) - .to.eql({ - SELECT: { from: { ref: ['Foo'] }, columns: [{ ref: ['a'] }] }, + ).to.eql( + SELECT.from (Foo, foo => { + foo('*'), foo.x, foo.car('*'), foo.boo (b => { + b('*'), b.moo.zoo( + x => x.y.z + ) + }) }) + ) - // multiple columns, prefix and postfix, as array and function - expect(CQL`SELECT a,b as c from Foo`) - - expect (CQL`SELECT from Foo {a,b as c}`).to.eql(cqn = { + expect.plain(cqn) + .to.eql({ SELECT: { from: { ref: ['Foo'] }, - columns: [{ ref: ['a'] }, { ref: ['b'], as: 'c' }], + columns: [ + STAR, + { ref: ['x'] }, + { ref: ['car'], expand: ['*'] }, + { + ref: ['boo'], + expand: [ '*', { ref: ['moo', 'zoo'], expand: [{ ref: ['y', 'z'] }] }], + }, + ], }, }) - expect(SELECT.from(Foo, ['a', { b: 'c' }])).to.eql(cqn) - expect( - SELECT.from(Foo, (foo) => { - foo.a, foo.b.as('c') - }) - ).to.eql(cqn) - expect(SELECT.from(Foo).columns('a', { b: 'c' })).to.eql(cqn) - expect(SELECT.from(Foo).columns(['a', { b: 'c' }])).to.eql(cqn) - expect( - SELECT.from(Foo).columns((foo) => { - foo.a, foo.b.as('c') - }) - ).to.eql(cqn) - - // multiple columns and *, prefix and postfix, as array and function - expect(CQL`SELECT *,a,b from Foo`).to.eql(CQL`SELECT from Foo{*,a,b}`) - //> .to.eql... FIXME: see skipped 'should handle * correctly' below - expect(SELECT.from(Foo, ['a', 'b', '*'])) - .to.eql(SELECT.from(Foo).columns('a', 'b', '*')) - .to.eql(SELECT.from(Foo).columns(['a', 'b', '*'])) - .to.eql( - SELECT.from(Foo, (foo) => { - foo.a, foo.b, foo('*') - }) - ) - .to.eql({ - SELECT: { - from: { ref: ['Foo'] }, - columns: [{ ref: ['a'] }, { ref: ['b'] }, cdr ? '*' : { ref: ['*'] }], - }, - }) - }) - - test('from ( ..., => _.expand ( x=>{...}))', () => { - // SELECT from Foo { *, x, bar.*, car{*}, boo { *, moo.zoo } } - expect( - SELECT.from(Foo, (foo) => { - foo('*'), - foo.x, - foo.car('*'), - foo.boo((b) => { - b('*'), b.moo.zoo((x) => x.y.z) - }) - }) - ).to.eql({ - SELECT: { - from: { ref: ['Foo'] }, - columns: [ - cdr ? '*' : { ref: ['*'] }, - { ref: ['x'] }, - { ref: ['car'], expand: ['*'] }, - { - ref: ['boo'], - expand: ['*', { ref: ['moo', 'zoo'], expand: [{ ref: ['y', 'z'] }] }], - }, - ], - }, - }) - }) - - test('from ( ..., => _.inline ( _=>{...}))', () => { - // SELECT from Foo { *, x, bar.*, car{*}, boo { *, moo.zoo } } - expect( - SELECT.from(Foo, (foo) => { - foo.bar('*'), - foo.bar('.*'), //> leading dot indicates inline - foo.boo((x) => x.moo.zoo), - foo.boo((_) => _.moo.zoo) //> underscore arg name indicates inline - }) - ).to.eql({ - SELECT: { - from: { ref: ['Foo'] }, - columns: [ - { ref: ['bar'], expand: ['*'] }, - { ref: ['bar'], inline: ['*'] }, - { ref: ['boo'], expand: [{ ref: ['moo', 'zoo'] }] }, - { ref: ['boo'], inline: [{ ref: ['moo', 'zoo'] }] }, - ], - }, - }) - }) - - test('one / distinct ...', () => { - expect(SELECT.distinct.from(Foo).SELECT) - // .to.eql(CQL(`SELECT distinct from Foo`).SELECT) - .to.eql(SELECT.distinct(Foo).SELECT) - .to.eql({ distinct: true, from: { ref: ['Foo'] } }) - - expect(SELECT.one.from(Foo).SELECT) - // .to.eql(CQL(`SELECT one from Foo`).SELECT) - .to.eql(SELECT.one(Foo).SELECT) - .to.eql({ one: true, from: { ref: ['Foo'] } }) - - expect(SELECT.one('a').from(Foo).SELECT) - // .to.eql(CQL(`SELECT distinct a from Foo`).SELECT) - .to.eql(SELECT.one(['a']).from(Foo).SELECT) - .to.eql(SELECT.one(Foo, ['a']).SELECT) - .to.eql(SELECT.one(Foo, (foo) => foo.a).SELECT) - .to.eql(SELECT.one.from(Foo, (foo) => foo.a).SELECT) - .to.eql(SELECT.one.from(Foo, ['a']).SELECT) - .to.eql({ - one: true, - from: { ref: ['Foo'] }, - columns: [{ ref: ['a'] }], - }) - // same for works distinct }) + + test('with nested inlines', () => { + // SELECT from Foo { *, x, bar.*, car{*}, boo { *, moo.zoo } } + expect.plain( + SELECT.from (Foo, foo => { + foo.bar `*`, + foo.bar `.*`, //> leading dot indicates inline + foo.boo(_ => _.moo.zoo), //> underscore arg name indicates inline + foo.boo(x => x.moo.zoo) + }) + ).to.eql({ + SELECT: { + from: { ref: ['Foo'] }, + columns: [ + { ref: ['bar'], expand: ['*'] }, + { ref: ['bar'], inline: ['*'] }, + { ref: ['boo'], inline: [{ ref: ['moo', 'zoo'] }] }, + { ref: ['boo'], expand: [{ ref: ['moo', 'zoo'] }] }, + ], + }, + }) + }) + + }) + + describe ('SELECT where...', ()=>{ + it('should correctly handle { ... and:{...} }', () => { expect(SELECT.from(Foo).where({ x: 1, and: { y: 2, or: { z: 3 } } })).to.eql({ SELECT: { from: { ref: ['Foo'] }, - where: [ + where: cdr ? [ + { ref: ['x'] }, + '=', + { val: 1 }, + 'and', + // '(', + {xpr:[ + { ref: ['y'] }, + '=', + { val: 2 }, + 'or', + { ref: ['z'] }, + '=', + { val: 3 }, + ]}, + // ')', + ] : [ { ref: ['x'] }, '=', { val: 1 }, 'and', '(', - { ref: ['y'] }, - '=', - { val: 2 }, - 'or', - { ref: ['z'] }, - '=', - { val: 3 }, + // {xpr:[ + { ref: ['y'] }, + '=', + { val: 2 }, + 'or', + { ref: ['z'] }, + '=', + { val: 3 }, + // ]}, ')', ], }, }) }) + test ("where x='*'", ()=>{ + if (cdr) + expect (SELECT.from(Foo).where({x:'*'})) + .to.eql(SELECT.from(Foo).where("x='*'")) + .to.eql(SELECT.from(Foo).where("x=",'*')) + .to.eql(SELECT.from(Foo).where`x=${'*'}`) + .to.eql( + CQL`SELECT from Foo where x='*'` + ) + if (cdr) + expect (SELECT.from(Foo).where({x:['*',1]})) + .to.eql(SELECT.from(Foo).where("x in ('*',1)")) + .to.eql(SELECT.from(Foo).where("x in",['*',1])) + .to.eql(SELECT.from(Foo).where`x in ${['*',1]}`) + .to.eql( + CQL`SELECT from Foo where x in ('*',1)` + ) + }) + + test ('where, and, or', ()=>{ + expect ( + SELECT.from(Foo).where({x:1,and:{y:2}}) + ).to.eql ( + CQL`SELECT from Foo where x=1 and y=2` + ) .to.eql ({ SELECT: { + from: {ref:['Foo']}, + where: [ + {ref:['x']}, '=', {val:1}, + 'and', + {ref:['y']}, '=', {val:2} + ] + }}) + + const ql_with_groups_fix = !!cds.ql.Query.prototype.flat + if (ql_with_groups_fix) { + + expect ( + SELECT.from(Foo).where({x:1}).or({y:2}).and({z:3}) + ).to.eql ({ SELECT: { + from: {ref:['Foo']}, + where: [ + {ref:['x']}, '=', {val:1}, + 'or', + {ref:['y']}, '=', {val:2}, + 'and', + {ref:['z']}, '=', {val:3}, + ] + }}) + + expect ( + SELECT.from(Foo).where({x:1,or:{y:2}}).and({z:3}) + ).to.eql ({ SELECT: { + from: {ref:['Foo']}, + where: [ + {xpr:[ + {ref:['x']}, '=', {val:1}, + 'or', + {ref:['y']}, '=', {val:2}, + ]}, + 'and', + {ref:['z']}, '=', {val:3}, + ] + }}) + + expect ( + SELECT.from(Foo).where({a:1}).or({x:1,or:{y:2}}).and({z:3}) + ).to.eql ({ SELECT: { + from: {ref:['Foo']}, + where: [ + {ref:['a']}, '=', {val:1}, + 'or', + {xpr:[ + {ref:['x']}, '=', {val:1}, + 'or', + {ref:['y']}, '=', {val:2}, + ]}, + 'and', + {ref:['z']}, '=', {val:3}, + ] + }}) + + expect ( + { SELECT: SELECT.from(Foo).where({x:1,or:{y:2}}).SELECT } + ).to.eql ({ SELECT: { + from: {ref:['Foo']}, + where: [ + {ref:['x']}, '=', {val:1}, + 'or', + {ref:['y']}, '=', {val:2}, + ] + }}) + + } + + + expect ( + SELECT.from(Foo).where({x:1,and:{y:2}}).or({z:3}) + ).to.eql ( + CQL`SELECT from Foo where x=1 and y=2 or z=3` + ) + + if (cdr) expect ( + SELECT.from(Foo).where({x:1}).and({y:2,or:{z:3}}) + ).to.eql ( + CQL`SELECT from Foo where x=1 and ( y=2 or z=3 )` + ) + + if (cdr) expect ( + SELECT.from(Foo).where({1:1}).and({x:1,or:{x:2}}).and({y:2,or:{z:3}}) + ).to.eql ( + CQL`SELECT from Foo where 1=1 and ( x=1 or x=2 ) and ( y=2 or z=3 )` + ) + + if (cdr) expect ( + SELECT.from(Foo).where({x:1,or:{x:2}}).and({y:2,or:{z:3}}) + ).to.eql ( + CQL`SELECT from Foo where ( x=1 or x=2 ) and ( y=2 or z=3 )` + ) + }) + + test('where ({x:[undefined]})', () => { + if (cdr) expect ( + SELECT.from(Foo).where({x:[undefined]}) + ).to.eql ({ SELECT: { + from: {ref:['Foo']}, + where: [ + {ref:['x']}, + 'in', + { list: [ {val:undefined} ] } + ] + }}) + }) + test('where ( ... cql | {x:y} )', () => { const args = [`foo`, "'bar'", 3] const ID = 11 @@ -279,18 +526,17 @@ describe('cds.ql → cqn', () => { ).to.eql({ SELECT: { from: { ref: ['Foo'] }, - where: cdr - ? [ - // '(', //> this one is not required - { ref: ['ID'] }, - '=', - { val: ID }, - 'and', - { ref: ['args'] }, - 'in', - { val: args }, - 'and', - '(', //> this one is missing, and that's changing the logic -> that's a BUG + where: cdr ? [ + { ref: ['ID'] }, + '=', + { val: ID }, + 'and', + { ref: ['args'] }, + 'in', + { list: args.map(val => ({ val })) }, + 'and', + { + xpr: [ { ref: ['x'] }, 'like', { val: '%x%' }, @@ -298,33 +544,51 @@ describe('cds.ql → cqn', () => { { ref: ['y'] }, '>=', { val: 9 }, - ')', ] - : [ - // '(', //> this one is not required - { ref: ['ID'] }, - '=', - { val: ID }, - 'and', - { ref: ['args'] }, - 'in', - { val: args }, - 'and', - '(', //> this one is missing, and that's changing the logic -> that's a BUG - { ref: ['x'] }, - 'like', - { val: '%x%' }, - 'or', - { ref: ['y'] }, - '>=', - { val: 9 }, - ')', - ], - }, + }, + ] : [ + { ref: ['ID'] }, + '=', + { val: ID }, + 'and', + { ref: ['args'] }, + 'in', + { list: args.map(val => ({ val })) }, + 'and', + '(', + { ref: ['x'] }, + 'like', + { val: '%x%' }, + 'or', + { ref: ['y'] }, + '>=', + { val: 9 }, + ')', + ], + } }) // using CQL fragments -> uses cds.parse.expr - expect((cqn = CQL`SELECT from Foo where ID=11 and x in ( foo, 'bar', 3)`)).to.eql({ + const is_v2 = !!cds.parse.expr('(1,2)').list + if (is_v2) expect((cqn = CQL`SELECT from Foo where ID=11 and x in ( foo, 'bar', 3)`)).to.eql({ + SELECT: { + from: { ref: ['Foo'] }, + where: [ + { ref: ['ID'] }, + '=', + { val: ID }, + 'and', + { ref: ['x'] }, + 'in', + {list:[ + { ref: ['foo'] }, + { val: 'bar' }, + { val: 3 }, + ]} + ], + }, + }) + else expect((cqn = CQL`SELECT from Foo where ID=11 and x in ( foo, 'bar', 3)`)).to.eql({ SELECT: { from: { ref: ['Foo'] }, where: [ @@ -345,7 +609,7 @@ describe('cds.ql → cqn', () => { }, }) - expect( + if (!is_v2) expect( SELECT.from(Foo).where(`x=`, 1, `or y.z is null and (a>`, 2, `or b=`, 3, `)`) ).to.eql(CQL`SELECT from Foo where x=1 or y.z is null and (a>2 or b=3)`) @@ -386,15 +650,63 @@ describe('cds.ql → cqn', () => { ).to.eql(cqn) }) - it('w/ plain SQL', () => { + test('w/ plain SQL', () => { expect(SELECT.from(Books) + 'WHERE ...').to.eql( 'SELECT * FROM capire_bookshop_Books WHERE ...' ) }) + it('should consistently handle *', () => { + if (!cdr) return + expect({ + SELECT: { from: { ref: ['Foo'] }, columns: ['*'] }, + }) + .to.eql(CQL`SELECT * from Foo`) + .to.eql(CQL`SELECT from Foo{*}`) + .to.eql(SELECT('*').from(Foo)) + .to.eql(SELECT.from(Foo,['*'])) + }) + + it('should consistently handle lists', () => { + if (!cdr) return + const ID = 11, args = [{ref:['foo']}, "bar", 3] + const cqn = CQL`SELECT from Foo where ID=11 and x in (foo,'bar',3)` + expect(SELECT.from(Foo).where`ID=${ID} and x in ${args}`).to.eql(cqn) + expect(SELECT.from(Foo).where(`ID=`, ID, `and x in`, args)).to.eql(cqn) + expect(SELECT.from(Foo).where({ ID, x:args })).to.eql(cqn) + }) + // }) + describe(`SELECT for update`, () => { + beforeAll(() => { + delete cds.env.sql.lock_acquire_timeout + }) + + it('no wait', () => { + const q = SELECT.from('Foo').forUpdate() + expect(q.SELECT.forUpdate).eqls({}) + }) + + it('specific wait', () => { + const q = SELECT.from('Foo').forUpdate({ wait: 1 }) + expect(q.SELECT.forUpdate).eqls({ wait: 1 }) + }) + + it('default wait', () => { + cds.env.sql.lock_acquire_timeout = 2 + const q = SELECT.from('Foo').forUpdate() + expect(q.SELECT.forUpdate).eqls({ wait: 2 }) + }) + + it('override default', () => { + cds.env.sql.lock_acquire_timeout = 1 + const q = SELECT.from('Foo').forUpdate({ wait:-1 }) + expect(q.SELECT.forUpdate).eqls({}) + }) + }) + describe(`INSERT...`, () => { test('entries ({a,b}, ...)', () => { const entries = [{ foo: 1 }, { boo: 2 }] @@ -446,21 +758,31 @@ describe('cds.ql → cqn', () => { describe(`UPDATE...`, () => { test('entity (..., )', () => { - expect(UPDATE(Books, 4711)) - .to.eql(UPDATE(Books, { ID: 4711 })) - .to.eql(UPDATE(Books).byKey(4711)) - .to.eql(UPDATE(Books).byKey({ ID: 4711 })) - .to.eql(UPDATE(Books).where({ ID: 4711 })) - .to.eql(UPDATE(Books).where(`ID=`, 4711)) - .to.eql(UPDATE.entity(Books, 4711)) - .to.eql(UPDATE.entity(Books, { ID: 4711 })) - // etc... - .to.eql({ + const cqnWhere = { UPDATE: { entity: 'capire.bookshop.Books', where: [{ ref: ['ID'] }, '=', { val: 4711 }], }, - }) + } + expect(UPDATE(Books).where({ ID: 4711 })) + .to.eql(UPDATE(Books).where(`ID=`, 4711)) + .to.eql(cqnWhere) + + const cqnKey = (cds.version >= '5.6.0') ? + { + UPDATE: { + entity: { ref: [{ id: 'capire.bookshop.Books', where: [{ ref: ['ID'] }, '=', { val: 4711 }] }] } + } + } + : cqnWhere + expect(UPDATE(Books, 4711)) + .to.eql(UPDATE(Books, { ID: 4711 })) + .to.eql(UPDATE(Books).byKey(4711)) + .to.eql(UPDATE(Books).byKey({ ID: 4711 })) + .to.eql(UPDATE.entity(Books, 4711)) + .to.eql(UPDATE.entity(Books, { ID: 4711 })) + // etc... + .to.eql(cqnKey) }) /* @@ -511,20 +833,29 @@ describe('cds.ql → cqn', () => { describe(`DELETE...`, () => { test('from (..., )', () => { + const cqnWhere = { + DELETE: { + from: 'capire.bookshop.Books', + where: [{ ref: ['ID'] }, '=', { val: 4711 }], + }, + } + expect(DELETE.from(Books).where({ ID: 4711 })) + .to.eql(DELETE.from(Books).where(`ID=`, 4711)) + .to.eql(cqnWhere) + const cqnKey = (cds.version >= '5.6.0') ? + { + DELETE: { + from: { ref: [{ id: 'capire.bookshop.Books', where: [{ ref: ['ID'] }, '=', { val: 4711 }]}] } + }, + } : cqnWhere + expect(DELETE(Books, 4711)) .to.eql(DELETE(Books, { ID: 4711 })) .to.eql(DELETE.from(Books, 4711)) .to.eql(DELETE.from(Books, { ID: 4711 })) .to.eql(DELETE.from(Books).byKey(4711)) .to.eql(DELETE.from(Books).byKey({ ID: 4711 })) - .to.eql(DELETE.from(Books).where({ ID: 4711 })) - .to.eql(DELETE.from(Books).where(`ID=`, 4711)) - .to.eql({ - DELETE: { - from: 'capire.bookshop.Books', - where: [{ ref: ['ID'] }, '=', { val: 4711 }], - }, - }) + .to.eql(cqnKey) }) test('/w plain SQL', () => { diff --git a/test/consuming-services.test.js b/test/consuming-services.test.js index 96d49f60..deb0e18d 100644 --- a/test/consuming-services.test.js +++ b/test/consuming-services.test.js @@ -1,31 +1,30 @@ -const cds = require('./cds') -const { expect } = cds.test ( - 'serve', 'AdminService', '--from', '@capire/bookshop,@capire/common', '--in-memory' -).in(__dirname) +const cds = require('@sap/cds/lib') -describe('Consuming Services locally', () => { - // - it('bootrapped the database successfully', ()=>{ +describe('cap/samples - Consuming Services locally', () => { + + const { expect } = cds.test ('@capire/bookshop') + + it('bootstrapped the database successfully', ()=>{ const { AdminService } = cds.services const { Authors } = AdminService.entities - expect(AdminService).not.to.be.undefined - expect(Authors).not.to.be.undefined + expect(AdminService).to.exist + expect(Authors).to.exist }) it('supports targets as strings or reflected defs', async () => { const AdminService = await cds.connect.to('AdminService') const { Authors } = AdminService.entities - const _ = expect (await AdminService.read(Authors)) + expect (await SELECT.from(Authors)) + // .to.eql(await SELECT.from('Authors')) + .to.eql(await AdminService.read(Authors)) .to.eql(await AdminService.read('Authors')) .to.eql(await AdminService.run(SELECT.from(Authors))) - // temporary workaround - if (cds.version >= '4.2.0') - _.to.eql(await AdminService.run(SELECT.from('Authors'))) + .to.eql(await AdminService.run(SELECT.from('Authors'))) }) it('allows reading from local services using cds.ql', async () => { const AdminService = await cds.connect.to('AdminService') - const query = SELECT.from('Authors', (a) => { + const authors = await AdminService.read (`Authors`, a => { a.name, a.books((b) => { b.title, @@ -34,15 +33,33 @@ describe('Consuming Services locally', () => { }) }) }).where(`name like`, 'E%') - // temporary workaround - if (cds.version < '4.2.0') - query.SELECT.from.ref[0] = 'AdminService.Authors' - const authors = await AdminService.run(query) + if (require('semver').gte(cds.version, '5.9.0')) { + expect(authors).to.containSubset([ + { + name: 'Emily Brontë', + books: [ + { + title: 'Wuthering Heights', + currency: { name: 'British Pound', symbol: '£' }, + }, + ], + }, + { + name: 'Edgar Allen Poe', + books: [ + { title: 'The Raven', currency: { name: 'US Dollar', symbol: '$' } }, + { title: 'Eleonora', currency: { name: 'US Dollar', symbol: '$' } }, + ], + }, + ]) + return + } expect(authors).to.containSubset([ { name: 'Emily Brontë', books: [ { + ID: 201, title: 'Wuthering Heights', currency: { name: 'British Pound', symbol: '£' }, }, @@ -51,8 +68,8 @@ describe('Consuming Services locally', () => { { name: 'Edgar Allen Poe', books: [ - { title: 'The Raven', currency: { name: 'US Dollar', symbol: '$' } }, - { title: 'Eleonora', currency: { name: 'US Dollar', symbol: '$' } }, + { ID: 251, title: 'The Raven', currency: { name: 'US Dollar', symbol: '$' } }, + { ID: 252, title: 'Eleonora', currency: { name: 'US Dollar', symbol: '$' } }, ], }, ]) diff --git a/test/custom-handlers.test.js b/test/custom-handlers.test.js index b2562644..5bd8acda 100644 --- a/test/custom-handlers.test.js +++ b/test/custom-handlers.test.js @@ -1,20 +1,16 @@ -const { GET, POST, expect } = require('./cds').test('bookshop').in(__dirname,'..') -const is_jest = !!global.test -if (is_jest) { // it's jest - global.before = (msg,fn) => global.beforeAll(fn||msg) - global.after = (msg,fn) => global.afterAll(fn||msg) -} +const cds = require('@sap/cds/lib') -describe('Custom Handlers', () => { +describe('cap/samples - Custom Handlers', () => { + + const { GET, POST, expect } = cds.test(__dirname+'/../bookshop') + beforeAll(()=>{ + cds.User.default = cds.User.Privileged // hard core monkey patch + }) it('should reject out-of-stock orders', async () => { - await expect( - Promise.all([ - POST('/browse/submitOrder', { book: 201, amount: 5 }), - POST('/browse/submitOrder', { book: 201, amount: 5 }), - POST('/browse/submitOrder', { book: 201, amount: 5 }), - ]) - ).to.be.rejectedWith(/409 - 5 exceeds stock for book #201/) + await POST `/browse/submitOrder ${{ book: 201, quantity: 5 }}` + await POST `/browse/submitOrder ${{ book: 201, quantity: 5 }}` + await expect(POST `/browse/submitOrder ${{ book: 201, quantity: 5 }}`).to.be.rejectedWith(/409 - 5 exceeds stock for book #201/) const { data } = await GET`/admin/Books/201/stock/$value` expect(data).to.equal(2) }) diff --git a/test/fiori.test.js b/test/fiori.test.js new file mode 100644 index 00000000..a48abc3c --- /dev/null +++ b/test/fiori.test.js @@ -0,0 +1,25 @@ +const cds = require('@sap/cds/lib') + +describe('cap/samples - Fiori APIs - v2', function() { + + const { GET, expect, axios } = cds.test ('@capire/fiori', '--with-mocks') + axios.defaults.auth = { username: 'alice', password: 'admin' } + + // if (this.timeout) this.timeout(1e6) + + it('serves $metadata documents in v2', async () => { + const { headers, data } = await GET `/v2/browse/$metadata` + expect(headers).to.contain({ + 'content-type': 'application/xml', + 'dataserviceversion': '2.0', + }) + expect(data).to.contain('') + }) + + it('serves Books in v2', async () => { + const { data } = await GET `/v2/browse/Books` + expect(data).to.containSubset({d:{results:[]}}) + expect(data.d.results.length).to.be.greaterThanOrEqual(5) + }) + +}) diff --git a/test/hello-world.test.js b/test/hello-world.test.js index d6d32974..30f3c5d8 100644 --- a/test/hello-world.test.js +++ b/test/hello-world.test.js @@ -1,7 +1,8 @@ -const cds = require ('./cds') -const { GET, expect } = cds.test('serve','hello/world.cds').in(__dirname,'..') +const cds = require('@sap/cds/lib') -describe('Hello world!', () => { +describe('cap/samples - Hello world!', () => { + + const { GET, expect } = cds.test (__dirname+'/../hello') it('should say hello with class impl', async () => { const {data} = await GET `/say/hello(to='world')` @@ -9,8 +10,7 @@ describe('Hello world!', () => { }) it('should say hello with another impl', async () => { - const cds = require ('@sap/cds') - cds.serve('say').from(cds.model) + await cds.serve('say').from(cds.model) .at('/say-again').in(cds.app) .with(srv => { srv.on('hello', (req) => `Hello again ${req.data.to}!`) diff --git a/test/hierarchical-data.test.js b/test/hierarchical-data.test.js index 1c8451cb..94741978 100644 --- a/test/hierarchical-data.test.js +++ b/test/hierarchical-data.test.js @@ -1,45 +1,53 @@ -const cwd = process.cwd(); process.chdir (__dirname) //> only for internal CI/CD@SAP -const cds = require ('./cds'), {expect} = cds.test +const cds = require('@sap/cds/lib') -// monkey patching older releases: -if (!cds.compile.cdl) cds.compile.cdl = cds.parse -const { parse:cdr } = cds.ql +describe('cap/samples - Hierarchical Data', ()=>{ -const model = cds.compile.cdl (` - entity Categories { - key ID : Integer; - name : String; - children : Composition of many Categories on children.parent = $self; - parent : Association to Categories; - } -`) -const {Categories:Cats} = model.definitions - - -describe('Hierarchical Data', ()=>{ + const model = CDL` + entity Categories { + key ID : Integer; + name : String; + children : Composition of many Categories on children.parent = $self; + parent : Association to Categories; + } + ` + const {Categories:Cats} = model.definitions + const {expect} = cds.test before ('bootstrap sqlite in-memory db...', async()=>{ await cds.deploy (model) .to ('sqlite::memory:') expect (cds.db) .to.exist - expect (cds.db.model) .to.exist + expect (cds.db.model) .to.exist }) - after(()=> process.chdir(cwd)) - it ('supports deeply nested inserts', ()=> INSERT.into (Cats, - { ID:100, name:'Some Cats...', children:[ - { ID:101, name:'Cat', children:[ - { ID:102, name:'Kitty', children:[ - { ID:103, name:'Kitty Cat', children:[ - { ID:104, name:'Aristocat' } ]}, - { ID:105, name:'Kitty Bat' } ]}, - { ID:106, name:'Catwoman', children:[ - { ID:107, name:'Catalina' } ]} ]}, - { ID:108, name:'Catweazle' } - ]} - )) + { ID:100, name:'Some Cats...', children:[ + { ID:101, name:'Cat', children:[ + { ID:102, name:'Kitty', children:[ + { ID:103, name:'Kitty Cat', children:[ + { ID:104, name:'Aristocat' } ]}, + { ID:105, name:'Kitty Bat' } ]}, + { ID:106, name:'Catwoman', children:[ + { ID:107, name:'Catalina' } ]} ]}, + { ID:108, name:'Catweazle' } + ]} + )) it ('supports nested reads', async()=>{ + if (require('semver').gte(cds.version, '5.9.0')) { + expect (await + SELECT.one.from (Cats, c=>{ + c.ID, c.name.as('parent'), c.children (c=>{ + c.name.as('child') + }) + }) .where ({name:'Cat'}) + ) .to.eql ( + { ID:101, parent:'Cat', children:[ + { child:'Kitty' }, + { child:'Catwoman' }, + ]} + ) + return + } expect (await SELECT.one.from (Cats, c=>{ c.ID, c.name.as('parent'), c.children (c=>{ @@ -55,6 +63,25 @@ describe('Hierarchical Data', ()=>{ }) it ('supports deeply nested reads', async()=>{ + if (require('semver').gte(cds.version, '5.9.0')) { + expect (await SELECT.one.from (Cats, c=>{ + c.ID, c.name, c.children ( + c => { c.name }, + {levels:3} + ) + }) .where ({name:'Cat'}) + ) .to.eql ( + { ID:101, name:'Cat', children:[ + { name:'Kitty', children:[ + { name:'Kitty Cat', children:[ + { name:'Aristocat' }, ]}, // level 3 + { name:'Kitty Bat', children:[] }, ]}, + { name:'Catwoman', children:[ + { name:'Catalina', children:[] } ]}, + ]} + ) + return + } expect (await SELECT.one.from (Cats, c=>{ c.ID, c.name, c.children ( c => { c.name }, @@ -74,16 +101,14 @@ describe('Hierarchical Data', ()=>{ }) it ('supports cascaded deletes', async()=>{ - const affectedRows = await DELETE.from (Cats) .where ({ID:[102,106]}) - expect (affectedRows) .to.equal (5) + const affectedRows = await DELETE.from (Cats) .where ({ID:[102,106]}) + expect (affectedRows) .to.be.greaterThan (0) const expected = [ - { ID:100, name:'Some Cats...' }, - { ID:101, name:'Cat' }, - { ID:104, name:'Aristocat' }, // REVISIT: Should be deleted as well? - { ID:108, name:'Catweazle' } + { ID:100, name:'Some Cats...' }, + { ID:101, name:'Cat' }, + { ID:108, name:'Catweazle' } ] - if (cdr) expect ( await SELECT.from(Cats) ).to.containSubset (expected) - else expect ( await SELECT.from(Cats) ).to.eql (expected) + expect ( await SELECT`ID,name`.from(Cats) ).to.eql (expected) }) }) diff --git a/test/localized-data.cds b/test/localized-data/services.cds similarity index 100% rename from test/localized-data.cds rename to test/localized-data/services.cds diff --git a/test/localized-data.test.js b/test/localized-data/services.test.js similarity index 78% rename from test/localized-data.test.js rename to test/localized-data/services.test.js index 4b345695..8ec30485 100644 --- a/test/localized-data.test.js +++ b/test/localized-data/services.test.js @@ -1,22 +1,16 @@ -const cds = require ('./cds') -const { GET, expect } = cds.test ('serve', __dirname+'/localized-data.cds', '--in-memory') +const cds = require('@sap/cds/lib') -describe('Localized Data', () => { +describe('cap/samples - Localized Data', () => { - it('serves localized $metadata documents', async () => { - const { data } = await GET`/browse/$metadata?sap-language=de` - expect(data).to.contain('') + const { GET, expect } = cds.test (__dirname) + beforeAll(()=>{ + cds.User.default = cds.User.Privileged // hard core monkey patch }) - it('supports sap-language param', async () => { - const { data } = await GET(`/browse/Books?$select=title,author` + '&sap-language=de') - expect(data.value).to.containSubset([ - { title: 'Sturmhöhe', author: 'Emily Brontë' }, - { title: 'Jane Eyre', author: 'Charlotte Brontë' }, - { title: 'The Raven', author: 'Edgar Allen Poe' }, - { title: 'Eleonora', author: 'Edgar Allen Poe' }, - { title: 'Catweazle', author: 'Richard Carpenter' }, - ]) + + it('serves localized $metadata documents', async () => { + const { data } = await GET(`/browse/$metadata?sap-language=de`, { headers: { 'accept-language': 'de' }}) + expect(data).to.contain('') }) it('supports accept-language header', async () => { @@ -41,7 +35,7 @@ describe('Localized Data', () => { { title: 'Jane Eyre', author: 'Charlotte Brontë', currency: { name: 'Pfund' } }, { title: 'The Raven', author: 'Edgar Allen Poe', currency: { name: 'US-Dollar' } }, { title: 'Eleonora', author: 'Edgar Allen Poe', currency: { name: 'US-Dollar' } }, - { title: 'Catweazle', author: 'Richard Carpenter', currency: { name: 'Euro' } }, + { title: 'Catweazle', author: 'Richard Carpenter', currency: { name: 'Yen' } }, ]) }) @@ -83,7 +77,7 @@ describe('Localized Data', () => { { title: 'Jane Eyre', currency: { name: 'British Pound' } }, { title: 'The Raven', currency: { name: 'US Dollar' } }, { title: 'Eleonora', currency: { name: 'US Dollar' } }, - { title: 'Catweazle', currency: { name: 'Euro' } }, + { title: 'Catweazle', currency: { name: 'Yen' } }, ]) }) }) diff --git a/test/messaging.test.js b/test/messaging.test.js index abc0d305..9e9ab66c 100644 --- a/test/messaging.test.js +++ b/test/messaging.test.js @@ -1,18 +1,17 @@ -const cwd = process.cwd(); process.chdir (__dirname) //> only for internal CI/CD@SAP -const cds = require ('./cds'), {expect} = cds.test -const _model = '@capire/reviews' -let messaging +const cds = require('@sap/cds/lib') +describe('cap/samples - Messaging', ()=>{ -describe('Messaging', ()=>{ - - beforeAll(async () => { - messaging = await cds.connect.to('messaging') + const { expect } = cds.test.in(__dirname,'..') + const _model = '@capire/reviews' + const Reviews = 'sap.capire.reviews.Reviews' + beforeAll(()=>{ + cds.User.default = cds.User.Privileged // hard core monkey patch }) - after(()=> process.chdir(cwd)) it ('should bootstrap sqlite in-memory db', async()=>{ const db = await cds.deploy (_model) .to ('sqlite::memory:') + await db.delete(Reviews) expect (db.model) .not.undefined }) @@ -24,15 +23,16 @@ describe('Messaging', ()=>{ let N=0, received=[], M=0 it ('should add messaging event handlers', ()=>{ - messaging.on('reviewed', (msg,next)=> { received.push(msg); return next() }) + srv.on('reviewed', (msg)=> received.push(msg)) }) it ('should add more messaging event handlers', ()=>{ - messaging.on('reviewed', (_,next)=> { ++M; return next() }) + srv.on('reviewed', ()=> ++M) }) it ('should add review', async ()=>{ const review = { subject: "201", title: "Captivating", rating: ++N } + cds._debug = 1 const response = await srv.create ('Reviews') .entries (review) expect (response) .to.containSubset (review) }) @@ -46,16 +46,16 @@ describe('Messaging', ()=>{ // { ID: 111 + (++N), subject: "201", title: "Captivating", rating: N }, // ), srv.create ('Reviews') .entries ( - { ID: 111 + (++N), subject: "201", title: "Captivating", rating: N } + { ID: String(111 + (++N)), subject: "201", title: "Captivating", rating: N } ), srv.create ('Reviews') .entries ( - { ID: 111 + (++N), subject: "201", title: "Captivating", rating: N } + { ID: String(111 + (++N)), subject: "201", title: "Captivating", rating: N } ), srv.create ('Reviews') .entries ( - { ID: 111 + (++N), subject: "201", title: "Captivating", rating: N } + { ID: String(111 + (++N)), subject: "201", title: "Captivating", rating: N } ), srv.create ('Reviews') .entries ( - { ID: 111 + (++N), subject: "201", title: "Captivating", rating: N } + { ID: String(111 + (++N)), subject: "201", title: "Captivating", rating: N } ), ])) @@ -64,11 +64,11 @@ describe('Messaging', ()=>{ expect(M).equals(N) expect(received.length).equals(N) expect(received.map(m=>m.data)).to.deep.equal([ - { subject: '201', rating: 1 }, - { subject: '201', rating: 1.5 }, - { subject: '201', rating: 2 }, - { subject: '201', rating: 2.5 }, - { subject: '201', rating: 3 }, + { count: 1, subject: '201', rating: 1 }, + { count: 2, subject: '201', rating: 1.5 }, + { count: 3, subject: '201', rating: 2 }, + { count: 4, subject: '201', rating: 2.5 }, + { count: 5, subject: '201', rating: 3 }, ]) }) }) diff --git a/test/odata.test.js b/test/odata.test.js index ca89a20d..73ac0ff4 100644 --- a/test/odata.test.js +++ b/test/odata.test.js @@ -1,9 +1,11 @@ -const { GET, expect } = require('./cds').test('bookshop').in(__dirname,'..') +const cds = require('@sap/cds/lib') -describe('OData Protocol', () => { +describe('cap/samples - Bookshop APIs', () => { + const { GET, expect, axios } = cds.test ('@capire/bookshop') + axios.defaults.auth = { username: 'alice', password: 'admin' } it('serves $metadata documents in v4', async () => { - const { headers, status, data } = await GET`/browse/$metadata` + const { headers, status, data } = await GET `/browse/$metadata` expect(status).to.equal(200) expect(headers).to.contain({ 'content-type': 'application/xml', @@ -13,10 +15,23 @@ describe('OData Protocol', () => { expect(data).to.contain('') }) + it('serves ListOfBooks?$expand=genre,currency', async () => { + const Mystery = { ID: 16, name: 'Mystery', descr: null, parent_ID: 10 } + const Romance = { ID: 15, name: 'Romance', descr: null, parent_ID: 10 } + const USD = { code: 'USD', name: 'US Dollar', descr: null, symbol: '$' } + const { data } = await GET `/browse/ListOfBooks ${{ + params: { $search: 'Po', $select: `title,author`, $expand:`genre,currency` }, + }}` + expect(data.value).to.eql([ + { ID: 251, title: 'The Raven', author: 'Edgar Allen Poe', genre:Mystery, currency:USD }, + { ID: 252, title: 'Eleonora', author: 'Edgar Allen Poe', genre:Romance, currency:USD }, + ]) + }) + it('supports $search in multiple fields', async () => { - const { data } = await GET(`/browse/Books`, { + const { data } = await GET `/browse/Books ${{ params: { $search: 'Po', $select: `title,author` }, - }) + }}` expect(data.value).to.eql([ { ID: 201, title: 'Wuthering Heights', author: 'Emily Brontë' }, { ID: 207, title: 'Jane Eyre', author: 'Charlotte Brontë' }, @@ -71,4 +86,12 @@ describe('OData Protocol', () => { { ID: 271, title: 'Catweazle' }, ]) }) + + it('serves user info', async () => { + const { data: alice } = await GET `/user/me` + expect(alice).to.containSubset({ id: 'alice', locale:'en' }) + const { data: joe } = await GET (`/user/me`, {auth: { username: 'joe' }}) + expect(joe).to.containSubset({ id: 'joe', locale:'en' }) + }) + })