Created
December 29, 2022 05:52
-
-
Save shreyakupadhyay/1df71c86533500620170f192963902cd to your computer and use it in GitHub Desktop.
Advanced level typescript implementation of API response handling
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- common payload: stats associated with data --> | |
type StatsRange = { | |
max: number, min: number | |
} | |
type StatsKeys = 'count' | 'aum' | 'priceusd' | 'value' | |
type PartialStats< | |
T extends Partial<{ | |
[key in StatsKeys]: any; | |
}> = { | |
[key in StatsKeys]: any; | |
}, | |
> = { | |
stats?: { | |
[key in keyof T]?: StatsRange; | |
}; | |
}; | |
<!-- common payload: pagination info --> | |
type Pagination = { | |
pagination?: { | |
currentPage: number, | |
perPage: number, | |
total: number, | |
totalPages: number | |
} | |
} | |
<!-- api: onboarding data --> | |
type APIResponseOnboards = { | |
count: number, | |
unixTimeStamp: number, | |
timestamp: string, | |
} | |
<!-- api: historical data --> | |
type APIResponseHistorical = { | |
aum: number, | |
unixTimeStamp: number, | |
} | |
<!-- api: wallets data --> | |
type APIResponseWallets = { | |
wid: number, | |
tenant: number, | |
portfolioValue: number, | |
address: string, | |
} | |
<!-- all api data handling --> | |
type GroupedResponse<T> = ( | |
{ data: T[]} | { data: T[]; field: string; grouping: string} | |
)[] | |
type DataServiceResponse< | |
BasePayload extends Record<string, any>, | |
DataShape extends BasePayload | Array<BasePayload> = BasePayload, | |
> = { | |
data: DataShape; | |
} & (DataShape extends Array<any> ? Pagination : null) & | |
(BasePayload extends Partial<{ [k in StatsKeys]: number }> | |
? PartialStats<BasePayload> | |
: null); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment