Content Modules

Reading and rendering comments

Aktualisiert am 230 Aufrufe

People can comment on your blog posts, help articles, changelog entries, pages, announcements and feedback posts. The SDK gives you those threads back so you can render them on your own site instead of sending readers to the Kookee portal.

Comments are read-only through the SDK. The public API exposes the list endpoint and nothing else — posting, editing and deleting happen in the Kookee dashboard and portal, signed in. There is no public write method, so nothing on this page can be used to submit a comment.

Where getComments() lives

Every module that can carry comments has the same method, and they all return the same shape:

TypeScript
await kookee.blog.getComments('entry-id');
await kookee.help.getComments('entry-id');
await kookee.changelog.getComments('entry-id');
await kookee.pages.getComments('entry-id');
await kookee.announcements.getComments('entry-id');

// The generic module, for any entry type
await kookee.entries.getComments('entry-id');

The module methods are thin wrappers around kookee.entries.getComments(), so they are interchangeable. Use whichever module you already have in hand.

The first argument is the entry id, not the slug. If you are working from a slug, fetch the entry first and pass its id:

TypeScript
const post = await kookee.blog.getBySlug('hello-world');
const comments = await kookee.blog.getComments(post.id);

Paging through a thread

The second argument is a pagination object — page and limit, nothing else:

TypeScript
const comments = await kookee.blog.getComments(post.id, { page: 1, limit: 20 });

page defaults to 1 and limit to 50. The server caps limit at 100; ask for more and the request is rejected. Comments come back oldest first, so page 1 is the start of the conversation.

You get the standard paginated envelope:

TypeScript
interface PaginatedResponse<T> {
  data: T[];
  total: number;
  limit: number;
  page: number;
  totalPages: number;
}

Which makes a "load more" button straightforward:

TypeScript
async function loadAllComments(entryId: string) {
  const all = [];
  let page = 1;

  for (;;) {
    const response = await kookee.blog.getComments(entryId, { page, limit: 100 });
    all.push(...response.data);
    if (page >= response.totalPages) return all;
    page += 1;
  }
}

The comment shape

TypeScript
interface EntryComment {
  id: string;
  content: JSONContent; // the rich-text document
  contentHtml: string; // the same thing, pre-rendered
  isOfficial: boolean;
  attachments: EntryCommentAttachment[];
  createdAt: string;
  updatedAt: string;
  author: EntryAuthor;
}

interface EntryAuthor {
  id: string;
  name: string | null;
  image: string | null;
  isTeamMember?: boolean;
}

Two fields carry the same text, and picking the right one is most of the work:

  • contentHtml is the comment already rendered to an HTML string. This is the fast path, and what you want in nearly every case.

  • content is the underlying rich-text document as JSON — a { type: 'doc', content: [...] } tree. Reach for it when you need to do something with the structure rather than display it: re-render through your own pipeline, strip it to plain text, count words, or load it back into an editor.

name and image are both nullable, so an author with neither still needs to render as something. Fall back to a label of your own.

Rendering a comment

The shortest path is contentHtml:

tsx
function Comments({ comments }: { comments: EntryComment[] }) {
  return (
    <ul>
      {comments.map((comment) => (
        <li key={comment.id}>
          <header>
            {comment.author.image && <img src={comment.author.image} alt="" width={32} height={32} />}
            <strong>{comment.author.name ?? 'Anonymous'}</strong>
            {comment.isOfficial && <span className="badge">Team</span>}
            <time dateTime={comment.createdAt}>{new Date(comment.createdAt).toLocaleDateString()}</time>
          </header>
          <div className="kookee-entry-content" dangerouslySetInnerHTML={{ __html: comment.contentHtml }} />
        </li>
      ))}
    </ul>
  );
}

Outside React it is the same idea:

JavaScript
const comments = await kookee.help.getComments(article.id);

for (const comment of comments.data) {
  const el = document.createElement('div');
  el.className = 'kookee-entry-content';
  el.innerHTML = comment.contentHtml;
  document.querySelector('#comments').append(el);
}

The HTML is generated by Kookee from the stored document, not passed through from whatever someone typed, so it holds the formatting the editor supports and nothing else. Both examples give the container the kookee-entry-content class: the SDK's content stylesheet is scoped to it, so code and file chips inside a comment are styled like the rest of your content.

Official replies

isOfficial is true when the comment was posted by an owner or admin of the project. It is stamped when the comment is written, so it reflects who that person was at the time — it does not shift if their role changes later. Use it for the "from the team" badge that separates your answer from the thread around it.

author.isTeamMember is a different thing, worked out fresh on every read: is this author a member of the project right now, at any role. A member who is not an owner or admin gets isTeamMember: true and isOfficial: false.

tsx
{comment.isOfficial && <span className="badge badge-official">Official reply</span>}
{!comment.isOfficial && comment.author.isTeamMember && <span className="badge">Staff</span>}

The type marks isTeamMember optional, so treat a missing value as false.

Comments are flat

There are no nested replies. A thread is a single ordered list, and a comment has no parent, no children and no depth. Render it as a list, not a tree — and if your design needs threading, you will have to build the convention yourself (an @-mention at the start of a reply, say) because the data does not carry it.

Attachments

A comment can have files attached:

TypeScript
interface EntryCommentAttachment {
  id: string;
  fileId: string;
  file: EntryCommentAttachmentFile;
  createdAt: string;
}

interface EntryCommentAttachmentFile {
  id: string;
  path: string;
  originalName: string;
  mimeType: string;
  size: number;
  public: boolean;
}

Images and file chips that the author placed inside the comment are already part of contentHtml, pointing at working URLs — you do not have to do anything for those to appear. The attachments array is the metadata list for the same files, which is what you want when you would rather show a separate "Attachments" strip under the comment body:

tsx
{comment.attachments.length > 0 && (
  <ul className="attachments">
    {comment.attachments.map((attachment) => (
      <li key={attachment.id}>
        {attachment.file.originalName}
        <span> · {Math.round(attachment.file.size / 1024)} KB</span>
      </li>
    ))}
  </ul>
)}

mimeType is the honest way to split images from everything else:

TypeScript
const images = comment.attachments.filter((a) => a.file.mimeType.startsWith('image/'));
const documents = comment.attachments.filter((a) => !a.file.mimeType.startsWith('image/'));

size is in bytes. path is the file's storage path rather than a ready-made link, and public says whether the file is publicly readable — so prefer the URLs already baked into contentHtml over trying to rebuild your own.

Feedback board comments

Comments on a feedback post work the same way, through the feedback module:

TypeScript
const post = await kookee.feedback.getById('post-uuid');
const comments = await kookee.feedback.getComments(post.id, { page: 1, limit: 20 });

The shape is the same idea under a different name:

TypeScript
interface FeedbackComment {
  id: string;
  content: JSONContent;
  contentHtml: string;
  attachments: FeedbackCommentAttachment[];
  createdAt: string;
  updatedAt: string;
  isOfficial: boolean;
  author: FeedbackAuthor;
}

contentHtml, isOfficial and attachments mean exactly what they mean above, and the attachment's file is the same EntryCommentAttachmentFile. A rendering component written for one will render the other, which is worth knowing if you show both on the same site. See Showing your feedback board in your app for the rest of the feedback API.

Comments have to be turned on first

Commenting is switched on per project and then per module, in your portal settings. The modules that can be enabled are the blog, changelog, help center, announcements and pages; the feedback board is governed by the feedback module instead.

Nothing can be posted while a module is off, so getComments() on it returns an empty page — data: [], total: 0 — rather than an error. That is the expected state for a project that has never enabled it, and not something to debug.

The switch controls posting, not reading. Turning it off later stops new comments, but comments already posted are still returned. If your UI hides the whole section when the setting is off, drive that from your own configuration — the SDK response looks the same either way.

Handling a slow or abandoned request

getComments() takes an AbortSignal as its last argument, after the pagination object, so a reader who navigates away mid-load does not leave a request running:

TypeScript
const controller = new AbortController();

kookee.blog.getComments(post.id, { limit: 20 }, controller.signal);

// The reader left
controller.abort();

An aborted request rejects with an AbortError, which is not a KookeeApiError — see The generic Entries module for the full rules on cancelling requests.

  • The generic Entries module — the same getComments() for every entry type, plus cancelling requests.

  • Rendering content and styling code blocks — how the rest of an entry's HTML is styled.

  • Showing your feedback board in your app — the feedback board these comments hang off.

  • Reactions, views and engagement data — the other signal readers leave on your content.

War dieser Artikel hilfreich?