aboutsummaryrefslogtreecommitdiff
path: root/packages/taler-util/src/codec.ts
diff options
context:
space:
mode:
Diffstat (limited to 'packages/taler-util/src/codec.ts')
-rw-r--r--packages/taler-util/src/codec.ts33
1 files changed, 28 insertions, 5 deletions
diff --git a/packages/taler-util/src/codec.ts b/packages/taler-util/src/codec.ts
index b04ce0612..cd727a792 100644
--- a/packages/taler-util/src/codec.ts
+++ b/packages/taler-util/src/codec.ts
@@ -83,6 +83,7 @@ interface Alternative {
class ObjectCodecBuilder<OutputType, PartialOutputType> {
private propList: Prop[] = [];
+ private _allowExtra: boolean = false;
/**
* Define a property for the object.
@@ -98,6 +99,11 @@ class ObjectCodecBuilder<OutputType, PartialOutputType> {
return this as any;
}
+ allowExtra(): ObjectCodecBuilder<OutputType, PartialOutputType> {
+ this._allowExtra = true;
+ return this;
+ }
+
/**
* Return the built codec.
*
@@ -106,6 +112,7 @@ class ObjectCodecBuilder<OutputType, PartialOutputType> {
*/
build(objectDisplayName: string): Codec<PartialOutputType> {
const propList = this.propList;
+ const allowExtra = this._allowExtra;
return {
decode(x: any, c?: Context): PartialOutputType {
if (!c) {
@@ -129,6 +136,20 @@ class ObjectCodecBuilder<OutputType, PartialOutputType> {
);
obj[prop.name] = propVal;
}
+ for (const prop in x) {
+ if (prop in obj) {
+ continue;
+ }
+ if (allowExtra) {
+ obj[prop] = x[prop];
+ } else {
+ logger.warn(
+ `Extra property ${prop} for ${objectDisplayName} at ${renderContext(
+ c,
+ )}`,
+ );
+ }
+ }
return obj as PartialOutputType;
},
};
@@ -146,7 +167,7 @@ class UnionCodecBuilder<
constructor(
private discriminator: TagPropertyLabel,
private baseCodec?: Codec<CommonBaseType>,
- ) { }
+ ) {}
/**
* Define a property for the object.
@@ -491,7 +512,10 @@ export function codecOptional<V>(innerCodec: Codec<V>): Codec<V | undefined> {
};
}
-export function codecOptionalDefault<V>(innerCodec: Codec<V>, def: V): Codec<V> {
+export function codecOptionalDefault<V>(
+ innerCodec: Codec<V>,
+ def: V,
+): Codec<V> {
return {
decode(x: any, c?: Context): V {
if (x === undefined || x === null) {
@@ -503,18 +527,17 @@ export function codecOptionalDefault<V>(innerCodec: Codec<V>, def: V): Codec<V>
}
export function codecForLazy<V>(innerCodec: () => Codec<V>): Codec<V> {
- let instance: Codec<V> | undefined = undefined
+ let instance: Codec<V> | undefined = undefined;
return {
decode(x: any, c?: Context): V {
if (instance === undefined) {
- instance = innerCodec()
+ instance = innerCodec();
}
return instance.decode(x, c);
},
};
}
-
export type CodecType<T> = T extends Codec<infer X> ? X : any;
export function codecForEither<T extends Array<Codec<unknown>>>(