createLink method

Future<CreateLinkResult> createLink(
  1. CreateLinkOptions options
)

Creates a new short link programmatically based on the provided options.

This feature requires an apiKey to be configured in the LinkFortyConfig. As per the specification, a CreateLinkOptions.templateId is mandatory.

Returns a CreateLinkResult containing the generated URL and metadata.

Throws NotInitializedError if the SDK is not initialized. Throws MissingApiKeyError if no API key is available. Throws MissingTemplateIdError if no template ID is provided in options.

Implementation

Future<CreateLinkResult> createLink(CreateLinkOptions options) async {
  if (!_isInitialized) {
    throw const NotInitializedError();
  }

  final config = _config;
  if (config == null) {
    throw const NotInitializedError();
  }

  if (config.apiKey == null) {
    throw const MissingApiKeyError();
  }

  if (options.templateId == null) {
    throw const MissingTemplateIdError();
  }

  final networkManager = _networkManager;
  if (networkManager == null) {
    throw const NotInitializedError();
  }

  final response = await networkManager.request<DashboardCreateLinkResponse>(
    endpoint: '/api/links',
    method: HttpMethod.post,
    body: options.toJson(),
    fromJson: (json) => DashboardCreateLinkResponse.fromJson(json),
  );

  final baseUrl = config.baseURL.toString().replaceAll(RegExp(r'/$'), '');
  final templateSlug = options.templateSlug ?? '';
  final pathSegment = templateSlug.isEmpty
      ? response.shortCode
      : '$templateSlug/${response.shortCode}';
  final url = '$baseUrl/$pathSegment';

  return CreateLinkResult(
    url: url,
    shortCode: response.shortCode,
    linkId: response.id,
  );
}