createThreadFromMessage method

JsonMap createThreadFromMessage(
  1. String principalId,
  2. String channelId,
  3. JsonMap body
)

createThread with parent_message_id: a thread from a message of the main thread of a text channel, titled from the message (title_source = auto), with an optional first message. Returns the API ThreadCreated.

Implementation

JsonMap createThreadFromMessage(
  String principalId,
  String channelId,
  JsonMap body,
) {
  final channel = channels[channelId];
  if (channel == null || !seesChannel(principalId, channelId)) {
    throw const FakeProblem(404, 'not_found');
  }
  if (channel.access[principalId] == 'read') {
    throw const FakeProblem(403, 'forbidden');
  }
  final parentId = body['parent_message_id']! as String;
  final parent = messages[parentId];
  if (parent == null ||
      parent['thread_id'] != channel.json['main_thread_id'] ||
      threads.values.any((t) => t['parent_message_id'] == parentId)) {
    throw const FakeProblem(
      400,
      'validation_failed',
      errors: [
        {'pointer': '/parent_message_id', 'code': 'invalid_parent'},
      ],
    );
  }
  final text = (parent['content_md']! as String).trim();
  final title = (body['title'] as String?)?.trim().isNotEmpty ?? false
      ? (body['title']! as String).trim()
      : text.isEmpty
      ? 'Thread'
      : text.split('\n').first;
  final id = addThread(channelId, title, createdBy: principalId);
  final thread = threads[id]!
    ..['parent_message_id'] = parentId
    ..['title_source'] = body['title'] == null ? 'auto' : 'manual';
  append(
    'thread.created',
    resource: {'kind': 'thread', 'id': id, 'version': thread['version']},
    scope: _scopeOf(id),
    payload: {'thread': thread},
    actor: principalId,
  );
  final first = body['first_message'] as JsonMap?;
  final message = first == null
      ? null
      : createMessage(principalId, id, first).message;
  return {'thread': thread, 'first_message': ?message};
}