const EntityReferenceInstanceSchema = Schema.instanceOf(EntityReference);
const encodedReferenceSchema = Schema.Struct({
type: Schema.Literal(config.type),
id: config.id.$schema,
});
const decodeReference = Schema.decodeUnknownEither(encodedReferenceSchema);
const referenceSchema = Schema.asSchema(Schema.transformOrFail(
Schema.Union(
EntityReferenceInstanceSchema,
encodedReferenceSchema,
),
EntityReferenceInstanceSchema,
{
encode(ref) {
return ParseResult.succeed({
type: ref.type,
id: ref.id,
});
},
decode(val) {
if (val instanceof EntityReference) {
// Validate the reference has the right type and ID
return Either.map(
decodeReference(val),
(decoded) => new EntityReference(decoded.type, decoded.id),
);
}
// Since val is now a raw object, it already has been validated at this point
return ParseResult.succeed(new EntityReference(val.type, val.id));
},
},
));
const EntityReferenceInstanceSchema = Schema.instanceOf(EntityReference);
const encodedReferenceSchema = Schema.Struct({
type: Schema.Literal(config.type),
id: config.id.$schema,
});
const decodeReference = Schema.decodeUnknownEither(encodedReferenceSchema);
const referenceSchema = Schema.asSchema(Schema.transformOrFail(
Schema.Union(
EntityReferenceInstanceSchema,
encodedReferenceSchema,
),
EntityReferenceInstanceSchema,
{
encode(ref) {
return ParseResult.succeed({
type: ref.type,
id: ref.id,
});
},
decode(val) {
if (val instanceof EntityReference) {
// Validate the reference has the right type and ID
return Either.map(
decodeReference(val),
(decoded) => new EntityReference(decoded.type, decoded.id),
);
}
// Since val is now a raw object, it already has been validated at this point
return ParseResult.succeed(new EntityReference(val.type, val.id));
},
},
));