0.0.0 • Published 3 months ago

rx-xtra.safe-map v0.0.0

Weekly downloads
-
License
ISC
Repository
github
Last release
3 months ago

Rx Xtra: SafeMap

safeMap allows you to perform data validation and conversion with one operator. Great for use with JSON.parse and Zod.

If the validation / conversion throws an error, then the emitted signal is ignored, but the Observable continues.

rx-xtra.safe-map is part of Rx Xtra, a collection of RxJS utilities.

Created by Joel Shinness LinkTreeGithubBuy me a coffee!

Usage

safeMap<A, B>

  • Parameters
    • project: (value:A, index:number) => B converts a value of type A into a value of type B. If this function throws an error, then the item is ignored.
    • onError: (err:any) => void gets called with the validation error if one exists. If this function throws an error, then the entire Observable errors.
  • Returns
import { from } from 'rxjs';
import { z } from 'zod';
import { safeMap } from 'rx-xtra.safe-map';

const data = [
  'Not JSON',
  '{"error": "invalid JSON"}',
  '{"msg": "Valid Object"}',
];

const template = z.object({
  'msg': z.string()
});

function validate(input:string):z.infer<typeof template>{
  const parsedJSON = JSON.parse(input);
  const validObject = template.parse(parsedJSON);
  return validObject;
}

from(data).pipe(
  safeMap(
    validate, 
    (err) => { console.log('Validation Error:', err.message); 
  })
).subscribe((val) => { console.log('Next:', val.msg); });

// OUTPUT:
// Validation Error: Unexpected token 'N', "Not JSON" is not valid JSON
// Validation Error: [
//   {
//     "code": "invalid_type",
//     "expected": "string",
//     "received": "undefined",
//     "path": [
//       "msg"
//     ],
//     "message": "Required"
//   }
// ]
// Next: Valid Object