cap/samples reloaded
- cleaned up set of samples - added new showcases, e.g. draft of localized data - removed lerna
This commit is contained in:
18
.vscode/extensions.json
vendored
Normal file
18
.vscode/extensions.json
vendored
Normal file
@@ -0,0 +1,18 @@
|
||||
{
|
||||
// See https://go.microsoft.com/fwlink/?LinkId=827846 to learn about workspace recommendations.
|
||||
// Extension identifier format: ${publisher}.${name}. Example: vscode.csharp
|
||||
|
||||
// List of extensions which should be recommended for users of this workspace.
|
||||
"recommendations": [
|
||||
// "CDS Editor !",
|
||||
"dbaeumer.vscode-eslint",
|
||||
"esbenp.prettier-vscode",
|
||||
"mechatroner.rainbow-csv",
|
||||
"humao.rest-client",
|
||||
"alexcvzz.vscode-sqlite"
|
||||
],
|
||||
// List of extensions recommended by VS Code that should not be recommended for users of this workspace.
|
||||
"unwantedRecommendations": [
|
||||
|
||||
]
|
||||
}
|
||||
22
.vscode/launch.json
vendored
22
.vscode/launch.json
vendored
@@ -5,16 +5,9 @@
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
{
|
||||
"name": "bookshop", "request": "launch", "type": "node", "runtimeExecutable": "npx", "runtimeArgs": [ "-n" ],
|
||||
"args": [ "--", "cds", "run", "--in-memory" ],
|
||||
"cwd": "${workspaceFolder}/packages/bookshop",
|
||||
"console": "integratedTerminal",
|
||||
"skipFiles": ["<node_internals>/**"]
|
||||
},
|
||||
{
|
||||
"name": "cds run ...", "request": "launch", "type": "node", "runtimeExecutable": "npx", "runtimeArgs": [ "-n" ],
|
||||
"name": "cds run ...", "cwd": "${workspaceFolder}/${input:sample}",
|
||||
"request": "launch", "type": "node", "runtimeExecutable": "npx", "runtimeArgs": [ "-n" ],
|
||||
"args": [ "--", "cds", "run", "--with-mocks", "--in-memory?" ],
|
||||
"cwd": "${workspaceFolder}/packages/${input:service}",
|
||||
"console": "integratedTerminal",
|
||||
"skipFiles": ["<node_internals>/**"]
|
||||
}
|
||||
@@ -22,14 +15,13 @@
|
||||
"inputs": [
|
||||
{
|
||||
"type": "pickString",
|
||||
"id": "service",
|
||||
"description": "Which service do you want to start?",
|
||||
"id": "sample",
|
||||
"description": "Which sample do you want to start?",
|
||||
"options": [
|
||||
"bookshop",
|
||||
"bookstore",
|
||||
"media-server",
|
||||
"office-supplies",
|
||||
"reviews-service"
|
||||
"fiori",
|
||||
"reviews",
|
||||
"reviews/test/bookshop"
|
||||
],
|
||||
"default": "bookshop"
|
||||
}
|
||||
|
||||
17
.vscode/tasks.json
vendored
17
.vscode/tasks.json
vendored
@@ -1,17 +0,0 @@
|
||||
{
|
||||
// See https://go.microsoft.com/fwlink/?LinkId=733558
|
||||
// for the documentation about the tasks.json format
|
||||
"version": "2.0.0",
|
||||
"tasks": [
|
||||
{
|
||||
"type": "npm", "script": "watch", "path": "packages/bookshop/",
|
||||
"options": { "env": { "PORT": "4004" }},
|
||||
"presentation": { "group": "A" }
|
||||
},
|
||||
{
|
||||
"type": "npm", "script": "watch", "path": "packages/reviews-service/",
|
||||
"options": { "env": { "PORT": "5005" }},
|
||||
"presentation": { "group": "A" }
|
||||
}
|
||||
]
|
||||
}
|
||||
1
NOTICE
1
NOTICE
@@ -1 +0,0 @@
|
||||
Copyright (c) 2019 SAP SE or an SAP affiliate company. All rights reserved.
|
||||
78
README.md
78
README.md
@@ -1,71 +1,49 @@
|
||||
# cloud-cap-samples
|
||||
# Welcome to cap/samples
|
||||
|
||||
This is a monorepository for sample projects on [SAP Cloud Application Programming Model](https://cap.cloud.sap).
|
||||
|
||||
## Description
|
||||
|
||||
This repository provides a list of samples and reusable packages created based on SAP Cloud Application Programming Model.
|
||||
The SAP Cloud Application Programming Model enables you to quickly create business applications by allowing you to focus on your domain logic. It offers a consistent end-to-end programming model that includes languages, libraries and APIs tailored for full-stack development on SAP Cloud Platform.
|
||||
|
||||
The samples provided can be run in a local setup on SQLite Database.
|
||||
Find here a collection of samples for the [SAP Cloud Application Programming Model](https://cap.cloud.sap) organised in a simplistic [monorepo setup](samples.md#all-in-one-monorepo). → See [**Overview** of contained samples](samples.md)
|
||||
|
||||
|
||||
## Requirements
|
||||
* [Node.js](https://nodejs.org/en/) v8 or higher
|
||||
* [Git](https://git-scm.com)
|
||||
* [SQLite DB](https://www.sqlite.org/download.html) (Windows only; pre-installed on Mac/Linux)
|
||||
## Preliminaries
|
||||
|
||||
#### Optional (if you want to import the code into an editor)
|
||||
* [VS Code](https://code.visualstudio.com)
|
||||
* [Add CDS extension to VS](https://cap.cloud.sap/docs/get-started/in-vscode#add-cds-editor)
|
||||
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)
|
||||
|
||||
## Download and Installation
|
||||
|
||||
#### Install `cds` development kit
|
||||
## 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).
|
||||
|
||||
```sh
|
||||
# `@sap`-scoped packages are set via .npmrc
|
||||
npm install -g @sap/cds-dk
|
||||
cds #> test-run it
|
||||
# git clone https://github.com/sap-samples/cloud-cap-samples samples
|
||||
git clone https://github.com/SAP-samples/cloud-cap-samples -b cap-samples-reloaded samples
|
||||
cd samples
|
||||
```
|
||||
Got issues? Check out the [documentation](https://cap.cloud.sap/docs/get-started/).
|
||||
|
||||
#### Clone and build the application
|
||||
`git clone https://github.com/SAP-samples/cloud-cap-samples samples && cd samples && npm i`
|
||||
## Setup
|
||||
|
||||
#### Run the samples
|
||||
In the samples folder run:
|
||||
```sh
|
||||
npm install
|
||||
```
|
||||
|
||||
With that you're ready to run the samples, e.g. start the [_bookshop_](./packages/bookshop) sample as follows:
|
||||
## Run
|
||||
|
||||
`npm run bookshop`
|
||||
With that you're ready to run the samples, for example:
|
||||
```sh
|
||||
cd bookshop
|
||||
cds watch
|
||||
```
|
||||
|
||||
## Test
|
||||
|
||||
For example, try these links in your browser:
|
||||
- <http://localhost:4004> to test with generic index page.
|
||||
- <http://localhost:4004/fiori.html> to test with Fiori sandbox.
|
||||
After that open this link in your browser: <http://localhost:4004>
|
||||
|
||||
|
||||
## Debug
|
||||
## Get Support
|
||||
|
||||
For example, in [VS Code](https://code.visualstudio.com) switch to _Debug_ view and launch one of the prepared _cds run_ launch configurations.
|
||||
Check out the cap docs at https://cap.cloud.sap. <br>
|
||||
In case you find a bug or need support, please [open an issue in here](https://github.com/SAP-samples/cloud-cap-samples/issues/new).
|
||||
|
||||
|
||||
## Limitations
|
||||
|
||||
None
|
||||
|
||||
## Known Issues
|
||||
|
||||
None
|
||||
|
||||
## How to obtain support
|
||||
|
||||
Check out the documentation on https://cap.cloud.sap. In case you find a bug, or you need additional support, please open an issue [here](https://github.com/SAP-samples/cloud-cap-samples/issues/new) in GitHub.
|
||||
|
||||
## To-Do (upcoming changes)
|
||||
|
||||
None
|
||||
|
||||
## License
|
||||
|
||||
Copyright (c) 2019 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under SAP Sample Code License Agreement, except as noted otherwise in the [LICENSE](/LICENSE) file.
|
||||
|
||||
16
bookshop/db/data/sap.capire.bookshop-Genres.csv
Normal file
16
bookshop/db/data/sap.capire.bookshop-Genres.csv
Normal file
@@ -0,0 +1,16 @@
|
||||
ID;parent_ID;name
|
||||
10;;Fiction
|
||||
11;10;Drama
|
||||
12;10;Poetry
|
||||
13;10;Fantasy
|
||||
14;10;Science Fiction
|
||||
15;10;Romance
|
||||
16;10;Mystery
|
||||
17;10;Thriller
|
||||
18;10;Dystopia
|
||||
19;10;Fairy Tale
|
||||
20;;Non-Fiction
|
||||
21;20;Biography
|
||||
22;20;Autobiography
|
||||
23;20;Essay
|
||||
24;20;Speech
|
||||
|
@@ -1,11 +1,13 @@
|
||||
namespace sap.capire.bookshop;
|
||||
using { Currency, managed, cuid } from '@sap/cds/common';
|
||||
using { Currency, managed, sap } from '@sap/cds/common';
|
||||
// using { Currency, managed, sap } from '@capire/commorn';
|
||||
|
||||
entity Books : managed {
|
||||
key ID : Integer;
|
||||
title : localized String(111);
|
||||
descr : localized String(1111);
|
||||
author : Association to Authors;
|
||||
genre : Association to Genres;
|
||||
stock : Integer;
|
||||
price : Decimal(9,2);
|
||||
currency : Currency;
|
||||
@@ -21,15 +23,8 @@ entity Authors : managed {
|
||||
books : Association to many Books on books.author = $self;
|
||||
}
|
||||
|
||||
entity Orders : cuid, managed {
|
||||
OrderNo : String @title:'Order Number'; //> readable key
|
||||
Items : Composition of many OrderItems on Items.parent = $self;
|
||||
total : Decimal(9,2) @readonly;
|
||||
currency : Currency;
|
||||
}
|
||||
entity OrderItems : cuid {
|
||||
parent : Association to Orders;
|
||||
book : Association to Books;
|
||||
amount : Integer;
|
||||
netAmount : Decimal(9,2);
|
||||
entity Genres : sap.common.CodeList {
|
||||
key ID : Integer;
|
||||
parent : Association to Genres;
|
||||
children : Composition of many Genres on children.parent = $self;
|
||||
}
|
||||
@@ -1,2 +1,3 @@
|
||||
using from './db/schema';
|
||||
using from './srv/cat-service';
|
||||
using from './srv/admin-service';
|
||||
1
bookshop/index.js
Normal file
1
bookshop/index.js
Normal file
@@ -0,0 +1 @@
|
||||
exports.CatalogService = require('./srv/cat-service')
|
||||
21
bookshop/package.json
Normal file
21
bookshop/package.json
Normal file
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"name": "@capire/bookshop",
|
||||
"version": "1.0.0",
|
||||
"description": "A simple self-contained bookshop service.",
|
||||
"dependencies": {
|
||||
"@sap/cds": "^3.31.1",
|
||||
"express": "^4.17.1"
|
||||
},
|
||||
"scripts": {
|
||||
"genres": "cds serve test/genres.cds",
|
||||
"start": "cds run",
|
||||
"watch": "cds watch"
|
||||
},
|
||||
"cds": {
|
||||
"requires": {
|
||||
"db": {
|
||||
"kind": "sql"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
31
bookshop/readme.md
Normal file
31
bookshop/readme.md
Normal file
@@ -0,0 +1,31 @@
|
||||
# Bookshop Getting Started Sample
|
||||
|
||||
This stand-alone sample introduces the essential tasks in the development of CAP-based services as also covered in the [Getting Started guide in capire](https://cap.cloud.sap/docs/get-started/in-a-nutshell).
|
||||
|
||||
## Hypothetical Use Cases
|
||||
|
||||
1. Build a service that allows to browse _Books_ and _Authors_.
|
||||
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)
|
||||
|
||||
## Running the Sample
|
||||
|
||||
```sh
|
||||
npm run watch
|
||||
```
|
||||
|
||||
## Content & Best Practices
|
||||
|
||||
| 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/generic-providers) | 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](https://cap.cloud.sap/docs/guides/testing) | [`./test`](./test) |
|
||||
| [Sharing for Reuse](https://cap.cloud.sap/docs/get-started/projects#sharing-and-reusing-content) | [`./index.cds`](./index.cds) |
|
||||
@@ -3,5 +3,4 @@ using { sap.capire.bookshop as my } from '../db/schema';
|
||||
service AdminService @(_requires:'authenticated-user') {
|
||||
entity Books as projection on my.Books;
|
||||
entity Authors as projection on my.Authors;
|
||||
entity Orders as select from my.Orders;
|
||||
}
|
||||
@@ -1,13 +1,12 @@
|
||||
using { sap.capire.bookshop as my } from '../db/schema';
|
||||
|
||||
@path:'/browse'
|
||||
service CatalogService {
|
||||
service CatalogService @(path:'/browse') {
|
||||
|
||||
@readonly entity Books as SELECT from my.Books {*,
|
||||
author.name as author
|
||||
} excluding { createdBy, modifiedBy };
|
||||
|
||||
@requires_: 'authenticated-user'
|
||||
@insertonly entity Orders as projection on my.Orders;
|
||||
action order (book : Books.ID, amount: Integer);
|
||||
|
||||
}
|
||||
23
bookshop/srv/cat-service.js
Normal file
23
bookshop/srv/cat-service.js
Normal file
@@ -0,0 +1,23 @@
|
||||
const cds = require('@sap/cds')
|
||||
|
||||
/** Service implementation for CatalogService */
|
||||
module.exports = cds.service.impl (function() {
|
||||
|
||||
// Get entity definitions from reflected model
|
||||
const { Books } = cds.entities
|
||||
|
||||
// Add some discount for overstocked books
|
||||
this.after ('READ', 'Books', each => {
|
||||
if (each.stock > 111) each.title += ` -- 11% discount!`
|
||||
})
|
||||
|
||||
// Reduce stock of ordered books if available stock suffices
|
||||
this.on ('order', async (req) => {
|
||||
const {UPDATE} = cds.ql(req), {book,amount} = req.data
|
||||
const n = await UPDATE (Books, book)
|
||||
.where ('stock >=', amount)
|
||||
.set ('stock -=', amount)
|
||||
n > 0 || req.error (409,`${amount} exceeds stock for book #${book}`)
|
||||
})
|
||||
|
||||
})
|
||||
4
bookshop/test/genres.cds
Normal file
4
bookshop/test/genres.cds
Normal file
@@ -0,0 +1,4 @@
|
||||
using { sap.capire.bookshop as my } from '../db/schema';
|
||||
service TestService {
|
||||
entity Genres as projection on my.Genres;
|
||||
}
|
||||
@@ -3,10 +3,15 @@
|
||||
# Genres
|
||||
#
|
||||
|
||||
GET http://localhost:4004/admin/Genres?
|
||||
GET http://localhost:4004/test/Genres?
|
||||
###
|
||||
|
||||
POST http://localhost:4004/admin/Genres?
|
||||
GET http://localhost:4004/test/Genres?
|
||||
&$filter=parent_ID eq null&$select=name
|
||||
&$expand=children($select=name)
|
||||
###
|
||||
|
||||
POST http://localhost:4004/test/Genres?
|
||||
Content-Type: application/json
|
||||
|
||||
{ "ID":100, "name":"Some Sample Genres...", "children":[
|
||||
@@ -21,13 +26,13 @@ Content-Type: application/json
|
||||
]}
|
||||
###
|
||||
|
||||
GET http://localhost:4004/admin/Genres(100)?
|
||||
GET http://localhost:4004/test/Genres(100)?
|
||||
# &$expand=children
|
||||
# &$expand=children($expand=children($expand=children($expand=children)))
|
||||
###
|
||||
|
||||
DELETE http://localhost:4004/admin/Genres(103)
|
||||
DELETE http://localhost:4004/test/Genres(103)
|
||||
###
|
||||
|
||||
DELETE http://localhost:4004/admin/Genres(100)
|
||||
DELETE http://localhost:4004/test/Genres(100)
|
||||
###
|
||||
@@ -1,16 +1,18 @@
|
||||
const cds = require ('@sap/cds')
|
||||
const {expect} = cds.require.chai
|
||||
|
||||
describe('reading/writing hierarchies', ()=>{
|
||||
|
||||
it ('should prepare to sqlite in-memory', async()=>{
|
||||
it ('should bootstrap sqlite in-memory db', async()=>{
|
||||
await cds.deploy (__dirname+'/../db') .to ('sqlite::memory:')
|
||||
expect (cds.model) .toBeDefined()
|
||||
expect (cds.db) .to.exist
|
||||
expect (cds.db.model) .to.exist
|
||||
})
|
||||
|
||||
it ('should insert hierarchy of categories', ()=>{
|
||||
const { Categories } = cds.entities
|
||||
return INSERT.into (Categories) .entries (
|
||||
{ ID:100, name:'Some Sample Categories...', children:[
|
||||
it ('should insert hierarchy of genres', ()=>{
|
||||
const { Genres } = cds.entities
|
||||
return INSERT.into (Genres) .entries (
|
||||
{ ID:100, name:'Some Sample Genres...', children:[
|
||||
{ ID:101, name:'Cat', children:[
|
||||
{ ID:102, name:'Kitty', children:[
|
||||
{ ID:103, name:'Kitty Cat', children:[
|
||||
@@ -23,17 +25,17 @@ describe('reading/writing hierarchies', ()=>{
|
||||
)
|
||||
})
|
||||
|
||||
it ('should read categories with children', async()=>{
|
||||
const { Categories } = cds.entities
|
||||
it ('should read genres with children', async()=>{
|
||||
const { Genres } = cds.entities
|
||||
expect (await
|
||||
|
||||
SELECT.one.from (Categories, c=>{
|
||||
SELECT.one.from (Genres, c=>{
|
||||
c.ID, c.name.as('parent'), c.children (c=>{
|
||||
c.name.as('child')
|
||||
})
|
||||
}) .where ({name:'Cat'})
|
||||
|
||||
) .toMatchObject (
|
||||
) .to.containSubset (
|
||||
|
||||
{ ID:101, parent:'Cat', children:[
|
||||
{ child:'Kitty' },
|
||||
@@ -43,15 +45,15 @@ describe('reading/writing hierarchies', ()=>{
|
||||
)
|
||||
})
|
||||
|
||||
it ('should read hierarchy of categories', async()=>{
|
||||
const { Categories } = cds.entities
|
||||
it ('should read hierarchy of genres', async()=>{
|
||||
const { Genres } = cds.entities
|
||||
expect (await
|
||||
|
||||
SELECT.one.from (Categories, c=>{
|
||||
SELECT.one.from (Genres, c=>{
|
||||
c.ID, c.name, c.children (c=>{ c.name },{levels:3})
|
||||
}) .where ({name:'Cat'})
|
||||
|
||||
) .toMatchObject (
|
||||
) .to.containSubset (
|
||||
|
||||
{ ID:101, name:'Cat', children:[
|
||||
{ name:'Kitty', children:[
|
||||
40
bookshop/test/requests.http
Normal file
40
bookshop/test/requests.http
Normal file
@@ -0,0 +1,40 @@
|
||||
GET http://localhost:4004/browse
|
||||
###
|
||||
|
||||
GET http://localhost:4004/browse/$metadata
|
||||
###
|
||||
|
||||
|
||||
GET http://localhost:4004/browse/Books?
|
||||
&$select=title,stock
|
||||
&$expand=currency
|
||||
#> add @capire/common to see data for currencies
|
||||
# &sap-language=de
|
||||
###
|
||||
|
||||
|
||||
GET http://localhost:4004/admin/Authors?
|
||||
# &$select=name,dateOfBirth,placeOfBirth
|
||||
&$expand=books($select=title;$expand=currency)
|
||||
#> add @capire/common to see data for currencies
|
||||
# &$filter=ID eq 101
|
||||
&sap-language=de
|
||||
###
|
||||
|
||||
|
||||
POST http://localhost:4004/browse/order
|
||||
# Run that three times to get out-of-stock message
|
||||
Content-Type: application/json
|
||||
|
||||
{ "book":201, "amount":5 }
|
||||
###
|
||||
|
||||
|
||||
|
||||
GET http://localhost:4004/browse/Genres?
|
||||
###
|
||||
|
||||
GET http://localhost:4004/browse/Genres?
|
||||
&$filter=parent_ID eq null&$select=name
|
||||
&$expand=children($select=name)
|
||||
###
|
||||
5
common/data/sap.common-Languages.csv
Normal file
5
common/data/sap.common-Languages.csv
Normal file
@@ -0,0 +1,5 @@
|
||||
code;name
|
||||
de;German
|
||||
fr;French
|
||||
en;English
|
||||
en_GB;British English
|
||||
|
10
common/data/sap.common-Languages_texts.csv
Normal file
10
common/data/sap.common-Languages_texts.csv
Normal file
@@ -0,0 +1,10 @@
|
||||
code;locale;name
|
||||
de;en;German
|
||||
de;de;Deutsch
|
||||
de;fr;Allemande
|
||||
fr;en;French
|
||||
fr;de;Französisch
|
||||
fr;fr;Francais
|
||||
en;en;English
|
||||
en;de;Englisch
|
||||
en;fr;Anglais
|
||||
|
45
common/index.cds
Normal file
45
common/index.cds
Normal file
@@ -0,0 +1,45 @@
|
||||
using { sap } from '@sap/cds/common';
|
||||
|
||||
extend sap.common.Currencies with {
|
||||
// Currencies.code = ISO 4217 alphabetic three-letter code
|
||||
// with the first two letters being equal to ISO 3166 alphabetic country codes
|
||||
// See also:
|
||||
// [1] https://www.iso.org/iso-4217-currency-codes.html
|
||||
// [2] https://www.currency-iso.org/en/home/tables/table-a1.html
|
||||
// [3] https://www.ibm.com/support/knowledgecenter/en/SSZLC2_7.0.0/com.ibm.commerce.payments.developer.doc/refs/rpylerl2mst97.htm
|
||||
numcode : Integer;
|
||||
exponent : Integer; //> e.g. 2 --> 1 Dollar = 10^2 Cent
|
||||
minor : String; //> e.g. 'Cent'
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* The Code Lists below are designed as optional extensions to
|
||||
* the base schema. Switch them on by adding an Association to
|
||||
* one of the code list entities in your models or by:
|
||||
* annotate sap.common.Countries with @cds.persistence.skip:false;
|
||||
*/
|
||||
|
||||
context sap.common_countries {
|
||||
|
||||
extend sap.common.Countries {
|
||||
regions : Composition of many Regions on regions._parent = $self.code;
|
||||
}
|
||||
|
||||
entity Regions : sap.common.CodeList {
|
||||
key code : String(5); // ISO 3166-2 alpha5 codes, e.g. DE-BW
|
||||
children : Composition of many Regions on children._parent = $self.code;
|
||||
cities : Composition of many Cities on cities.region = $self;
|
||||
_parent : String(11);
|
||||
}
|
||||
entity Cities : sap.common.CodeList {
|
||||
key code : String(11);
|
||||
region : Association to Regions;
|
||||
districts : Composition of many Districts on districts.city = $self;
|
||||
}
|
||||
entity Districts : sap.common.CodeList {
|
||||
key code : String(11);
|
||||
city : Association to Cities;
|
||||
}
|
||||
|
||||
}
|
||||
4
common/package.json
Normal file
4
common/package.json
Normal file
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"name": "@capire/common",
|
||||
"version": "1.0.0"
|
||||
}
|
||||
72
fiori/app/admin/fiori-service.cds
Normal file
72
fiori/app/admin/fiori-service.cds
Normal file
@@ -0,0 +1,72 @@
|
||||
using AdminService from '@capire/bookshop';
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
// Books Object Page
|
||||
//
|
||||
|
||||
annotate AdminService.Books with @(
|
||||
UI: {
|
||||
Facets: [
|
||||
{$Type: 'UI.ReferenceFacet', Label: '{i18n>General}', Target: '@UI.FieldGroup#General'},
|
||||
{$Type: 'UI.ReferenceFacet', Label: '{i18n>Translations}', Target: 'texts/@UI.LineItem'},
|
||||
{$Type: 'UI.ReferenceFacet', Label: '{i18n>Details}', Target: '@UI.FieldGroup#Details'},
|
||||
{$Type: 'UI.ReferenceFacet', Label: '{i18n>Admin}', Target: '@UI.FieldGroup#Admin'},
|
||||
],
|
||||
FieldGroup#General: {
|
||||
Data: [
|
||||
{Value: title},
|
||||
{Value: author_ID},
|
||||
{Value: genre_ID},
|
||||
{Value: descr},
|
||||
]
|
||||
},
|
||||
FieldGroup#Details: {
|
||||
Data: [
|
||||
{Value: stock},
|
||||
{Value: price},
|
||||
{Value: currency_code, Label: '{i18n>Currency}'},
|
||||
]
|
||||
},
|
||||
FieldGroup#Admin: {
|
||||
Data: [
|
||||
{Value: createdBy},
|
||||
{Value: createdAt},
|
||||
{Value: modifiedBy},
|
||||
{Value: modifiedAt}
|
||||
]
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
|
||||
|
||||
////////////////////////////////////////////////////////////
|
||||
//
|
||||
// Draft for Localized Data
|
||||
//
|
||||
|
||||
annotate sap.capire.bookshop.Books with @fiori.draft.enabled;
|
||||
annotate AdminService.Books with @odata.draft.enabled;
|
||||
|
||||
annotate AdminService.Books_texts with @(
|
||||
UI: {
|
||||
Identification: [{Value:title}],
|
||||
SelectionFields: [ locale, title ],
|
||||
LineItem: [
|
||||
{Value: locale, Label: 'Locale'},
|
||||
{Value: title, Label: 'Title'},
|
||||
{Value: descr, Label: 'Description'},
|
||||
]
|
||||
}
|
||||
);
|
||||
|
||||
// Add Value Help for Locales
|
||||
annotate AdminService.Books_texts {
|
||||
locale @ValueList:{entity:'Languages',type:#fixed}
|
||||
}
|
||||
// In addition we need to expose Languages through AdminService
|
||||
using { sap } from '@sap/cds/common';
|
||||
extend service AdminService {
|
||||
entity Languages as projection on sap.common.Languages;
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
using CatalogService from '../../srv/cat-service';
|
||||
using CatalogService from '@capire/bookshop';
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
@@ -40,6 +40,7 @@ annotate CatalogService.Books with @(
|
||||
LineItem: [
|
||||
{Value: title},
|
||||
{Value: author, Label:'{i18n>Author}'},
|
||||
{Value: genre.name},
|
||||
{Value: price},
|
||||
{Value: currency.symbol, Label:' '},
|
||||
]
|
||||
@@ -2,7 +2,7 @@
|
||||
Common Annotations shared by all apps
|
||||
*/
|
||||
|
||||
using { sap.capire.bookshop as my } from '../db/schema';
|
||||
using { sap.capire.bookshop as my } from '@capire/bookshop';
|
||||
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////
|
||||
@@ -17,6 +17,7 @@ annotate my.Books with @(
|
||||
{Value: ID},
|
||||
{Value: title},
|
||||
{Value: author.name, Label:'{i18n>Author}'},
|
||||
{Value: genre.name},
|
||||
{Value: stock},
|
||||
{Value: price},
|
||||
{Value: currency.symbol, Label:' '},
|
||||
@@ -57,12 +58,16 @@ annotate my.Books with @(
|
||||
annotate my.Books with {
|
||||
ID @title:'{i18n>ID}' @UI.HiddenFilter;
|
||||
title @title:'{i18n>Title}';
|
||||
genre @title:'{i18n>Genre}';
|
||||
author @title:'{i18n>AuthorID}';
|
||||
price @title:'{i18n>Price}';
|
||||
stock @title:'{i18n>Stock}';
|
||||
descr @UI.MultiLineText;
|
||||
}
|
||||
|
||||
annotate my.Genres with {
|
||||
name @title: '{i18n>Genre}';
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
@@ -28,7 +28,7 @@
|
||||
navigationMode: "embedded"
|
||||
},
|
||||
"manage-orders": {
|
||||
title: "Manage Orders",
|
||||
title: "Order Books",
|
||||
description: "... testing FE v42",
|
||||
additionalInformation: "SAPUI5.Component=orders",
|
||||
applicationType : "URL",
|
||||
@@ -6,3 +6,5 @@ using from './admin/fiori-service';
|
||||
using from './browse/fiori-service';
|
||||
using from './orders/fiori-service';
|
||||
using from './common';
|
||||
|
||||
using from '@capire/common';
|
||||
@@ -1,13 +1,15 @@
|
||||
using AdminService from '../../srv/admin-service';
|
||||
using OrdersService from '@capire/orders/srv/orders-service';
|
||||
|
||||
annotate AdminService.Books with {
|
||||
annotate OrdersService.Books with {
|
||||
price @Common.FieldControl: #ReadOnly;
|
||||
}
|
||||
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
// Common
|
||||
//
|
||||
annotate AdminService.OrderItems with {
|
||||
annotate OrdersService.OrderItems with {
|
||||
book @(
|
||||
Common: {
|
||||
Text: book.title,
|
||||
@@ -22,7 +24,7 @@ annotate AdminService.OrderItems with {
|
||||
|
||||
|
||||
@odata.draft.enabled
|
||||
annotate AdminService.Orders with @(
|
||||
annotate OrdersService.Orders with @(
|
||||
UI: {
|
||||
////////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
@@ -83,9 +85,9 @@ annotate AdminService.Orders with @(
|
||||
|
||||
|
||||
|
||||
//The enity types name is AdminService.my_bookshop_OrderItems
|
||||
//The enity types name is OrdersService.my_bookshop_OrderItems
|
||||
//The annotations below are not generated in edmx WHY?
|
||||
annotate AdminService.OrderItems with @(
|
||||
annotate OrdersService.OrderItems with @(
|
||||
UI: {
|
||||
HeaderInfo: {
|
||||
TypeName: 'Order Item', TypeNamePlural: ' ',
|
||||
@@ -3,12 +3,12 @@
|
||||
"sap.app": {
|
||||
"id": "orders",
|
||||
"type": "application",
|
||||
"title": "Manage Orders",
|
||||
"title": "Order Books",
|
||||
"description": "Sample Application",
|
||||
"i18n": "i18n/i18n.properties",
|
||||
"dataSources": {
|
||||
"AdminService": {
|
||||
"uri": "/admin/",
|
||||
"OrdersService": {
|
||||
"uri": "/orders/",
|
||||
"type": "OData",
|
||||
"settings": {
|
||||
"odataVersion": "4.0"
|
||||
@@ -33,7 +33,7 @@
|
||||
"uri": "i18n/i18n.properties"
|
||||
},
|
||||
"": {
|
||||
"dataSource": "AdminService",
|
||||
"dataSource": "OrdersService",
|
||||
"settings": {
|
||||
"synchronizationMode": "None",
|
||||
"operationMode": "Server",
|
||||
@@ -140,7 +140,7 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"AuthorsDetails": {
|
||||
"type": "Component",
|
||||
3
fiori/db/schema.cds
Normal file
3
fiori/db/schema.cds
Normal file
@@ -0,0 +1,3 @@
|
||||
// Proxy for importing schema from bookshop sample
|
||||
using from '@capire/bookshop';
|
||||
namespace sap.capire.bookshop;
|
||||
15
fiori/package.json
Normal file
15
fiori/package.json
Normal file
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"name": "@capire/fiori",
|
||||
"version": "1.0.0",
|
||||
"dependencies": {
|
||||
"@capire/bookshop": "*",
|
||||
"@capire/orders": "*",
|
||||
"@capire/common": "*",
|
||||
"@sap/cds": "^3.31.1",
|
||||
"express": "^4.17.1"
|
||||
},
|
||||
"scripts": {
|
||||
"start": "cds run --in-memory?",
|
||||
"watch": "cds watch"
|
||||
}
|
||||
}
|
||||
3
fiori/srv/admin-service.cds
Normal file
3
fiori/srv/admin-service.cds
Normal file
@@ -0,0 +1,3 @@
|
||||
// Proxy for importing services from bookshop sample
|
||||
using from '@capire/bookshop';
|
||||
annotate AdminService with @impl:'srv/admin-service.js';
|
||||
8
fiori/srv/admin-service.js
Normal file
8
fiori/srv/admin-service.js
Normal file
@@ -0,0 +1,8 @@
|
||||
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)
|
||||
})
|
||||
7
hello/package.json
Normal file
7
hello/package.json
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"name": "@capire/hello-world",
|
||||
"version": "1.0.0",
|
||||
"scripts": {
|
||||
"watch": "cds serve world.cds"
|
||||
}
|
||||
}
|
||||
1
hello/test.http
Normal file
1
hello/test.http
Normal file
@@ -0,0 +1 @@
|
||||
GET http://localhost:4004/say/hello(to='world')
|
||||
3
hello/world.cds
Normal file
3
hello/world.cds
Normal file
@@ -0,0 +1,3 @@
|
||||
service say {
|
||||
function hello (to:String) returns String;
|
||||
}
|
||||
3
hello/world.js
Normal file
3
hello/world.js
Normal file
@@ -0,0 +1,3 @@
|
||||
module.exports = class say {
|
||||
hello(req) { return `Hello ${req.data.to}!` }
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
{"packages":["packages/*"],"version":"1.0.0"}
|
||||
19
media/package.json
Normal file
19
media/package.json
Normal file
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"name": "@capire/media",
|
||||
"version": "1.0.0",
|
||||
"dependencies": {
|
||||
"lokijs": "^1.5.6"
|
||||
},
|
||||
"files": [
|
||||
"db",
|
||||
"srv",
|
||||
"index.cds"
|
||||
],
|
||||
"cds": {
|
||||
"requires": {
|
||||
"db": {
|
||||
"kind": "sql"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
17
orders/db/schema.cds
Normal file
17
orders/db/schema.cds
Normal file
@@ -0,0 +1,17 @@
|
||||
using { sap.capire.bookshop.Books } from '@capire/bookshop';
|
||||
using { Currency, managed, cuid } from '@sap/cds/common';
|
||||
namespace sap.capire.bookshop;
|
||||
|
||||
entity Orders : cuid, managed {
|
||||
OrderNo : String @title:'Order Number'; //> readable key
|
||||
Items : Composition of many OrderItems on Items.parent = $self;
|
||||
total : Decimal(9,2) @readonly;
|
||||
currency : Currency;
|
||||
}
|
||||
|
||||
entity OrderItems : cuid {
|
||||
parent : Association to Orders;
|
||||
book : Association to Books;
|
||||
amount : Integer;
|
||||
netAmount : Decimal(9,2);
|
||||
}
|
||||
4
orders/package.json
Normal file
4
orders/package.json
Normal file
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"name": "@capire/orders",
|
||||
"version": "1.0.0"
|
||||
}
|
||||
5
orders/srv/orders-service.cds
Normal file
5
orders/srv/orders-service.cds
Normal file
@@ -0,0 +1,5 @@
|
||||
using { sap.capire.bookshop as my } from '../db/schema';
|
||||
|
||||
service OrdersService {
|
||||
entity Orders as projection on my.Orders;
|
||||
}
|
||||
21
orders/srv/orders-service.js
Normal file
21
orders/srv/orders-service.js
Normal file
@@ -0,0 +1,21 @@
|
||||
const cds = require('@sap/cds')
|
||||
|
||||
module.exports = cds.service.impl(function() {
|
||||
|
||||
const { Books } = cds.entities
|
||||
|
||||
// Reduce stock of ordered books if available stock suffices
|
||||
this.before ('CREATE', 'Orders', (req) => {
|
||||
const { Items: OrderItems } = req.data
|
||||
return cds.transaction(req) .run (()=> OrderItems.map (order =>
|
||||
UPDATE (Books) .where ('ID =', order.book_ID)
|
||||
.and ('stock >=', order.amount)
|
||||
.set ('stock -=', order.amount)
|
||||
)) .then (all => all.forEach ((affectedRows,i) => {
|
||||
if (affectedRows === 0) req.error (409,
|
||||
`${OrderItems[i].amount} exceeds stock for book #${OrderItems[i].book_ID}`
|
||||
)
|
||||
}))
|
||||
})
|
||||
|
||||
})
|
||||
36
package.json
36
package.json
@@ -1,30 +1,20 @@
|
||||
{
|
||||
"name": "@sap/capire-samples",
|
||||
"description": "The umbrella project for all samples to easily setup for local development and tests.",
|
||||
"repository": "https://github.com/SAP-samples/cloud-cap-samples.git",
|
||||
"name": "@capire/samples",
|
||||
"description": "A monorepo with several samples for CAP.",
|
||||
"repository": "https://github.com/sap-samples/cloud-cap-samples.git",
|
||||
"author": "daniel.hutzel@sap.com",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"lerna": "npx --no-install lerna -v > /dev/null || npm i lerna --no-save",
|
||||
"install": "(npm -s run lerna) && lerna bootstrap --hoist",
|
||||
"cleanup": "lerna clean -y && rm -fr node_modules",
|
||||
"bookshop": "cds watch packages/bookshop",
|
||||
"bookshop-enhanced": "cds watch packages/bookshop-enhanced",
|
||||
"reviews-service": "cds watch packages/reviews-service",
|
||||
|
||||
"bookstore": "cds watch packages/bookstore",
|
||||
"media-server": "cds watch packages/media-server"
|
||||
},
|
||||
"dependencies": {
|
||||
"@sap/cds": "latest",
|
||||
"express": "*"
|
||||
"@capire/bookshop": "file:bookshop",
|
||||
"@capire/common": "file:common",
|
||||
"@capire/fiori": "file:fiori",
|
||||
"@capire/media": "file:media",
|
||||
"@capire/orders": "file:orders",
|
||||
"@capire/reviews": "file:reviews"
|
||||
},
|
||||
"devDependencies": {
|
||||
"sqlite3": "*"
|
||||
"chai": "^4.2.0",
|
||||
"chai-subset": "^1.6.0"
|
||||
},
|
||||
"--add-these-to-devDependencies-for-tests": {
|
||||
"@types/jest": "*",
|
||||
"jest": "*"
|
||||
},
|
||||
"license": "SAP SAMPLE CODE LICENSE"
|
||||
"license": "SAP SAMPLE CODE LICENSE",
|
||||
"private": true
|
||||
}
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
using from '@sap/capire-bookshop/app';
|
||||
@@ -1,25 +0,0 @@
|
||||
/*
|
||||
In this model we demonstrate how to add Genres to Books in
|
||||
as if it was an external extension. For example we use
|
||||
CDS Aspects' to extend the core domain model's Books entity
|
||||
as well as the AdminService.
|
||||
*/
|
||||
|
||||
namespace sap.capire.bookshop;
|
||||
using { sap.capire.reviews.ReviewsService as external } from '@sap/capire-reviews';
|
||||
using { sap.capire.bookshop.Books } from '@sap/capire-bookshop/db/schema';
|
||||
using { sap.common.CodeList } from '@sap/cds/common';
|
||||
|
||||
// Extending Books by Reviews and Genres
|
||||
extend Books with {
|
||||
reviews : Composition of many external.Reviews on reviews.subject = ID;
|
||||
rating : external.Reviews.rating;
|
||||
genre : Association to Genres;
|
||||
}
|
||||
|
||||
// Hierarchical Code List for Genres
|
||||
entity Genres : CodeList {
|
||||
key ID : Integer;
|
||||
children : Composition of many Genres on children.parent = $self;
|
||||
parent : Association to Genres;
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
{
|
||||
"name": "@sap/capire-bookshop-enhanced",
|
||||
"version": "1.0.0",
|
||||
"description": "A sample for extending a base application package, in this case bookshop, e.g. in context of verticalization or customization.",
|
||||
"repository": "https://github.com/SAP-samples/cloud-cap-samples.git",
|
||||
"license": "SAP SAMPLE CODE LICENSE",
|
||||
"dependencies": {
|
||||
"@sap/capire-bookshop": "^1.0.0",
|
||||
"@sap/capire-reviews": "^1.0.0",
|
||||
"@sap/cds": "latest",
|
||||
"express": "*"
|
||||
},
|
||||
"scripts": {
|
||||
"reviews-service": "PORT=5005 cds run ../reviews-service --bind --in-memory?",
|
||||
"start": "cds run --in-memory?",
|
||||
"watch": "cds watch"
|
||||
},
|
||||
"cds": {
|
||||
"requires": {
|
||||
"sap.capire.reviews.ReviewsService": {
|
||||
"kind": "odata",
|
||||
"model": "@sap/capire-reviews"
|
||||
},
|
||||
"messaging": {
|
||||
"kind": "file-based-messaging"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
namespace sap.capire.bookshop;
|
||||
|
||||
using { AdminService } from '@sap/capire-bookshop/srv/admin-service';
|
||||
using { sap.capire.bookshop } from '../db/schema';
|
||||
|
||||
@impl:'srv/services'
|
||||
extend service AdminService with {
|
||||
entity Genres as projection on bookshop.Genres;
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
const cds = require ('@sap/cds')
|
||||
|
||||
module.exports = cds.service.impl (async()=>{
|
||||
|
||||
const ReviewsService = await cds.connect.to ('sap.capire.reviews.ReviewsService')
|
||||
const CatalogService = await cds.connect.to ('CatalogService')
|
||||
const db = await cds.connect.to ('db')
|
||||
// import model definitions from connected services to work with subsequently
|
||||
const { Books } = db.entities
|
||||
const { Reviews } = ReviewsService.entities
|
||||
|
||||
CatalogService.impl (srv => {
|
||||
// delegate requests to read reviews to ReviewsService
|
||||
srv.on ('READ', 'Books/reviews', (req) => {
|
||||
const [ subject ] = req.params
|
||||
const tx = ReviewsService.transaction (req)
|
||||
return tx.run (SELECT.from (Reviews) .where ({subject}))
|
||||
})
|
||||
})
|
||||
|
||||
// react on event messages from reviews service
|
||||
ReviewsService.on ('reviewed', (msg) => {
|
||||
console.debug ('> received:', msg.event, msg.data)
|
||||
const { subject, rating } = msg.data
|
||||
const tx = db // TODO: db.transaction (msg)
|
||||
return tx.run (UPDATE (Books, subject) .with ({rating}))
|
||||
// return tx.update (Books, subject) .with ({rating})
|
||||
})
|
||||
|
||||
})
|
||||
@@ -1,32 +0,0 @@
|
||||
#################################################
|
||||
#
|
||||
# Reviews Service
|
||||
#
|
||||
|
||||
|
||||
### Use this one for ReviewsService running as a separate process
|
||||
# Note: use 5005 instead of 4004 in case of separate service
|
||||
POST http://localhost:5005/reviews/Reviews
|
||||
# POST http://localhost:4004/reviews/Reviews
|
||||
Content-Type: application/json;IEEE754Compatible=true
|
||||
|
||||
{"subject":"201", "rating":"5", "title":"boo"}
|
||||
|
||||
### Direct Request to ReviewsService
|
||||
# Note: use 5005 instead of 4004 in case of separate service
|
||||
GET http://localhost:5005/reviews/Reviews?
|
||||
# GET http://localhost:4004/reviews/Reviews?
|
||||
# &$filter=subject eq '201'
|
||||
|
||||
|
||||
### Request to CatalogService > delegated to ReviewsService
|
||||
GET http://localhost:4004/browse/Books(201)/reviews
|
||||
|
||||
### Alternative OData URL
|
||||
GET http://localhost:4004/browse/Books/201/reviews
|
||||
|
||||
###
|
||||
GET http://localhost:4004/browse/Books(201)?
|
||||
&$select=ID,title,rating
|
||||
# &$expand=reviews
|
||||
# Note: the latter only works in case of ReviewsService in same process
|
||||
@@ -1,37 +0,0 @@
|
||||
using AdminService from '../../srv/admin-service';
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
// Books Object Page
|
||||
//
|
||||
annotate AdminService.Books with @(
|
||||
UI: {
|
||||
Facets: [
|
||||
{$Type: 'UI.ReferenceFacet', Label: '{i18n>General}', Target: '@UI.FieldGroup#General'},
|
||||
{$Type: 'UI.ReferenceFacet', Label: '{i18n>Details}', Target: '@UI.FieldGroup#Details'},
|
||||
{$Type: 'UI.ReferenceFacet', Label: '{i18n>Admin}', Target: '@UI.FieldGroup#Admin'},
|
||||
],
|
||||
FieldGroup#General: {
|
||||
Data: [
|
||||
{Value: title},
|
||||
{Value: author_ID},
|
||||
{Value: descr},
|
||||
]
|
||||
},
|
||||
FieldGroup#Details: {
|
||||
Data: [
|
||||
{Value: stock},
|
||||
{Value: price},
|
||||
{Value: currency_code, Label: '{i18n>Currency}'},
|
||||
]
|
||||
},
|
||||
FieldGroup#Admin: {
|
||||
Data: [
|
||||
{Value: createdBy},
|
||||
{Value: createdAt},
|
||||
{Value: modifiedBy},
|
||||
{Value: modifiedAt}
|
||||
]
|
||||
}
|
||||
}
|
||||
);
|
||||
@@ -1,7 +0,0 @@
|
||||
code;symbol;name;descr
|
||||
EUR;€;Euro;European Euro
|
||||
USD;$;US Dollar;United States Dollar
|
||||
CAD;$;Canadian Dollar;Canadian Dollar
|
||||
AUD;$;Australian Dollar;Australian Dollar
|
||||
GBP;£;Pound;Great Britain Pound
|
||||
ILS;₪;Shekel;Israeli New Shekel
|
||||
|
@@ -1,21 +0,0 @@
|
||||
{
|
||||
"name": "@sap/capire-bookshop",
|
||||
"version": "1.0.0",
|
||||
"description": "A simple bookshop application, build in a self-contained all-in-one fashion, i.e. w/o reusing other packages.",
|
||||
"license": "SAP SAMPLE CODE LICENSE",
|
||||
"dependencies": {
|
||||
"@sap/cds": "latest",
|
||||
"express": "*"
|
||||
},
|
||||
"scripts": {
|
||||
"start": "cds run --in-memory?",
|
||||
"watch": "cds watch"
|
||||
},
|
||||
"cds": {
|
||||
"requires": {
|
||||
"db": {
|
||||
"kind": "sql"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
const cds = require('@sap/cds')
|
||||
const { Books } = cds.entities
|
||||
|
||||
/** Service implementation for CatalogService */
|
||||
module.exports = cds.service.impl(function() {
|
||||
this.after ('READ', 'Books', each => each.stock > 111 && _addDiscount2(each,11))
|
||||
this.before ('CREATE', 'Orders', _reduceStock)
|
||||
})
|
||||
|
||||
/** Add some discount for overstocked books */
|
||||
function _addDiscount2 (each,discount) {
|
||||
each.title += ` -- ${discount}% discount!`
|
||||
}
|
||||
|
||||
/** Reduce stock of ordered books if available stock suffices */
|
||||
async function _reduceStock (req) {
|
||||
const { Items: OrderItems } = req.data
|
||||
return cds.transaction(req) .run (()=> OrderItems.map (order =>
|
||||
UPDATE (Books) .set ('stock -=', order.amount)
|
||||
.where ('ID =', order.book_ID) .and ('stock >=', order.amount)
|
||||
)) .then (all => all.forEach ((affectedRows,i) => {
|
||||
if (affectedRows === 0) req.error (409,
|
||||
`${OrderItems[i].amount} exceeds stock for book #${OrderItems[i].book_ID}`
|
||||
)
|
||||
}))
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
### Service Document
|
||||
GET http://localhost:4004/browse
|
||||
|
||||
### Service $metadata document
|
||||
GET http://localhost:4004/browse/$metadata
|
||||
|
||||
### Browsing Books
|
||||
GET http://localhost:4004/browse/Books?
|
||||
# &$select=title,author
|
||||
# &$expand=currency
|
||||
# &sap-language=de
|
||||
|
||||
### Browsing Authors
|
||||
GET http://localhost:4004/admin/Authors?
|
||||
# &$select=name,dateOfBirth,placeOfBirth
|
||||
# &$expand=books($select=title;$expand=currency)
|
||||
# &$filter=ID eq 101
|
||||
# &sap-language=de
|
||||
@@ -1,18 +0,0 @@
|
||||
|
||||
### List Books with their current stocks
|
||||
GET http://localhost:4004/admin/Books?$select=ID,stock
|
||||
|
||||
### List all Orders
|
||||
GET http://localhost:4004/admin/Orders?
|
||||
&$expand=Items
|
||||
|
||||
### Submit Orders
|
||||
POST http://localhost:4004/browse/Orders
|
||||
Content-Type: application/json
|
||||
|
||||
{ "OrderNo":"2019-09...", "Items":[
|
||||
{ "book_ID":201, "amount":5 },
|
||||
{ "book_ID":207, "amount":3 }
|
||||
]}
|
||||
|
||||
# Sending this three times should result in a 409: 5 exceeds stock for book #201
|
||||
@@ -1,5 +0,0 @@
|
||||
ID;firstname;lastname;dateOfBirth;placeOfBirth;dateOfDeath;placeOfDeath
|
||||
101;Emily;Brontë;1818-07-30;Thornton, Yorkshire;1848-12-19;Haworth, Yorkshire
|
||||
107;Charlotte;Brontë;1818-04-21;Thornton, Yorkshire;1855-03-31;Haworth, Yorkshire
|
||||
150;Edgar Allen;Poe;1809-01-19;Boston, Massachusetts;1849-10-07;Baltimore, Maryland
|
||||
170;Richard;Carpenter;1929-08-14;King’s Lynn, Norfolk;2012-02-26;Hertfordshire, England
|
||||
|
@@ -1,11 +0,0 @@
|
||||
ID;parent_ID;name
|
||||
1;;Poetry
|
||||
2;;Biography
|
||||
3;;Fantasy
|
||||
4;;Science Fiction
|
||||
5;;Romance
|
||||
6;;Mystery
|
||||
7;;Thriller
|
||||
8;;Dystopia
|
||||
9;;Tragedy
|
||||
10;;Novel
|
||||
|
@@ -1,6 +0,0 @@
|
||||
ID;title;descr;author_ID;stock;price;currency_code;category_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;9
|
||||
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;10
|
||||
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;1
|
||||
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;5
|
||||
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;3
|
||||
|
@@ -1,4 +0,0 @@
|
||||
ID;locale;title;descr
|
||||
201;de;Sturmhöhe;Sturmhöhe (Originaltitel: Wuthering Heights) ist der einzige Roman der englischen Schriftstellerin Emily Brontë (1818–1848). Der 1847 unter dem Pseudonym Ellis Bell veröffentlichte Roman wurde vom viktorianischen Publikum weitgehend abgelehnt, heute gilt er als ein Klassiker der britischen Romanliteratur des 19. Jahrhunderts.
|
||||
207;de;Jane Eyre;Jane Eyre. Eine Autobiographie (Originaltitel: Jane Eyre. An Autobiography), erstmals erschienen im Jahr 1847 unter dem Pseudonym Currer Bell, ist der erste veröffentlichte Roman der britischen Autorin Charlotte Brontë und ein Klassiker der viktorianischen Romanliteratur des 19. Jahrhunderts. Der Roman erzählt in Form einer Ich-Erzählung die Lebensgeschichte von Jane Eyre (ausgesprochen /ˌdʒeɪn ˈɛə/), die nach einer schweren Kindheit eine Stelle als Gouvernante annimmt und sich in ihren Arbeitgeber verliebt, jedoch immer wieder um ihre Freiheit und Selbstbestimmung kämpfen muss. Als klein, dünn, blass, stets schlicht dunkel gekleidet und mit strengem Mittelscheitel beschrieben, gilt die Heldin des Romans Jane Eyre nicht zuletzt aufgrund der Kino- und Fernsehversionen der melodramatischen Romanvorlage als die bekannteste englische Gouvernante der Literaturgeschichte
|
||||
252;de;Eleonora;“Eleonora” ist eine Erzählung von Edgar Allan Poe. Sie wurde 1841 erstveröffentlicht. In ihr geht es um das Paradox der Treue in der Treulosigkeit.
|
||||
|
@@ -1,18 +0,0 @@
|
||||
namespace sap.capire.bookstore;
|
||||
|
||||
// We reuse Products, which are Books in our domain
|
||||
using { sap.capire.products.Products as Books } from '@sap/capire-products';
|
||||
extend Books with {
|
||||
author : Association to Authors;
|
||||
rating : Decimal(2,1);
|
||||
}
|
||||
|
||||
// We reuse aspect Person to define Authors
|
||||
using { sap.capire.contacts.Person } from '@sap/capire-contacts';
|
||||
entity Authors : Person {
|
||||
key ID : UUID;
|
||||
books : Association to many Books on books.author = $self;
|
||||
}
|
||||
|
||||
// we use enhanced currencies code lists
|
||||
using from '@sap/capire-currencies';
|
||||
@@ -1,48 +0,0 @@
|
||||
{
|
||||
"name": "@sap/capire-bookstore",
|
||||
"version": "1.0.0",
|
||||
"description": "A variant of the bookshop application, built on top of products-service and common reuse packages.",
|
||||
"repository": "https://github.com/SAP-samples/cloud-cap-samples.git",
|
||||
"license": "SAP SAMPLE CODE LICENSE",
|
||||
"dependencies": {
|
||||
"@sap/capire-products": "^1.0.0",
|
||||
"@sap/capire-reviews": "^1.0.0",
|
||||
"@sap/capire-orders": "^1.0.0",
|
||||
"@sap/capire-media": "^1.0.0",
|
||||
"@sap/capire-users": "^1.0.0",
|
||||
"@sap/capire-contacts": "^1.0.0",
|
||||
"@sap/capire-currencies": "^1.0.0",
|
||||
"@sap/cds": "latest",
|
||||
"express": "*"
|
||||
},
|
||||
"bundledDependencies": [
|
||||
"@sap/capire-products",
|
||||
"@sap/capire-reviews",
|
||||
"@sap/capire-orders",
|
||||
"@sap/capire-media",
|
||||
"@sap/capire-users",
|
||||
"@sap/capire-contacts",
|
||||
"@sap/capire-currencies"
|
||||
],
|
||||
"files": [
|
||||
"app", "srv", "db"
|
||||
],
|
||||
"scripts": {
|
||||
"start": "cds run --in-memory?",
|
||||
"watch": "cds watch"
|
||||
},
|
||||
"cds": {
|
||||
"requires": {
|
||||
"db": {
|
||||
"kind": "sql"
|
||||
},
|
||||
"sap.capire.media.MediaServer": {
|
||||
"kind": "rest"
|
||||
},
|
||||
"sap.capire.reviews.ReviewsService": {
|
||||
"model": "@sap/capire-reviews",
|
||||
"kind": "odata"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
//----------------------
|
||||
// workarounds -> should be done by @cds-compiler
|
||||
|
||||
annotate cds.UUID with @odata.Type: 'Edm.String';
|
||||
|
||||
using from '@sap/capire-products';
|
||||
annotate sap.capire.products.Products with { texts @odata.contained }
|
||||
annotate sap.capire.products.Categories with { texts @odata.contained }
|
||||
|
||||
annotate sap.capire.reviews.ReviewsService with @imported;
|
||||
annotate sap.capire.reviews.Reviews with @cds.persistence.skip;
|
||||
annotate sap.capire.reviews.Likes with @cds.persistence.skip;
|
||||
@@ -1,35 +0,0 @@
|
||||
namespace sap.capire.bookstore;
|
||||
|
||||
// Service for all users to browse books
|
||||
using { sap.capire.products } from '../db/schema';
|
||||
|
||||
service CatalogService @(path:'browse'){
|
||||
|
||||
@readonly entity Books as select from products.Products { *,
|
||||
author.firstname ||' '|| author.lastname as author : String,
|
||||
category.name as genre,
|
||||
} excluding { createdBy, modifiedBy };
|
||||
|
||||
@readonly entity Genres as projection on products.Categories;
|
||||
|
||||
}
|
||||
|
||||
// Reuse AdminService from @sap/capire-products...
|
||||
using { sap.capire.products.AdminService } from '@sap/capire-products';
|
||||
using { sap.capire.bookstore as my } from '../db/schema';
|
||||
|
||||
extend service AdminService with @(impl:'srv/services.js') {
|
||||
entity Authors as projection on my.Authors;
|
||||
}
|
||||
|
||||
// Adding reviews via @sap/capire-reviews service
|
||||
using { sap.capire.reviews.ReviewsService as external } from '@sap/capire-reviews';
|
||||
extend service CatalogService with {
|
||||
@readonly entity Reviews as projection on external.Reviews;
|
||||
}
|
||||
|
||||
|
||||
// Adding images via @sap/capire-media service
|
||||
using from '@sap/capire-media';
|
||||
// using from '@sap/capire-orders';
|
||||
// using from '@sap/capire-users';
|
||||
@@ -1,38 +0,0 @@
|
||||
const cds = require('@sap/cds')
|
||||
module.exports['sap.capire.bookstore.CatalogService'] = cds.service.impl (async (srv) => {
|
||||
|
||||
const ReviewsService = await cds.connect.to ('sap.capire.reviews.ReviewsService')
|
||||
const { Reviews } = ReviewsService.entities
|
||||
const { Books } = srv.entities
|
||||
|
||||
// delegate requests to reviews service
|
||||
srv.on('READ', 'Reviews', async (req) => {
|
||||
const { SELECT } = cds.ql(req)
|
||||
const results = await SELECT.from (Reviews)
|
||||
|
||||
// TODO: Should actually be using .where of fluent query API
|
||||
if (req.query.SELECT.where) {
|
||||
return results.filter (row => row.subject === req.query.SELECT.where[2].val)
|
||||
}
|
||||
|
||||
return results
|
||||
})
|
||||
|
||||
// react on event messages from reviews service
|
||||
ReviewsService.on ('reviewed', (msg) => {
|
||||
console.debug ('> received message:', msg.event, msg.data)
|
||||
const {subject,rating} = msg.data
|
||||
const tx = cds.transaction(msg)
|
||||
return tx.run (UPDATE(Books).set({rating}) .where ({ID:subject})) //.then (console.log)
|
||||
})
|
||||
|
||||
})
|
||||
|
||||
|
||||
// FIXME: pls remove this...
|
||||
process.env.destinations = JSON.stringify([{
|
||||
name: 'reviewsDest',
|
||||
url: 'http://localhost:4005/reviews',
|
||||
username: 'dummy',
|
||||
password: 'dummy'
|
||||
}])
|
||||
@@ -1,7 +0,0 @@
|
||||
using { sap.capire.products as my } from '../db/schema';
|
||||
|
||||
service BooksService {
|
||||
entity Books as SELECT from my.Products;
|
||||
}
|
||||
|
||||
annotate cds.UUID with @odata.Type: 'Edm.String';
|
||||
@@ -1,190 +0,0 @@
|
||||
const cds = require ('@sap/cds')
|
||||
|
||||
describe('Localized data on db level', ()=>{
|
||||
|
||||
let db, Books
|
||||
|
||||
it ('should deploy the db schema to sqlite in-memory', async()=>{
|
||||
db = await cds.deploy (__dirname+'/books') .to ('sqlite::memory:')
|
||||
expect (db.model) .toBeDefined()
|
||||
Books = db.entities('sap.capire.products').Products
|
||||
expect (Books) .toBeDefined()
|
||||
})
|
||||
|
||||
it ('should list all books with default language', async ()=>{
|
||||
const books = await SELECT.from (Books, b=>b.title)
|
||||
expect (books) .toMatchObject([
|
||||
{ title: 'Wuthering Heights' },
|
||||
{ title: 'Jane Eyre' },
|
||||
{ title: 'The Raven' },
|
||||
{ title: 'Eleonora' },
|
||||
{ title: 'Catweazle' }
|
||||
])
|
||||
})
|
||||
|
||||
|
||||
it ('should read translated texts from Books_texts', async ()=>{
|
||||
const texts = await SELECT ('locale','title').from (Books+'_texts')
|
||||
expect (texts) .toMatchObject ([
|
||||
{ locale: 'de', title: 'Sturmhöhe' },
|
||||
{ locale: 'de', title: 'Jane Eyre' },
|
||||
{ locale: 'de', title: 'Eleonora' }
|
||||
])
|
||||
})
|
||||
|
||||
it ('should read translated texts from Books.texts', async ()=>{
|
||||
const book = await SELECT.one.from (Books, b=>{
|
||||
b.ID, b.title, b.texts(t=> {
|
||||
t.locale, t.title
|
||||
})
|
||||
}) .where ({title:'Wuthering Heights'})
|
||||
expect (book) .toMatchObject ({
|
||||
title: 'Wuthering Heights', texts:[
|
||||
{locale:'de',title:'Sturmhöhe'}
|
||||
]
|
||||
})
|
||||
})
|
||||
|
||||
it ('should insert books with translated texts', async ()=>{
|
||||
const n = await INSERT.into (Books) .entries ({ ID:444, title:'A New Book', texts:[
|
||||
{locale:'de', title:'Ein Neues Buch'},
|
||||
{locale:'fr', title:'Un Nouveau Livre'},
|
||||
]})
|
||||
expect(n).toBe(3)
|
||||
})
|
||||
|
||||
it ('should delete books w/ cascaded delete to texts', async()=>{
|
||||
const n = await DELETE.from(Books) .where ({ID:444})
|
||||
expect(n).toBe(3)
|
||||
})
|
||||
|
||||
})
|
||||
|
||||
|
||||
describe('Localized data on service level', ()=>{
|
||||
|
||||
let srv, Books
|
||||
|
||||
it ('should serve BooksService', async()=>{
|
||||
srv = await cds.serve('BooksService').from(__dirname+'/books')
|
||||
expect (srv.model) .toBeDefined()
|
||||
Books = srv.entities.Books
|
||||
expect (Books) .toBeDefined()
|
||||
})
|
||||
|
||||
it ('should list all books with default language', async ()=>{
|
||||
const books = await srv.read (Books, b=>b.title)
|
||||
expect (books) .toMatchObject([
|
||||
{ title: 'Wuthering Heights' },
|
||||
{ title: 'Jane Eyre' },
|
||||
{ title: 'The Raven' },
|
||||
{ title: 'Eleonora' },
|
||||
{ title: 'Catweazle' }
|
||||
])
|
||||
})
|
||||
|
||||
it ('should read Books with translated texts', async ()=>{
|
||||
const book = await srv.run (
|
||||
SELECT.from (Books, b=>{ b.ID, b.title, b.texts(t=> {
|
||||
t.locale, t.title
|
||||
})}) .where ({title:'Wuthering Heights'})
|
||||
)
|
||||
expect (book) .toMatchObject ([{
|
||||
title: 'Wuthering Heights', texts:[
|
||||
{locale:'de',title:'Sturmhöhe'}
|
||||
]
|
||||
}])
|
||||
})
|
||||
|
||||
it ('should do the same with convenient method', async ()=>{
|
||||
const book = await srv.read (Books, b=>{ b.ID, b.title, b.texts(t=> {
|
||||
t.locale, t.title
|
||||
})}) .where ({title:'Wuthering Heights'})
|
||||
expect (book) .toMatchObject ([{
|
||||
title: 'Wuthering Heights', texts:[
|
||||
{locale:'de',title:'Sturmhöhe'}
|
||||
]
|
||||
}])
|
||||
})
|
||||
|
||||
it ('should read single Book with translated texts', async ()=>{
|
||||
const book = await srv.run (
|
||||
SELECT.one.from (Books, b=>{ b.ID, b.title, b.texts(t=> {
|
||||
t.locale, t.title
|
||||
})}) .where ({title:'Wuthering Heights'})
|
||||
)
|
||||
expect (book) .toMatchObject ({
|
||||
title: 'Wuthering Heights', texts:[
|
||||
{locale:'de',title:'Sturmhöhe'}
|
||||
]
|
||||
})
|
||||
})
|
||||
|
||||
it ('should insert books with translated texts', async ()=>{
|
||||
const book = { ID:444, title:'A New Book', texts:[
|
||||
{locale:'de', title:'Ein Neues Buch'},
|
||||
{locale:'fr', title:'Un Nouveau Livre'},
|
||||
]}
|
||||
const response = await srv.create (Books) .entries (book)
|
||||
expect(response).toMatchObject(book)
|
||||
})
|
||||
|
||||
it ('should delete books w/ cascaded delete to texts', async()=>{
|
||||
await srv.delete('Books') .where ({ID:444})
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
describe('Localized data on OData level', () => {
|
||||
|
||||
const app = require('express')()
|
||||
const srv = require('supertest')(app)
|
||||
|
||||
it ('should serve BooksService', async ()=>{
|
||||
await cds.serve('BooksService').from(__dirname+'/books') .in (app)
|
||||
})
|
||||
|
||||
it('should list all books with default language', async () => {
|
||||
const books = await srv.get('/books/Books/201/title')
|
||||
expect(books.body).toMatchObject({'value': 'Wuthering Heights'})
|
||||
})
|
||||
|
||||
it('should read books with translated texts', async () => {
|
||||
const books = await srv.get('/books/Books/201/title'). set('Accept-Language', 'de')
|
||||
expect(books.body).toMatchObject({value: 'Sturmhöhe'})
|
||||
})
|
||||
|
||||
it('should expand translated texts in Book', async () => {
|
||||
const books = await srv. get('/books/Books/201?$select=title&$expand=texts($select=locale,title)')
|
||||
expect(books.body).toMatchObject({
|
||||
title: 'Wuthering Heights',
|
||||
texts: [
|
||||
{ locale: 'de', title: 'Sturmhöhe', },
|
||||
],
|
||||
})
|
||||
})
|
||||
|
||||
const book = {
|
||||
title: 'New Book', descr: 'Lorem Ipsum',
|
||||
texts: [
|
||||
{ locale: 'de', title: 'Neues Buch', descr: 'Dolor sit amet' },
|
||||
{ locale: 'fr', title: 'Nouveau Livre', descr: 'consetetur sadipscing elitr' }
|
||||
],
|
||||
}
|
||||
|
||||
it('should insert books with translated texts', async () => {
|
||||
const {body} = await srv.post('/books/Books').send(book)
|
||||
expect(body).toMatchObject(book)
|
||||
book.ID = body.ID
|
||||
})
|
||||
|
||||
it ('should read the newly created book', async()=>{
|
||||
const {body} = await srv.get('/books/Books/'+book.ID+'?$expand=texts').send(book)
|
||||
expect(body).toMatchObject(book)
|
||||
})
|
||||
|
||||
it ('should delete books w/ cascaded delete to texts', async()=>{
|
||||
await srv.delete('/books/Books/'+book.ID)
|
||||
.expect(204)
|
||||
})
|
||||
})
|
||||
@@ -1,37 +0,0 @@
|
||||
using { sap.capire.contacts.PostalAddress } from './schema';
|
||||
using { sap } from '@sap/cds/common';
|
||||
namespace sap.capire.contacts;
|
||||
|
||||
/**
|
||||
* The Code Lists below are designed as optional extensions to
|
||||
* the base schema. Switch them on by adding an Association to
|
||||
* one of the code list entities in your models or by:
|
||||
* annotate sap.common.Countries with @cds.persistence.skip:false;
|
||||
*/
|
||||
|
||||
entity Countries as select from sap.common.Countries;
|
||||
extend sap.common.Countries {
|
||||
regions : Composition of many Regions on regions._parent = $self.code;
|
||||
}
|
||||
entity Regions : sap.common.CodeList {
|
||||
key code : String(5); // ISO 3166-2 alpha5 codes, e.g. DE-BW
|
||||
children : Composition of many Regions on children._parent = $self.code;
|
||||
cities : Composition of many Cities on cities.region = $self;
|
||||
_parent : String(11);
|
||||
}
|
||||
entity Cities : sap.common.CodeList {
|
||||
key code : String(11);
|
||||
region : Association to Regions;
|
||||
districts : Composition of many Districts on districts.city = $self;
|
||||
}
|
||||
entity Districts : sap.common.CodeList {
|
||||
key code : String(11);
|
||||
city : Association to Cities;
|
||||
}
|
||||
|
||||
annotate PostalAddress with {
|
||||
district @ref: sap.capire.contacts.Districts;
|
||||
city @ref: sap.capire.contacts.Cities;
|
||||
region @ref: sap.capire.contacts.Regions;
|
||||
country @ref: sap.capire.contacts.Countries;
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
namespace sap.capire.contacts;
|
||||
|
||||
|
||||
//--------------------------------------------------------------------------
|
||||
// Aspects
|
||||
|
||||
|
||||
aspect Organization {
|
||||
orgname : String(111);
|
||||
}
|
||||
|
||||
aspect Person {
|
||||
firstname : String(111);
|
||||
lastname : String(111);
|
||||
prefix : String(11);
|
||||
suffix : String(11);
|
||||
middle : String(11);
|
||||
dateOfBirth : Date; placeOfBirth : String;
|
||||
dateOfDeath : Date; placeOfDeath : String;
|
||||
}
|
||||
|
||||
aspect PostalAddress {
|
||||
street : String(222) @multiline;
|
||||
postCode : String(11);
|
||||
district : String(111);
|
||||
city : String(111);
|
||||
region : String(111);
|
||||
country : String(111);
|
||||
}
|
||||
|
||||
aspect ContactOptions {
|
||||
email : String @JSON:[{ kind:String, address: EmailAddress }];
|
||||
phone : String @JSON:[{ kind:String, number: PhoneNumber }];
|
||||
// phone : array of { kind:String; number: PhoneNumber };
|
||||
// addresses : Composition of many PostalAddress;
|
||||
}
|
||||
|
||||
type EmailAddress : String;
|
||||
type PhoneNumber : String;
|
||||
|
||||
|
||||
|
||||
//--------------------------------------------------------------------------
|
||||
// Entities
|
||||
|
||||
@cds.persistence.skip:'if-unused'
|
||||
entity Contacts : Person, Organization, ContactOptions {
|
||||
key ID : UUID;
|
||||
isOrg : Boolean;
|
||||
addresses : Composition of many PostalAddresses on addresses.contact = $self;
|
||||
}
|
||||
|
||||
@cds.persistence.skip:'if-unused'
|
||||
entity PostalAddresses : PostalAddress {
|
||||
contact : Association to Contacts;
|
||||
kind : String;
|
||||
key ID : UUID;
|
||||
}
|
||||
@@ -1,2 +0,0 @@
|
||||
using from './db/code-lists';
|
||||
using from './db/schema';
|
||||
@@ -1,10 +0,0 @@
|
||||
{
|
||||
"name": "@sap/capire-contacts",
|
||||
"version": "1.0.0",
|
||||
"description": "A reuse package providing common domain models and services for contacts-related data.",
|
||||
"repository": "https://github.com/SAP-samples/cloud-cap-samples.git",
|
||||
"license": "SAP SAMPLE CODE LICENSE",
|
||||
"dependencies": {
|
||||
"@sap/cds": "latest"
|
||||
}
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
# Common Contacts Sample
|
||||
|
||||
This sample provides a reuse package with common domain models and services for contacts-related data.
|
||||
|
||||
## Usage
|
||||
|
||||
|
||||
#### Import to your project
|
||||
|
||||
npm install @sap/capire-contacts
|
||||
|
||||
> e.g. see: [bookstore](../bookstore/package.json)
|
||||
|
||||
#### Reusing aspects
|
||||
|
||||
Define own entities derived from the pre-defined aspects as in [_bookstore_](../bookstore/db/schema.cds):
|
||||
|
||||
```swift
|
||||
using { sap.capire.contacts.Person } from '@sap/capire-contacts';
|
||||
entity Authors : contacts.Person { ... }
|
||||
```
|
||||
|
||||
> **Note:** All entities in this package are annotated with _`@cds.persistence.skip`:'if-unused'_, so they will be ignored if not referred to from other entities in your models.
|
||||
|
||||
|
||||
#### Reusing entities
|
||||
|
||||
Reuse the entities as in this example from [_users-service_](../users-service/srv/services.cds):
|
||||
```swift
|
||||
using { sap.capire.contacts.Contacts } from '@sap/capire-contacts';
|
||||
service UsersService @(requires:'authenticated-user') {
|
||||
entity MyProfile as select from Contacts where ID=$user;
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
#### Reusing code lists
|
||||
|
||||
Reuse the code lists as in [_./tests/index.cds_](./tests/index.cds):
|
||||
|
||||
```swift
|
||||
service Sue { ...
|
||||
// expose Countries to activate provided code lists
|
||||
@readonly entity Countries as projection on sap.capire.contacts.Countries;
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
|
||||
#### Reuse code list service
|
||||
|
||||
```js
|
||||
const { intercept } = require ('@sap/capire-contacts/srv/code-lists')
|
||||
```
|
||||
|
||||
|
||||
|
||||
## Content
|
||||
|
||||
|
||||
|
||||
## Concepts
|
||||
|
||||
* [Reuse of packages](https://cap.cloud.sap/docs/get-started/projects#reuse)
|
||||
* Code Lists, `@sap/cds/common` and `@cds.persistence.skip`: 'if-unused'
|
||||
* Using `aspects` vs `entities`
|
||||
@@ -1,70 +0,0 @@
|
||||
const cds = require ('@sap/cds')
|
||||
const READ='READ', WRITE = ['CREATE','UPDATE']
|
||||
|
||||
const intercept = exports.intercept = cds.service.impl (async (srv) => {
|
||||
|
||||
for (let each in srv.entities) {
|
||||
|
||||
// intercept JSON-encoded elements
|
||||
const jsons = await jsonsIn (srv.entities[each].elements)
|
||||
if (jsons) {
|
||||
srv.before (WRITE, each, ({data:row})=>{
|
||||
for (let e of jsons) if (row[e]) row[e] = JSON.stringify (row[e])
|
||||
})
|
||||
srv.after (READ, each, (row)=>{
|
||||
for (let e of jsons) if (row[e]) row[e] = JSON.parse (row[e])
|
||||
})
|
||||
}
|
||||
|
||||
// intercept references
|
||||
const refs = await refsIn (srv.entities[each].elements, srv.model)
|
||||
if (refs) srv.after (READ, each, (rows, req)=>{
|
||||
for (let row of rows) {
|
||||
for (let {element,codelist} of refs) {
|
||||
const entry = codelist [row[element]]
|
||||
if (entry) {
|
||||
const localized = entry.texts [req.user.locale || intercept.locale]
|
||||
row[element] = localized ? localized.name : entry.name
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
})
|
||||
|
||||
|
||||
function jsonsIn (elements) {
|
||||
const jsons=[]; for (let e in elements) {
|
||||
if (elements[e]['@JSON']) jsons.push(e)
|
||||
}
|
||||
return jsons.length && jsons
|
||||
}
|
||||
|
||||
async function refsIn (elements, model) {
|
||||
const refs=[]; for (let e in elements) {
|
||||
const $ref = elements[e]['@ref']
|
||||
if ($ref) {
|
||||
const d = model.definitions [$ref['=']]
|
||||
refs.push({
|
||||
element:e,
|
||||
codelist: CodeLists[d.name] || (CodeLists[d.name] = await load(d))
|
||||
})
|
||||
}
|
||||
}
|
||||
return refs.length && refs
|
||||
}
|
||||
|
||||
const load = exports.load = async (codelist) => {
|
||||
const all = {}
|
||||
const [entries,texts] = await Promise.all ([
|
||||
SELECT.from (codelist),
|
||||
SELECT.from (codelist.elements.texts.target)
|
||||
])
|
||||
for (let {code,name,descr} of entries) all[code] = {name,descr}
|
||||
for (let {code,locale,name,descr} of texts) (all[code].texts || (all[code].texts={})) [locale] = {name,descr}
|
||||
return all
|
||||
}
|
||||
|
||||
const CodeLists = {}
|
||||
@@ -1,68 +0,0 @@
|
||||
const {load,intercept} = require ('../srv/code-lists')
|
||||
const cds = require ('@sap/cds')
|
||||
|
||||
// patch-enhance cds.ql
|
||||
const select = SELECT.from('.').__proto__.__proto__, query = select.__proto__
|
||||
query.then = function (r,e) { return db.run(this) .then (r,e || ((e)=>{throw e})) }
|
||||
|
||||
let db, Countries, Australia = {
|
||||
name: 'Australia', descr: 'Commonwealth of Australia', texts: {
|
||||
de: { name: 'Australien', descr: 'Commonwealth Australien' }
|
||||
}
|
||||
}
|
||||
|
||||
describe ('code list tests', ()=>{
|
||||
|
||||
it ('should deploy the db schema to sqlite in-memory', async()=>{
|
||||
db = await cds.deploy (__dirname) .to ('sqlite::memory:', {silent:true,primary:true})
|
||||
Countries = db.model.entities ['sap.common.Countries']
|
||||
expect (Countries) .toBeDefined()
|
||||
})
|
||||
|
||||
it ('should read Countries', async()=>{
|
||||
const countries = await SELECT ('code','name') .from (Countries)
|
||||
expect (countries) .toContainEqual ({ code: 'AU', name: 'Australia' })
|
||||
})
|
||||
|
||||
it ('should read Countries_texts', async()=>{
|
||||
const countries = await SELECT ('locale','code','name') .from ('sap.common.Countries_texts')
|
||||
expect (countries) .toContainEqual ({ locale: 'de', code: 'AU', name: 'Australien' })
|
||||
})
|
||||
|
||||
it ('should read code lists with translated texts', async()=>{
|
||||
const {AU} = await load (Countries)
|
||||
expect (AU) .toEqual (Australia)
|
||||
})
|
||||
|
||||
cds.env.singletenant = true
|
||||
|
||||
it ('should serve services with localized data', async()=>{
|
||||
const { Sue:sue } = await cds.serve (__dirname)
|
||||
const { Foos } = sue.entities
|
||||
await sue.create (Foos) .entries ({country:'Avalon'})
|
||||
await sue.create (Foos) .entries ({country:'AU'})
|
||||
expect (await sue.read('Foos')) .toEqual ([ { ID: 1, country: 'Avalon' }, { ID: 2, country: 'AU' } ])
|
||||
})
|
||||
|
||||
it ('should resolve countries', async()=>{
|
||||
const sue = await cds.connect.to ('Sue')
|
||||
await intercept (sue)
|
||||
expect (await sue.read('Foos')) .toEqual ([ { ID: 1, country: 'Avalon' }, { ID: 2, country: 'Australia' } ])
|
||||
intercept.locale = 'de'
|
||||
expect (await sue.read('Foos')) .toEqual ([ { ID: 1, country: 'Avalon' }, { ID: 2, country: 'Australien' } ])
|
||||
console.log (await sue.read('Foos'))
|
||||
})
|
||||
|
||||
it ('should read countries with expand to translated texts', async()=>{
|
||||
const countries = await cds.read (Countries, c=>{
|
||||
c.name, c.texts (t => {
|
||||
t.locale, t.name
|
||||
})
|
||||
})
|
||||
console.log (countries)
|
||||
})
|
||||
|
||||
it ('should disconnect from db', ()=> db.disconnect())
|
||||
//> FIXME: that should not be required!
|
||||
|
||||
})
|
||||
@@ -1,11 +0,0 @@
|
||||
using { sap } from '..';
|
||||
|
||||
entity Foo {
|
||||
key ID : Integer;
|
||||
country : String @ref: sap.capire.contacts.Countries;
|
||||
}
|
||||
service Sue {
|
||||
entity Foos as projection on Foo;
|
||||
// expose Countries to activate provided code lists
|
||||
@readonly entity Countries as projection on sap.capire.contacts.Countries;
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
code;locale;name;descr
|
||||
EUR;de;Euro;European Euro
|
||||
USD;de;US-Dollar;United States Dollar
|
||||
CAD;de;Kanadischer Dollar;Kanadischer Dollar
|
||||
AUD;de;Australischer Dollar;Australischer Dollar
|
||||
GBP;de;Pfund;Britische Pfund
|
||||
ILS;de;Schekel;Israelische Schekel
|
||||
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
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user