본문 바로가기

안녕하세요!

프로그래밍 언어/CAP

[ CAP ] Class cds.Service - Handler Registration API(1)


 

Class cds.Service


 

Handler Registration API


 

srv.on(event, path?, handler) → this


 

srv.on로 등록되어 있는 Handlers는 순서대로 실행되며,
각 Handler는 srv.prepend를 함께 등록하여 사용자 지정대로 순서를 끝내는 기능을 사용할 수 있다.

만약, 일반적인 Handler 기능을 사용하기 위해서는 사용자정의 Handler에서 next를 호출하면 된다.  

 

event 단일 event의 이름또는 이러한 여러 evnet의 배열 
path entity CSN 개체, 노출된 entity 이름, 경로 또는 여러 항목의 배열
handler handler 함수

 

// Direct request | GET /Products
srv.on('READ', 'Products', (req) => {...})

// fully-qualified name 등록 | GET /Products
srv.on('READ', 'serviceName.Products', (req) => {...})

// Navigation requests | GET Supplier/1/supplier
srv.on('READ', 'Supplier/products', (req) => { let [ID] = req.params; ...})

// CSN 등록 | GET /Products
srv.on('READ', Products, (req) => {...})

// unbound actions/functions 호출
srv.on('cancelOrder', (req) => {...})

// bound actions/functions 호출
srv.on('cancel', 'Orders', (req) => {...})

srv.before(event, entity?, handler) → this


 

this.before ('CREATE', 'Orders', (req) => {
    const orders = req.data
    if(orders.quantity > 11) throw 'Order quantity must not exceed 10'
})

 

srv.beforesrv.on()으로 등록된 Handler보다 먼저 실행할 Handler를 등록하는 메서드이다.
즉, 일반 Handler보다 먼저 실행된다고 이해하면 된다.
이 메서드는 일반적으로 custom input 유효성 검사를 추가할 때에 종종 사용된다. 

'CREATE' 메서드와 'Orders' 개체를 사용해 service 실행 요소를 추가한다.
orders라는변수를 req라는 파라미터를 이용해 data에 저장한다.

만약에 주문량이 11개보다 많다면 위와 같은 경고문을 보여주게 된다.   

 

srv.before ('CREATE', 'Order', (req) => {
    const orders = req.data
    return UPDATE(Products).set ('unitsInStock -=', orders.quantity)
})

 

뿐만 아니라, entity Orders의 quantity가 추가될 때마다 
entity Products에 저장돼 있는 데이터 중 unitInStocks의 값은 감소하도록 설정할 수 있다.

다만, before Handler는 모두 등록된 순서대로 실햄됨을 주의하자.
또한 async 작업을 작동시키면 항상 promise를 반환한다.

그리고 반환된 모든 promise는 Primise.all에 적재되고,
.on Handler 실행 다음 단계는 모든 promise가 해결되었을 때 시작된다.

req.reject를 통해 requests를 먼저 종료할 수 있다.
하지만 async 부분은 병렬로 실행되기 때문에 .before Handler 간의 부작용에 대응할 수 없다. 

 

srv.after(event, entity?, handler) → this


 

this.after('READ', 'Products', (products) => {
	for(let each of products) each.unitsInStock > 10 && each.dicount='11%'
})

 

srv.after은 일반 Hendler 다음에 실행할 Handler를 등록하는 기능을 제공한다.

 

this.after('READ, 'Products', (products.req) => {
    if(req.data.ID) ...
})

 

inbound request를 반영해야 하는 경우에는
보조 param(개매변수) req를 사용하자.

 

this.after('READ', 'Products', (products) => {
	return ...
})

 

.after 메서드의 경우에는 수정만 가능하기에 위의 경우는 값을 반환시킬 수 없다.

 

this.on('READ', 'Products', async (req,next) => {
    const products = await next()
    return ...
})

 

따라서 특정 데이터값을 반환하기 위해서는 .on을 사용하고, 비동기 방식인 async를 입력한다.

products라는 변수는 async 메서드에서만 작동하는 await을 사용함으로써
하나의 메세지를 다 읽고 나서 다음 메세지를 읽도록 next() 함수를 선언해준다.

그리고 데이터 값을 반환하도록 설정한다.  

반응형

srv.reject(event, entity?) → this


 

this.reject('READ', 'Orders')

this.reject(['CREATE', 'UPDATE', 'DELETE'], ['Producst', 'Authors'])

 

event 단일 event 이름 또는 여러 이벤트 배열
entity 노출된 entity 이름 또는 여러 대의 배열

 

기본 에러 메세지와 함께 들어오는 request를 자동으로 거부하는 일반 Handler를 등록한다.

이는 여러 event 및 entity를 지정할 수 있다.  

Next Stage : 
728x90
반응형

'프로그래밍 언어 > CAP' 카테고리의 다른 글

[ CAP ] Node.js - Facade Pattern - @sap/cds  (0) 2023.08.14
[ CAP ] Views and Projections  (2) 2023.04.12
[ CAP ] Temporal Database  (0) 2023.04.10
[ CAP ] What is the 'CSV'?  (0) 2023.04.04

loading