createUserProfile method

Future<UserProfileModel> createUserProfile(
  1. Session session,
  2. UuidValue authUserId,
  3. UserProfileData userProfile, {
  4. Transaction? transaction,
  5. UserImageSource? imageSource,
})

Creates a new user profile and stores it in the database.

If an imageSource is provided, it will be set on the user profile. Setting the image is a best-effort operation and may fail if the image cannot be fetched or stored. In case of a failure, the user profile is still created without an image. Failures can be handled inside the UserProfileConfig.onAfterUserProfileCreated callback.

Implementation

Future<UserProfileModel> createUserProfile(
  final Session session,
  final UuidValue authUserId,
  UserProfileData userProfile, {
  final Transaction? transaction,
  final UserImageSource? imageSource,
}) async {
  return DatabaseUtil.runInTransactionOrSavepoint(
    session.db,
    transaction,
    (final transaction) async {
      final onBeforeUserProfileCreated = config.onBeforeUserProfileCreated;
      if (onBeforeUserProfileCreated != null) {
        userProfile = await onBeforeUserProfileCreated(
          session,
          authUserId,
          userProfile,
          transaction: transaction,
        );
      }

      userProfile = userProfile.copyWith(
        email: userProfile.email?.toLowerCase().trim(),
      );

      final createdProfile = await UserProfile.db.insertRow(
        session,
        UserProfile(
          authUserId: authUserId,
          userName: userProfile.userName,
          fullName: userProfile.fullName,
          email: userProfile.email,
        ),
        transaction: transaction,
      );

      UserProfileModel? createdProfileModel;
      if (imageSource != null) {
        try {
          createdProfileModel = await _setUserImage(
            session,
            authUserId,
            imageSource,
            transaction: transaction,
          );
        } catch (e, stackTrace) {
          session.log(
            'Failed to set user profile image during profile creation.',
            level: LogLevel.error,
            exception: e,
            stackTrace: stackTrace,
          );
        }
      }
      createdProfileModel ??= createdProfile.toModel();

      await config.onAfterUserProfileCreated?.call(
        session,
        createdProfileModel,
        transaction: transaction,
      );

      return createdProfileModel;
    },
  );
}