properties.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. /**
  2. * Property helper functions.
  3. *
  4. * @_subsection api/utils:Properties [about-properties]
  5. */
  6. function checkType(value, type, name) {
  7. const types = type.split("|").map(t => t.trim());
  8. for (let i = 0; i < types.length; i++) {
  9. switch (type) {
  10. case "any":
  11. return;
  12. case "bigint":
  13. case "boolean":
  14. case "number":
  15. case "string":
  16. if (typeof (value) === type) {
  17. return;
  18. }
  19. }
  20. }
  21. const error = new Error(`invalid value for type ${type}`);
  22. error.code = "INVALID_ARGUMENT";
  23. error.argument = `value.${name}`;
  24. error.value = value;
  25. throw error;
  26. }
  27. /**
  28. * Resolves to a new object that is a copy of %%value%%, but with all
  29. * values resolved.
  30. */
  31. export async function resolveProperties(value) {
  32. const keys = Object.keys(value);
  33. const results = await Promise.all(keys.map((k) => Promise.resolve(value[k])));
  34. return results.reduce((accum, v, index) => {
  35. accum[keys[index]] = v;
  36. return accum;
  37. }, {});
  38. }
  39. /**
  40. * Assigns the %%values%% to %%target%% as read-only values.
  41. *
  42. * It %%types%% is specified, the values are checked.
  43. */
  44. export function defineProperties(target, values, types) {
  45. for (let key in values) {
  46. let value = values[key];
  47. const type = (types ? types[key] : null);
  48. if (type) {
  49. checkType(value, type, key);
  50. }
  51. Object.defineProperty(target, key, { enumerable: true, value, writable: false });
  52. }
  53. }
  54. //# sourceMappingURL=properties.js.map