Skip to content

Contextual state shared across encode/decode #98

@grantila

Description

@grantila

I need to pass state to the extension codecs, to be able to decode values properly. The decoding needs state to be able to construct the JavaScript values. It would be very cumbersome to rewrite the code to wrap all the decoding in a super function just to be able to capture the state, and it would mean overhead.

Would it be possible to add a custom field in DecodeOptions and add an optional second argument to encode()/decode() (and the siblings) so that you could pass a state through?

E.g.:

const ctx = { // This is my local context
	session, // I have multiple sessions, and they "hold"/own encodable variables
};

const extensionCodec = new ExtensionCodec< typeof ctx >( );
extensionCodec.register( {
	type: 0,
	// In my case, encoding doesn't need ctx...
	encode( input, ctx ) {
		if ( input instanceof Foo )
			return input.encode( );
		else
			return null;
	},
	// But decode needs ctx to know where to "attach" Foo
	decode( input, ctx ) {
		const foo = Foo.decode( input );
		ctx.session.registerFoo( foo ); // <-- like so
		return foo;
	}
} );

decode( buf, { extensionCodec, ctx } );

Would you be interested in implementing this, or should I start doing it myself and provide a PR?

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions