private buildUseAuthenticatedUserStatement()

in packages/codegen-ui-react/lib/react-studio-template-renderer.ts [546:600]


  private buildUseAuthenticatedUserStatement(component: StudioComponent): Statement | undefined {
    if (isStudioComponentWithBinding(component)) {
      const authPropertyBindings = Object.entries(component.bindingProperties).filter(([, binding]) =>
        isAuthPropertyBinding(binding),
      );
      if (authPropertyBindings.length) {
        // create destructuring statements
        // { propertyName: newName, ['custom:property']: customProperty }
        const bindings = factory.createObjectBindingPattern(
          authPropertyBindings.map(([propName, binding]) => {
            const {
              bindingProperties: { userAttribute },
            } = binding as StudioComponentAuthPropertyBinding;
            let propertyName: undefined | Identifier | ComputedPropertyName = factory.createIdentifier(userAttribute);
            if (userAttribute.startsWith('custom:')) {
              propertyName = factory.createComputedPropertyName(factory.createStringLiteral(userAttribute));
            } else if (propName === userAttribute) {
              propertyName = undefined;
            }
            return factory.createBindingElement(undefined, propertyName, factory.createIdentifier(propName), undefined);
          }),
        );

        // get values from useAuthenticatedUser
        // const { property } = useAuth().user?.attributes || {};
        return factory.createVariableStatement(
          undefined,
          factory.createVariableDeclarationList(
            [
              factory.createVariableDeclaration(
                bindings,
                undefined,
                undefined,
                factory.createBinaryExpression(
                  factory.createPropertyAccessChain(
                    factory.createPropertyAccessExpression(
                      factory.createCallExpression(factory.createIdentifier('useAuth'), undefined, []),
                      factory.createIdentifier('user'),
                    ),
                    factory.createToken(ts.SyntaxKind.QuestionDotToken),
                    factory.createIdentifier('attributes'),
                  ),
                  factory.createToken(ts.SyntaxKind.QuestionQuestionToken),
                  factory.createObjectLiteralExpression([], false),
                ),
              ),
            ],
            ts.NodeFlags.Const,
          ),
        );
      }
    }

    return undefined;
  }