(value: unknown, type: ResponseType)
| 96 | } |
| 97 | |
| 98 | export function castValue(value: unknown, type: ResponseType): ValueType { |
| 99 | if (!isValidType(type)) throw new Error(`Invalid type: ${type}`); |
| 100 | |
| 101 | if (isNumericType(type)) { |
| 102 | const goCast = goSync(() => castNumber(value)); |
| 103 | if (!goCast.success) throw new Error(`Unable to cast value to ${type}`); |
| 104 | |
| 105 | return goCast.data; |
| 106 | } |
| 107 | |
| 108 | const parsedArrayType = parseArrayType(type); |
| 109 | if (parsedArrayType) { |
| 110 | const goApplyToArrayRecursively = goSync(() => applyToArrayRecursively(value, parsedArrayType, castNumber)); |
| 111 | if (!goApplyToArrayRecursively.success) throw new Error(`Unable to cast value to ${type}`); |
| 112 | |
| 113 | return goApplyToArrayRecursively.data as ValueType; |
| 114 | } |
| 115 | |
| 116 | switch (type) { |
| 117 | case 'bool': { |
| 118 | const goCast = goSync(() => castBoolean(value)); |
| 119 | if (!goCast.success) throw new Error(`Unable to cast value to ${type}`); |
| 120 | |
| 121 | return goCast.data; |
| 122 | } |
| 123 | case 'bytes32': { |
| 124 | const goCast = goSync(() => castBytesLike(value)); |
| 125 | if (!goCast.success) throw new Error(`Unable to cast value to ${type}`); |
| 126 | |
| 127 | return goCast.data; |
| 128 | } |
| 129 | case 'string': { |
| 130 | const goCast = goSync(() => castString(value)); |
| 131 | if (!goCast.success) throw new Error(`Unable to cast value to ${type}`); |
| 132 | |
| 133 | return goCast.data; |
| 134 | } |
| 135 | case 'address': { |
| 136 | const goCast = goSync(() => castAddress(value)); |
| 137 | if (!goCast.success) throw new Error(`Unable to cast value to ${type}`); |
| 138 | |
| 139 | return goCast.data; |
| 140 | } |
| 141 | case 'bytes': { |
| 142 | const goCast = goSync(() => castBytesLike(value)); |
| 143 | if (!goCast.success) throw new Error(`Unable to cast value to ${type}`); |
| 144 | |
| 145 | return goCast.data; |
| 146 | } |
| 147 | case 'string32': { |
| 148 | const goCast = goSync(() => castString32(value)); |
| 149 | if (!goCast.success) throw new Error(`Unable to cast value to ${type}`); |
| 150 | |
| 151 | return goCast.data; |
| 152 | } |
| 153 | case 'timestamp': { |
| 154 | const goCast = goSync(createTimestamp); |
| 155 | if (!goCast.success) throw new Error(`Unable to cast value to ${type}`); |
no test coverage detected