/
customer-material-service.js
70 lines (63 loc) · 2.5 KB
/
customer-material-service.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
const cds = require('@sap/cds')
function getCustomerFilter(req) {
var customer = req.user.attr.customer
return {Customer: customer}
}
module.exports = async function (srv){
const externalCustomerMaterial = await cds.connect.to('API_CUSTOMER_MATERIAL_SRV')
srv.on ('READ','A_CustomerMaterial', async req => {
const externalCustomerMaterialTransaction = externalCustomerMaterial.transaction(req)
try {
// Restrict to Customer in User attribute
var customerFilter = getCustomerFilter(req)
// Works but needs custom handling for read
if(req.query.SELECT.from && req.query.SELECT.from.ref[0] && req.query.SELECT.from.ref[0].where) {
// single read
var query = SELECT.from(req.target).where(req.data).where(customerFilter)
if(req.query.SELECT.columns) {
query.columns();
}
let results = await externalCustomerMaterialTransaction.run(query)
return results[0]
} else {
// Query
req.query.where(customerFilter)
let result = await externalCustomerMaterialTransaction.run(req.query)
return result
}
/*
// Creates:
// Request Patch: /sap/opu/odata/sap/API_CUSTOMER_MATERIAL_SRV/%5Bobject%20Object%5D?$select=Material,MaterialByCustomer,SalesOrganization,DistributionChannel,Customer&$filter=Customer%20eq%20%271000021%27&$format=json
// for single and mails.
req.query.where(customerFilter)
let result = await externalCustomerMaterialTransaction.run(req.query)
return result
*/
} catch (error) {
console.error("Error Message: " + error.message)
if(error.request && error.request.path) {
console.error("Request Patch: " + error.request.path)
}
}
})
srv.on ('READ','A_CustomerMaterialSimple', async req => {
const externalCustomerMaterialTransaction = externalCustomerMaterial.transaction(req)
try {
// Restrict to Customer in User attribute
var customerFilter = getCustomerFilter(req)
req.query.where(customerFilter)
let result = await externalCustomerMaterialTransaction.run(req.query)
return result
} catch (error) {
console.error("Error Message: " + error.message)
if(error.request && error.request.path) {
console.error("Request Patch: " + error.request.path)
}
}
})
srv.after('READ', 'A_CustomerMaterial', (customerMaterial,req) => {
if(customerMaterial && customerMaterial.length) {
customerMaterial.$count = customerMaterial.length
}
})
}