Skip to content

Commit 483af13

Browse files
committed
handle optional properties
1 parent bb94bc6 commit 483af13

File tree

1 file changed

+13
-5
lines changed

1 file changed

+13
-5
lines changed

packages/hypergraph/src/entity/entity.ts

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -50,10 +50,14 @@ export function encodeToGrc20Json<T extends object, E>(schema: Schema.Schema<T,
5050
const out: Record<string, unknown> = {};
5151

5252
for (const prop of ast.propertySignatures) {
53-
// TODO: what about optional properties here? usually we use prop.type.types[0] but we don't here?
54-
const result = SchemaAST.getAnnotation<string>(PropertyIdSymbol)(prop.type);
55-
if (Option.isSome(result)) {
56-
out[result.value] = (value as any)[prop.name];
53+
const propType =
54+
prop.isOptional && SchemaAST.isUnion(prop.type)
55+
? (prop.type.types.find((member) => !SchemaAST.isUndefinedKeyword(member)) ?? prop.type)
56+
: prop.type;
57+
const result = SchemaAST.getAnnotation<string>(PropertyIdSymbol)(propType);
58+
const propertyValue: any = (value as any)[prop.name];
59+
if (Option.isSome(result) && propertyValue !== undefined) {
60+
out[result.value] = propertyValue;
5761
}
5862
}
5963

@@ -71,7 +75,11 @@ export function decodeFromGrc20Json<T extends object, E>(
7175
const out: Record<string, unknown> = {};
7276

7377
for (const prop of ast.propertySignatures) {
74-
const result = SchemaAST.getAnnotation<string>(PropertyIdSymbol)(prop.type);
78+
const propType =
79+
prop.isOptional && SchemaAST.isUnion(prop.type)
80+
? (prop.type.types.find((member) => !SchemaAST.isUndefinedKeyword(member)) ?? prop.type)
81+
: prop.type;
82+
const result = SchemaAST.getAnnotation<string>(PropertyIdSymbol)(propType);
7583
if (Option.isSome(result)) {
7684
const grc20Key = result.value;
7785
if (grc20Key in grc20Data && typeof prop.name === 'string') {

0 commit comments

Comments
 (0)