ethers.js/src.ts/utils/properties.ts

61 lines
1.7 KiB
TypeScript
Raw Normal View History

2022-11-28 05:50:34 +03:00
/**
* Property helper functions.
*
2022-12-03 05:23:13 +03:00
* @_subsection api/utils:Properties [about-properties]
2022-11-28 05:50:34 +03:00
*/
function checkType(value: any, type: string, name: string): void {
2022-09-05 23:14:43 +03:00
const types = type.split("|").map(t => t.trim());
for (let i = 0; i < types.length; i++) {
switch (type) {
case "any":
return;
2022-11-28 05:50:34 +03:00
case "bigint":
2022-09-05 23:14:43 +03:00
case "boolean":
case "number":
case "string":
if (typeof(value) === type) { return; }
}
}
2022-11-28 05:50:34 +03:00
const error: any = new Error(`invalid value for type ${ type }`);
error.code = "INVALID_ARGUMENT";
error.argument = `value.${ name }`;
error.value = value;
throw error;
2022-09-05 23:14:43 +03:00
}
2022-12-03 05:23:13 +03:00
/**
* Resolves to a new object that is a copy of %%value%%, but with all
* values resolved.
*/
export async function resolveProperties<T>(value: { [ P in keyof T ]: T[P] | Promise<T[P]>}): Promise<T> {
const keys = Object.keys(value);
const results = await Promise.all(keys.map((k) => Promise.resolve(value[<keyof T>k])));
return results.reduce((accum: any, v, index) => {
accum[keys[index]] = v;
return accum;
}, <{ [ P in keyof T]: T[P] }>{ });
}
2022-11-28 05:50:34 +03:00
/**
* Assigns the %%values%% to %%target%% as read-only values.
*
* It %%types%% is specified, the values are checked.
*/
2022-09-05 23:14:43 +03:00
export function defineProperties<T>(
target: T,
2022-11-28 05:50:34 +03:00
values: { [ K in keyof T ]?: T[K] },
types?: { [ K in keyof T ]?: string }): void {
2022-09-05 23:14:43 +03:00
for (let key in values) {
let value = values[key];
2022-11-28 05:50:34 +03:00
const type = (types ? types[key]: null);
if (type) { checkType(value, type, key); }
2022-09-05 23:14:43 +03:00
Object.defineProperty(target, key, { enumerable: true, value, writable: false });
}
}