1 |
|
2 |
|
3 | import { assert, u8aToU8a } from '@polkadot/util';
|
4 |
|
5 | export function createDecode({
|
6 | coder,
|
7 | ipfs
|
8 | }, validate) {
|
9 | return (value, ipfsCompat) => {
|
10 | validate(value, ipfsCompat);
|
11 | return coder.decode(ipfs && ipfsCompat ? value.substr(1) : value);
|
12 | };
|
13 | }
|
14 | export function createEncode({
|
15 | coder,
|
16 | ipfs
|
17 | }) {
|
18 | return (value, ipfsCompat) => {
|
19 | const out = coder.encode(u8aToU8a(value));
|
20 | return ipfs && ipfsCompat ? `${ipfs}${out}` : out;
|
21 | };
|
22 | }
|
23 | export function createIs(validate) {
|
24 | return (value, ipfsCompat) => {
|
25 | try {
|
26 | return validate(value, ipfsCompat);
|
27 | } catch (error) {
|
28 | return false;
|
29 | }
|
30 | };
|
31 | }
|
32 | export function createValidate({
|
33 | chars,
|
34 | ipfs,
|
35 | type
|
36 | }) {
|
37 | return (value, ipfsCompat) => {
|
38 | assert(value && typeof value === 'string', () => `Expected non-null, non-empty ${type} string input`);
|
39 |
|
40 | if (ipfs && ipfsCompat) {
|
41 | assert(value[0] === ipfs, () => `Expected ipfs-compatible ${type} to start with '${ipfs}'`);
|
42 | }
|
43 |
|
44 | for (let i = ipfsCompat ? 1 : 0; i < value.length; i++) {
|
45 | assert(chars.includes(value[i]) || value[i] === '=' && (i === value.length - 1 || !chars.includes(value[i + 1])), () => `Invalid ${type} character "${value[i]}" (0x${value.charCodeAt(i).toString(16)}) at index ${i}`);
|
46 | }
|
47 |
|
48 | return true;
|
49 | };
|
50 | } |
\ | No newline at end of file |