36 lines
1.1 KiB
TypeScript
36 lines
1.1 KiB
TypeScript
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<ArrayBuffer>, CborEncodeError> {
|
|
return Effect.try({
|
|
try: () => cbor.encode(u) as Uint8Array<ArrayBuffer>,
|
|
catch: (cause) => new CborEncodeError({ cause }),
|
|
});
|
|
}
|
|
|
|
export function decode(u: Uint8Array<ArrayBuffer>): 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<ArrayBuffer>) => pipe(
|
|
decode(u),
|
|
Effect.flatMap((u) => schemaDecoder(u)),
|
|
);
|
|
};
|