Skip to content

war1oc/mlbd-chat-client

Repository files navigation

MLBD Chat Client

Javascript chat client for MLBD Chat Service.

Build Status

Usage

Installation

npm i @mlbd/chat-client

Initialization

Initialize the client:

import { ChatClient, TokenProvider, PusherProvider } from '@mlbd/chat-client'

const tokenProvider = new TokenProvider({
  // This is a POST request configuration for fetching chat token
  url: 'https://my-api/auth/chat',
  getHeaders: () => {
    // Optional
    // return a headers object your endpoint requires
    return Promise.resolve({ Authorization: 'Bearer <ACCESS_TOKEN>' })
  },
  getBody: () => {
    // Optional
    // return a body object your endpoint requires
    return Promise.resolve({ key: 'value' })
  },
})

const chatClient = new ChatClient({
  chatApiEndpoint: 'https://my-chat-api',
  tokenProvider: tokenProvider,
  pusherProvider: new PusherProvider({
    appKey: '<PUSHER_APP_KEY>',
    cluster: '<PUSHER_APP_CLUSTER>',
    forceTLS: true,
    authEndpoint: '<AUTH_END_POINT>',
    tokenProvider: tokenProvider,
  }),
})

Get my groups

const myGroups = await chatClient.getMyGroups()

Get group messages

const messages = await chatClient.getGroupMessages('<group_id>')

Send message to a group

// either message or attachments must be provided.
const messages = await chatClient.sendMessage({
  groupId: '<group_id>',
  message: 'hello, world!',
  attachments: [
    {
      title: 'Laika - the dog',
      mime_type: 'image/jpeg',
      url: 'https://domain/laika.jpeg',
    },
  ],
  parentMessageId: '<parent_message_id>',
  mentions: ['2', '3'],
})

If you want to send files to be uploaded and attached, send an array of files rather than attachments:

// either message or attachments must be provided.
const messages = await chatClient.sendMessage({
  groupId: "<group_id>",
  message: "hello, world!",
  files: File[],
  parentMessageId: "<parent_message_id>",
  mentions: ["2", "3"]
});

Get my stats

const stats = await chatClient.getMyStats()

Mark group as read

await chatClient.markGroupAsRead({ groupId: '<group_id>' })

Delete message

await chatClient.deleteMessage('<message_id>')

Get group

const group = await chatClient.getGroup('<group_id>')

Get message

const message = await chatClient.getMessage('<message_id>')

Search messages

const messages = await chatClient.searchMessages({
  keyword: '<search_keyword>',
  // groupId is optional, results will be filtered by group if this is passed
  groupId: '<group_id>',
  // limit is optional, default: 10
  limit: 5,
  // offset is optional, default: 0
  offset: 5,
})

limit and offset are to be used for pagination.

Get message history

const messages = await chatClient.getMessageHistory({
  // limit is optional, default: 10
  limit: 5,
  // optional, default: false
  // should the response include messages with latest or oldest set dates
  inclusive: true,
  // optional, date of the latest message to find
  latest: '<latest_date>',
  // optional, date of the oldest message to find
  oldest: '<oldest_date>',
  groupId: '<group_id>',
})

If latest and oldest both are provided or if none are provided, the latest message will be on the top of the response. This will also be the case if only latest date is provided.

If latest is not provided and only oldest is provided, the oldest message will be on the top of the response.

Get group attachments

const groupAttachments = await chatClient.getGroupAttachments('<group_id>', '<limit>', '<offset>')

Get attachment file detail

const attachmentDetail = await chatClient.getAttachmentFileDetail('<attachment_id>')

Get attachment file download url

const url = await chatClient.getAttachmentDownloadUrl('<attachment_id>')

Add pinned message

await chatClient.addPinnedMessage('<message_id>')

Remove pinned message

await chatClient.removePinnedMessage('<message_id>')

Get group pinned messages

const messages = await chatClient.getGroupPinnedMessages('<group_id>')

Add saved message

await chatClient.addSavedMessage('<message_id>')

Remove saved message

await chatClient.removeSavedMessage('<message_id>')

Get saved messages

const messages = await chatClient.getSavedMessages()

Get group saved messages

const messages = await chatClient.getGroupSavedMessages('<group_id>')

Hooks

When a user logs in:

await chatClient.connect()

When a user logs out:

await chatClient.disconnect()

Message Received

chatClient.onMessageRecieved((data: any) => {
  // You have a new message!
})

Added To A Group

chatClient.onAddedToGroup((data: any) => {
  // You have been added to a group!
})

Group Updated

chatClient.onGroupUpdated((data: any) => {
  // A group you are in has been updated!
})

Group Deleted

chatClient.onGroupDeleted((data: any) => {
  // A group you were in has been deleted!
})

Group Member Added

chatClient.onGroupMemberAdded((data: any) => {
  // A new member has been added to a group where you're in!
})

Group Member Removed

chatClient.onGroupMemberRemoved((data: any) => {
  // A member has been removed from a group where you're in!
})

Message Deleted

chatClient.onMessageDeleted((data: any) => {
  // A message has been deleted from a group where you're in!
})

Message Read

chatClient.onMessageRead((data: any) => {
  // A message has been read in a group where you're in!
})

Message Updated

chatClient.onMessageUpdated((data: any) => {
  // A message has been updated in a group where you're in!
})

Pinned Message Added

chatClient.onPinnedMessageAdded((data: any) => {
  // A message has been pinned in a group where you're in!
})

Pinned Message Removed

chatClient.onPinnedMessageRemoved((data: any) => {
  // A message has been unpinned in a group where you're in!
})

Saved Message Added

chatClient.onSavedMessageAdded((data: any) => {
  // A message has been saved!
})

Saved Message Removed

chatClient.onSavedMessageRemoved((data: any) => {
  // A message has been unsaved!
})

Developing

NPM scripts

  • npm t: Run test suite
  • npm start: Run npm run build in watch mode
  • npm run test:watch: Run test suite in interactive watch mode
  • npm run test:prod: Run linting and generate coverage
  • npm run build: Generate bundles and typings, create docs
  • npm run lint: Lints code
  • npm run commit: Commit using conventional commit style (husky will tell you to use it if you haven't πŸ˜‰)

Excluding peerDependencies

On library development, one might want to set some peer dependencies, and thus remove those from the final bundle. You can see in Rollup docs how to do that.

Good news: the setup is here for you, you must only include the dependency name in external property within rollup.config.js. For example, if you want to exclude lodash, just write there external: ['lodash'].

Automatic releases

Prerequisites: you need to create/login accounts and add your project to:

Prerequisite for Windows: Semantic-release uses node-gyp so you will need to install Microsoft's windows-build-tools using this command:

npm install --global --production windows-build-tools

Setup steps

Follow the console instructions to install semantic release and run it (answer NO to "Do you want a .travis.yml file with semantic-release setup?").

Note: make sure you've setup repository.url in your package.json file

npm install -g semantic-release-cli
semantic-release-cli setup
# IMPORTANT!! Answer NO to "Do you want a `.travis.yml` file with semantic-release setup?" question. It is already prepared for you :P

From now on, you'll need to use npm run commit, which is a convenient way to create conventional commits.

Automatic releases are possible thanks to semantic release, which publishes your code automatically on github and npm, plus generates automatically a changelog. This setup is highly influenced by Kent C. Dodds course on egghead.io

Git Hooks

There is already set a precommit hook for formatting your code with Prettier πŸ’…

By default, there are two disabled git hooks. They're set up when you run the npm run semantic-release-prepare script. They make sure:

This makes more sense in combination with automatic releases

FAQ

Array.prototype.from, Promise, Map... is undefined

TypeScript or Babel only provides down-emits on syntactical features (class, let, async/await...), but not on functional features (Array.prototype.find, Set, Promise...), . For that, you need Polyfills, such as core-js or babel-polyfill (which extends core-js).

For a library, core-js plays very nicely, since you can import just the polyfills you need:

import "core-js/fn/array/find"
import "core-js/fn/string/includes"
import "core-js/fn/promise"
...