Skip to content

Instantly share code, notes, and snippets.

@shreyakupadhyay
Created December 29, 2022 05:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shreyakupadhyay/1df71c86533500620170f192963902cd to your computer and use it in GitHub Desktop.
Save shreyakupadhyay/1df71c86533500620170f192963902cd to your computer and use it in GitHub Desktop.
Advanced level typescript implementation of API response handling
<!-- 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