function deconstructType()

in src/declarative-stack.ts [284:323]


function deconstructType(stack: cdk.Stack, typeRef: reflect.TypeReference, value: any) {
  const schemaDefs: any = {};
  const ctx = SchemaContext.root(schemaDefs);
  const schemaRef = schemaForPolymorphic(typeRef.type, ctx);
  if (!schemaRef) {
    return undefined;
  }

  const def = findDefinition(schemaDefs, schemaRef.$ref);

  const keys = Object.keys(value);
  if (keys.length !== 1) {
    throw new ValidationError(`Cannot parse class type ${typeRef} with value ${value}`);
  }

  const className = keys[0];

  // now we need to check if it's an enum or a normal class
  const schema = def.anyOf.find((x: any) => x.properties && x.properties[className]);
  if (!schema) {
    throw new ValidationError(`Cannot find schema for ${className}`);
  }

  const def2 = findDefinition(schemaDefs, schema.properties[className].$ref);
  const methodFqn = def2.comment;

  const parts = methodFqn.split('.');
  const last = parts[parts.length - 1];
  if (last !== '<initializer>') {
    throw new Error('Expectring an initializer');
  }

  const classFqn = parts.slice(0, parts.length - 1).join('.');
  const method = typeRef.system.findClass(classFqn).initializer;
  if (!method) {
    throw new Error(`Cannot find the initializer for ${classFqn}`);
  }

  return invokeMethod(stack, method, value[className]);
}