JUMBO refactor, still work in progress
This commit is contained in:
35
packages/common/src/Cbor.ts
Normal file
35
packages/common/src/Cbor.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
import * as cbor from "cbor2";
|
||||
import { Data, Effect, pipe, Schema } from "effect";
|
||||
|
||||
export class CborDecodeError extends Data.TaggedError("CborDecodeError")<{ cause: unknown }> { }
|
||||
export class CborEncodeError extends Data.TaggedError("CborEncodeError")<{ cause: unknown }> { }
|
||||
|
||||
export function encode(u: unknown): Effect.Effect<Uint8Array, CborEncodeError> {
|
||||
return Effect.try({
|
||||
try: () => cbor.encode(u),
|
||||
catch: (cause) => new CborEncodeError({ cause }),
|
||||
});
|
||||
}
|
||||
|
||||
export function decode(u: Uint8Array): Effect.Effect<unknown, CborDecodeError> {
|
||||
return Effect.try({
|
||||
try: () => cbor.decode(u),
|
||||
catch: (cause) => new CborDecodeError({ cause }),
|
||||
});
|
||||
}
|
||||
|
||||
export const encodeSchema = <A, I>(schema: Schema.Schema<A, I>) => {
|
||||
const schemaEncoder = Schema.encode(schema);
|
||||
return (a: A) => pipe(
|
||||
schemaEncoder(a),
|
||||
Effect.flatMap((i) => encode(i)),
|
||||
);
|
||||
};
|
||||
|
||||
export const decodeSchema = <A>(schema: Schema.Schema<A, any>) => {
|
||||
const schemaDecoder = Schema.decodeUnknown(schema);
|
||||
return (u: Uint8Array) => pipe(
|
||||
decode(u),
|
||||
Effect.flatMap((u) => schemaDecoder(u)),
|
||||
);
|
||||
};
|
||||
Reference in New Issue
Block a user