Skip to content

LynqChat.jsを利用する ​

LynqChat.jsはLynqChat公式のJavaScript/TypeScript SDKで、LynqChat内部でも実際に使用されており、完全に型が定義されています。
インストールするには以下のコマンドを実行します。

npm config set @last2014:registry https://gitea.last2014.com/api/packages/last2014/npm/
npm add @last2014/lynqchat-js
yarn config set "@last2014:registry" "https://gitea.last2014.com/api/packages/last2014/npm/"
yarn add @last2014/lynqchat-js
yarn config set npmScopes.last2014.npmRegistryServer "https://gitea.last2014.com/api/packages/last2014/npm/"
yarn add @last2014/lynqchat-js
pnpm config set @last2014:registry https://gitea.last2014.com/api/packages/last2014/npm/
pnpm add @last2014/lynqchat-js

クライアントの初期化 ​

import LynqChat from "@last2014/lynqchat-js";
import type ApiMap from "@last2014/lynqchat-js/map";

const client = new LynqChat<ApiMap>({
  origin: window.origin, // 多くのBotなどはwindowが存在しないランタイムのため、サーバーのオリジンをハードコードなどしてください。
});

client.token = "YOUR_API_TOKEN"; // トークンを設定します。

HTTP APIのリクエスト ​

import LynqChat from "@last2014/lynqchat-js";
import type ApiMap from "@last2014/lynqchat-js/map";

const client = new LynqChat<ApiMap>({
  origin: window.origin, // 多くのBotなどはwindowが存在しないランタイムのため、サーバーのオリジンをハードコードなどしてください。
  retry: 3, // 再試行する回数 このプロパティは任意でデフォルトは3です。
  waiting: 350, // 再試行までの原則(指数関数的バックオフされます)の待機時間 このプロパティは任意でデフォルトは350です。
});

client.token = "YOUR_API_TOKEN"; // トークンを設定します。

try {
  const me = await client.request("me"); // meエンドポイントからの応答
  console.log(JSON.stringify(me, null, 2)); // meの応答を出力

  // bodyを指定することもできます。
  // bodyが必要ない、または任意の場合はmeエンドポイントのように不要です。。
  const profileEditResult = await client.request("me/edit/profile", {
    username: "Test",
    isBot: true, 
  }); // me/edit/profileエンドポイントからの応答
  console.log(JSON.stringify(profileEditResult, null, 2)); // me/edit/profileの応答を出力
} catch (err) {
  console.error(err); // JSON以外のレスポンスやNetwork errorなどがthrowされます。LynqChatサーバーからのエラーはthrowされません。
}

トークンが無効だった場合のハンドル ​

LynqChatサーバーからトークンが無効だと受け取った場合にハンドルすることができます。
LynqChat内部では他の端末からサインアウトさせられたとして扱います。

📝メモ

client.request自体は動作します。
追加でハンドルすることができる機能であり、トークンが無効だった際にclient.requestを停止する機能ではありません。

import LynqChat from "@last2014/lynqchat-js";
import type ApiMap from "@last2014/lynqchat-js/map";

const client = new LynqChat<ApiMap>({
  origin: window.origin, // 多くのBotなどはwindowが存在しないランタイムのため、サーバーのオリジンをハードコードなどしてください。
  retry: 3, // 再試行する回数 このプロパティは任意でデフォルトは3です。
  waiting: 350, // 再試行までの原則(指数関数的バックオフされます)の待機時間 このプロパティは任意でデフォルトは350です。
});

client.token = "YOUR_API_TOKEN"; // トークンを設定します。

client.addEventListener("token_invalid", async () => {
  alert("トークンが無効になりました。");
  window.location.href = "/signin"; // 例としてサインインページにリダイレクトします。
});