Bu sayfa, iki farklı servisten API call çağrısı ile veri alıp çıktılarını birleştirerek tek bir çıktı halinde döndürme işlemini açıklar.
Senaryo
- Servis1: Kullanıcı bilgilerini döner
- Servis2: Departman bilgilerini döner
- Eşleştirme:
Servis1.xDEPARTMANI == Servis2.ChildDepartmentID durumunda Servis2’den Servis1’e veri ekler
Servis1 Örnek Çıktısı
[
{
"USERID": "111",
"FIRSTNAME": "ADI",
"LASTNAME": "SOYADI",
"EMPLOYEMENTSTART": "2011-04-18 00:00:00.0",
"DEPARTMENT": "333",
"DEPARTMENTNAME": "DEPARTMAN ADI",
"PROFESSION": "44",
"PROFESSIONNAME": "YETKİLİ",
"POS_ITION": "55555"
}
]
Servis2 Örnek Çıktısı
{
"0": {
"ParentDepartmentID": "xxx",
"ParentDepartmentName": "DEP NAME > GİDİLECEK DEP NAME",
"ChildDepartmentID": "yyy"
},
"1": {...}
}
Groovy Script
import groovy.json.JsonSlurper
import groovy.json.JsonOutput
def linearFind(map, elementToSearch) {
def returnValue = -1
map.each { k, v ->
if (v.ChildDepartmentID.toString() == elementToSearch.xDEPARTMANI.toString()){
returnValue = v
}
}
return returnValue
}
//Servis1'den cevap alır
String requestX = "http://1.1.1.1:30080/apigateway/xyolu"
URL urlX = new URL(requestX)
HttpURLConnection connX = (HttpURLConnection) urlX.openConnection()
connX.setDoOutput(true)
connX.setRequestMethod("GET")
connX.setRequestProperty("Content-Type", "application/json")
connX.setUseCaches(false)
connX.setConnectTimeout(60000)
def orijinalBody = connX.inputStream.withCloseable { inStream ->
new JsonSlurper().parse(inStream as InputStream)
}
//Servis2'den cevap alır
String request = "http://1.1.1.1:30080/apigateway/test/test"
URL url = new URL(request)
HttpURLConnection conn = (HttpURLConnection) url.openConnection()
conn.setDoOutput(true)
conn.setRequestMethod("POST")
conn.setRequestProperty("Content-Type", "application/json")
conn.setUseCaches(false)
conn.setConnectTimeout(10000)
def childBody = conn.inputStream.withCloseable { inStream ->
new JsonSlurper().parse(inStream as InputStream)
}
//2 servisteki verileri kıyaslar
//eşleşme bulursa ilgili değerleri kayda ekler
orijinalBody.eachWithIndex { val, idx ->
def result = linearFind(childBody, val)
if(result != -1){
val.put("ParentDepartmentID", result.ParentDepartmentID)
val.put("ParentDepartmentName", result.ParentDepartmentName)
}
}
//Sonucu json formatında döner
responseBodyTextToClient = JsonOutput.toJson(orijinalBody)
Açıklama
Bu script şu işlemleri yapar:
- Servis1’den Veri Alma: İlk servisten GET isteği ile kullanıcı bilgilerini alır.
- Servis2’den Veri Alma: İkinci servisten POST isteği ile departman bilgilerini alır.
- Eşleştirme:
linearFind fonksiyonu kullanarak Servis1’deki her kayıt için Servis2’de eşleşen departman bilgisini bulur.
- Veri Birleştirme: Eşleşme bulunduğunda Servis1 kaydına Servis2’den gelen
ParentDepartmentID ve ParentDepartmentName alanlarını ekler.
- Sonuç Döndürme: Birleştirilmiş veriyi JSON formatında döner.
Bu script, response hattında (Response Policy) çalıştırılmalıdır çünkü responseBodyTextToClient değişkenini kullanmaktadır.