cds.connect.to 한 줄로 외부 서비스 연결 끝 #shorts #SAP #CAP
Moderator
왜 cds.connect.to인가?
CAP 앱에서 외부 REST API나 S/4HANA 서비스를 직접 axios로 호출하면 인증 토큰 관리, BTP Destination 연동, 에러 핸들링을 모두 직접 구현해야 합니다. cds.connect.to()를 쓰면 이 모든 과정이 단 한 줄로 끝납니다.
package.json — 서비스 등록
{
"cds": {
"requires": {
"ExternalOrders": {
"kind": "rest",
"credentials": {
"destination": "MY_BTP_DEST"
}
}
}
}
}
BTP Destination 이름만 지정하면 CAP 런타임이 OAuth 토큰 발급과 갱신을 자동으로 처리합니다. 로컬 개발 시에는 credentials.url에 직접 URL을 넣으면 됩니다.
서비스 연결 — 핵심 두 줄
const ext = await cds.connect.to('ExternalOrders');
const result = await ext.get('/Orders?$top=10');
첫 줄에서 연결 객체를 가져오고, 두 번째 줄에서 OData 또는 REST 요청을 실행합니다. 인증 헤더는 런타임이 자동으로 주입합니다.
Service Handler 안에서 사용하기
module.exports = cds.service.impl(async function () {
const ext = await cds.connect.to('ExternalOrders');
this.on('READ', 'MyOrders', async (req) => {
return ext.run(req.query);
});
});
ext.run(req.query)는 프론트엔드에서 내려온 CDS 쿼리 객체를 외부 서비스의 OData 요청으로 변환해 실행합니다. 필터, 페이징, 정렬 조건이 자동 전달됩니다.
로컬 vs 프로덕션 전환
// .cdsrc.json (로컬 개발용)
{
"[development]": {
"requires": {
"ExternalOrders": {
"kind": "rest",
"credentials": { "url": "http://localhost:4005" }
}
}
}
}
환경별 설정을 분리하면 코드 변경 없이 로컬과 BTP 환경을 전환할 수 있습니다.
핵심 한 줄
cds.connect.to() 한 줄이면 BTP Destination 인증부터 OData 변환까지 CAP이 전부 처리한다.