Created
June 16, 2022 10:55
-
-
Save SuperstrongBE/e90d083ff05c2b1a81e67dad28a76e2b to your computer and use it in GitHub Desktop.
A abstraction wrapper of the proton SDK with helpers function
This file contains 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
import { Api, JsonRpc, RpcError, JsSignatureProvider } from '@proton/js'; | |
import { | |
GetAccountResult, | |
GetTableRowsResult, | |
} from '@proton/js/dist/rpc/types'; | |
export class ProtonRPC { | |
public rpc: JsonRpc; | |
public api: Api; | |
constructor() { | |
this.rpc = new JsonRpc(process.env.NEXT_PUBLIC_SDK_ENDPOINTS!.split(',')); | |
this.api = new Api({ | |
rpc: this.rpc, | |
}); | |
} | |
/** | |
* An abstract to fetch account | |
* @param accountName | |
* @returns GetAccountResult | ProtonRPCError | |
*/ | |
async getAccount(accountName: string): Promise<GetAccountResult | null> { | |
try { | |
const account = await this.rpc.get_account(accountName); | |
if (!account || !account.ram_quota) { | |
// return <ProtonRPCError>{ message: 'Unable to find account' }; | |
return null; | |
} | |
return account; | |
} catch (err) { | |
// return <ProtonRPCError>{ message: 'Error while fetching the account' }; | |
return null; | |
} | |
} | |
async getAccountRam(accountName: string) { | |
try { | |
const account = await this.getAccount(accountName); | |
if (!account || !(account as GetAccountResult).ram_quota) { | |
throw new Error('Unable to find account.'); | |
} | |
return { | |
used: (account as GetAccountResult).ram_usage, | |
max: (account as GetAccountResult).ram_quota, | |
percent: | |
(Number((account as GetAccountResult).ram_usage) / | |
Number((account as GetAccountResult).ram_quota)) * | |
100, | |
}; | |
} catch (err) { | |
console.warn(err); | |
return { | |
used: 0, | |
max: 0, | |
percent: 0, | |
}; | |
} | |
} | |
async getTableRows( | |
params: ProtonTableParams, | |
): Promise<GetTableRowsResult | ProtonRPCError> { | |
try { | |
const res = await this.rpc.get_table_rows({ | |
...params, | |
}); | |
return res; | |
} catch (err) { | |
return <ProtonRPCError>{ message: 'Error while fetching data' }; | |
} | |
} | |
} | |
declare interface ProtonRPCError { | |
message: string; | |
} | |
declare interface ProtonTableParams { | |
json?: boolean; | |
code: string; | |
scope: string; | |
table: string; | |
lower_bound?: string; | |
upper_bound?: string; | |
limit?: number; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment