|
| 1 | +import { |
| 2 | + HttpTransport, |
| 3 | + HttpTransportConfig, |
| 4 | +} from '@chainlink/external-adapter-framework/transports' |
| 5 | +import { BaseEndpointTypes } from '../endpoint/cpi' |
| 6 | + |
| 7 | +export interface ResponseSchema { |
| 8 | + index: string[] // dates as string |
| 9 | + truflation_us_cpi_frozen_index: number[] |
| 10 | + start_date: string |
| 11 | +} |
| 12 | + |
| 13 | +export type HttpTransportTypes = BaseEndpointTypes & { |
| 14 | + Provider: { |
| 15 | + RequestBody: never |
| 16 | + ResponseBody: ResponseSchema |
| 17 | + } |
| 18 | +} |
| 19 | + |
| 20 | +const transportConfig: HttpTransportConfig<HttpTransportTypes> = { |
| 21 | + prepareRequests: (params, config) => { |
| 22 | + return params.map((param) => { |
| 23 | + return { |
| 24 | + params: [param], |
| 25 | + request: { |
| 26 | + baseURL: config.API_ENDPOINT, |
| 27 | + headers: { |
| 28 | + Authorization: config.API_KEY, |
| 29 | + }, |
| 30 | + }, |
| 31 | + } |
| 32 | + }) |
| 33 | + }, |
| 34 | + parseResponse: (params, response) => { |
| 35 | + const data = response.data |
| 36 | + if ( |
| 37 | + !data?.index?.length || |
| 38 | + !data?.truflation_us_cpi_frozen_index?.length || |
| 39 | + data.index.length !== data.truflation_us_cpi_frozen_index.length |
| 40 | + ) { |
| 41 | + return params.map((param) => { |
| 42 | + return { |
| 43 | + params: param, |
| 44 | + response: { |
| 45 | + errorMessage: `Invalid data provider response: index and truflation_us_cpi_frozen_index arrays must contain data and have equal length`, |
| 46 | + statusCode: 502, |
| 47 | + }, |
| 48 | + } |
| 49 | + }) |
| 50 | + } |
| 51 | + |
| 52 | + const originalIndexArrayCopy = Array.from(data.index) |
| 53 | + // filter response, .sort() sorts ascending by default |
| 54 | + const sortedIndexArray = originalIndexArrayCopy.sort() |
| 55 | + const latestDate = sortedIndexArray[sortedIndexArray.length - 1] |
| 56 | + const mappedIndex = data.index.indexOf(latestDate) |
| 57 | + const result = data.truflation_us_cpi_frozen_index[mappedIndex] |
| 58 | + |
| 59 | + return params.map((param) => { |
| 60 | + return { |
| 61 | + params: param, |
| 62 | + response: { |
| 63 | + result, |
| 64 | + data: { |
| 65 | + date: latestDate, |
| 66 | + cpi: result, |
| 67 | + }, |
| 68 | + }, |
| 69 | + } |
| 70 | + }) |
| 71 | + }, |
| 72 | +} |
| 73 | + |
| 74 | +export class CpiTransport extends HttpTransport<HttpTransportTypes> { |
| 75 | + constructor() { |
| 76 | + super(transportConfig) |
| 77 | + } |
| 78 | +} |
| 79 | + |
| 80 | +export const httpTransport = new CpiTransport() |
0 commit comments