-
Notifications
You must be signed in to change notification settings - Fork 19
Description
I'm trying to encode objects which may contain undefined values into DAG-CBOR.
The approach I tried was to copy the Object implementation but there is an issue: objectToTokens and sortMapEntries are not exported by the module, so we basically have to re-implement the whole encoder logic, which is not really suitable. Note that we could also mutate the object in place (and return null to let the default handler do the job) but I don't want to be altering user provided data as this could lead to unexpected behaviors.
Would it be possible to either:
- Add a dedicated option (like
stripUndefinedObjectValuesorfilterObjectEntries: (key, value) => boolean) ? - Expose
objectToTokensandsortMapEntriesas part of the public API of the package ? - Have the ability to return some kind of "ignore" token from custom type encoders (e.g.
undefined: () => Token.ignore) and have the default Object encoder skip these entries ? - Use a special Error that can be thrown when encoding nested values, resulting in them being ignored ?
- Other ?
The use case for us (at @bluesky-social ) is to be able to encode values generated using typescript code, into DAG_CBOR. TS allows to assign undefined to optional properties, requiring us to manually pre-process object in order to strip undefined values.
I'd basically want to be able to do:
type Foo = { bar ?: string }
const foo: Foo = {
bar: undefined // "legal" in typescript
}
const options = {
typeEncoders: {
undefined: () => {
throw new Error('Undefined is not allowed in DAG-CBOR')
}
}
}
// I want this to silently ignore the undefined property somehow.
const encoded = encode(foo, options)
// Works but is quite slow
encode(stripUndefineds(foo), options)
// These should still result in an error
encode(undefined, options)
encode([undefined], options)
encode({x:[undefined]}, options)