npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@itd-api/hydrate

v0.1.0

Published

Методы действий на моделях и уведомлениях itd-api

Readme

@itd-api/hydrate

Методы действий прямо на моделях itd-api: постах, комментариях, пользователях, вложениях и уведомлениях REST/realtime.

Руководство · API из TSDoc

Установка

npm install itd-api @itd-api/hydrate

Поддерживается itd-api >=0.5.0 <1.0.0.

Использование

import { ItdClient } from 'itd-api';
import { hydrateClient } from '@itd-api/hydrate';

const itd = hydrateClient(new ItdClient({ auth: token }));

const post = await itd.posts.get(postId);
await post.like();

const comment = await post.comment('Согласен');
await comment.reply('Дополню мысль');

const profile = await post.author.get();
const wall = await profile.posts({ limit: 20 });

Тип результата выводится автоматически. Для собственного типа клиента можно явно применить HydrateFlavor:

import type { ItdClient } from 'itd-api';
import type { HydrateFlavor } from '@itd-api/hydrate';

type AppClient = HydrateFlavor<ItdClient>;

Методы моделей

| Модель | Методы | |---|---| | пост | get(), like(), unlike(), comment(), repost(), remove(), restore(), pin(), unpin() | | комментарий | like(), unlike(), reply(), update(), remove(), restore(), getReplies() | | автор, профиль, пользователь из списка или уведомления | get(), follow(), unfollow(), block(), unblock(), posts() | | вложение | isImage(), isVideo(), isAudio() | | уведомление | getPost(), comment |

getReplies() загружает полную страницу ответов. Поле comment.replies по-прежнему содержит предварительно загруженные ответы из исходной модели. Проверки вложений одновременно сужают поле type в TypeScript.

Страницы, вложенные модели, Paginator.next(), Paginator.pages(), collect() и асинхронный перебор гидратируются автоматически:

for await (const post of itd.posts.iterate({ limit: 20 })) {
  if (!post.isLiked) await post.like();
}

Realtime

Нормализованные уведомления из realtime получают те же методы, что и результаты REST API:

import { NotificationType } from 'itd-api';

const stream = itd.realtime();

stream.onNotification(
  [
    NotificationType.Follow,
    NotificationType.PostComment,
    NotificationType.WallPost,
  ],
  async ({ update }) => {
    const notification = update.data.notification;

    switch (notification.type) {
      case NotificationType.Follow:
        await notification.actors[0]?.follow();
        break;
      case NotificationType.PostComment:
        await notification.comment?.reply((comment) =>
          comment.content('Спасибо за комментарий'),
        );
        break;
      case NotificationType.WallPost:
        await (await notification.getPost())?.like();
        break;
    }
  },
);

await stream.connect();

getPost() возвращает связанный пост для событий о постах и комментариях. Поле comment содержит ссылку на комментарий и поддерживает действия reply(), like(), unlike(), update(), remove(), restore() и getReplies(). Для остальных видов уведомлений эти связанные сущности отсутствуют.

Гидратированный контекст передаётся в sequentialize, use(), onUpdate(), onNotification() и обработчики нормализованных событий. Событие message и поле raw сохраняют исходные данные транспорта.

Методы моделей используют ресурсы исходного клиента. Опции запроса, авторизация, очередь, повторы и подключённые плагины применяются как при прямом вызове ресурса.

Добавленные методы не перечисляются в Object.keys() и не попадают в JSON.