globalid-messaging-web-sdk
v1.0.0
Published
Messaging Web SDK
Downloads
5
Readme
Messaging Web SDK
Table of contents
Overview
The official globaliD messaging web SDK for JavaScript, available for browsers. The SDK provides convenient access to the globaliD messaging API from applications written in JavaScript. It provides an easy way to create chats, send messages, etc.
Installation
The preferred way to install the SDK is to use the npm package manager. Simply type the following into a terminal window:
npm install globalid-messaging-web-sdk
Usage
The SDK for JavaScript bundles TypeScript definition files for use in TypeScript projects and to support tools that can read .d.ts files. To use the TypeScript definition files within a Node.js project, simply import globalid-messaging-web-sdk as you normally would. In a TypeScript file:
import { Config, GlobalidMessagingClient, init } from 'globalid-messaging-web-sdk'
All types of SDK described in the appendix Interfaces.
Please prepare the config object for the initialization process. The mandatory parameter in a configuration is accessToken
. To get an access token you need to authorize a globaliD user. Please, read more about authorization process here.
All HTTP requests will be performed with this access token and all data will be related to this user.
const config: Config = {
accessToken: 'string'
}
To start using the SDK you need to initialize it with a configuration object.
client: GlobalidMessagingClient = await init(config)
The main class is GlobalidMessagingClient
. It provides an entry point to all functionality of the SDK. Please use this object in your application to access messaging API.
If an access token is not provided in config or it's invalid the init function will throw NoAccessTokenError
error.
Get configuration
The method getConfig()
returns configuration object which was used for initialization. It will be helpful if you need to check the current access token.
const config: Config = client.getConfig()
Subscribe to events
The SDK provides a real-time mechanism for getting chat messages and messaging events. You can get an event as soon as it is sent.
With the subscription, you will get new chat messages and different important events such as NEW_CHANNEL_CREATED
.
All supported event types were described in enum NotificationAction
in the appendix Interfaces.
Please create callback function and subscribe to new events as the first step after initialization to get notified about all messaging actions.
const token: string = client.subscribe((channel: string, notification: ServiceNotification) => {
console.log('Channel', channel)
console.log('Notification', notification)
})
The callback function has two parameters:
channel
: the channel is the unique string identifier of the channelnotification
: data of event contains useful information about the event After successful subscription, you will get a unique subscription token as a result of functionsubscribe()
. You have to use it later for unsubscribing. When you finish working with messaging, to unsubscribe from the previous subscription, please use functionunsubscribe()
with a unique subscription token.
client.unsubscribe(token)
Get channels
In order to get a list of channels related to the current user, please use channel().getChannels(page, perPage)
function. It returns an array of channels and meta information for paging.
You have to provide two parameters:
page
: number of channels pageperPage
: number of channels per page Example:
const channels: ChannelsResponse = await client.channel().getChannels(page, perPage)
Create a channel
If a user wants to start a new conversation, he/she will need to create a new channel. Channel contains all messages related to a single chat and meta-information about chat.
To create a new channel please use function channel().createChannel(channelPayload)
and provide channel payload with all required information.
The mandatory parameters for channel payload:
uuid
: the generated unique Version 4 UUID, needed to eliminate channel duplicatestype
: the channel typeexposed
: if true the channel will visible for searchingparticipants
: the list of globaliD user UUID what should be included to a new channel Example:
const channelPayload: ChannelPayload = {
uuid: 'ab999e7d-d0c8-4e21-9ef1-6c16b6d669f3',
type: ChannelType.Personal,
exposed: false,
participants: ['5800c6fb-fa9c-4ab4-ac31-2e62e102fde4']
}
const channel: Channel = await client.channel().createChannel(channelPayload)
The function returns the channel object of the newly created channel. It contains all the information about the channel.
Search channels
In order to find channels which contains provided participants, please use channel().searchChannels(participants)
function.
The first argument should be an array of globaliD user UUID.
const channels: ChannelsResponse = await client.channel().searchChannels(['5800c6fb-fa9c-4ab4-ac31-2e62e102fde4'])
The function returns the list of channel object which contains provided participants.
Get counters
To update the notifications with unread channels in your application, you could use channel().getCounters(page, perPage)
function.
You have to provide two parameters:
page
: number of channels pageperPage
: number of channels per page
const counters: CountersResponse = await client.channel().getCounters(page, perPage)
The function returns the list of counters and meta information for paging.
Get messages
The main feature of messaging is message exchange. To get a message list of the channel in history order, please use message().getMessages(channelId, page, perPage)
function.
You have to provide the parameters:
channelId
: the id of the channelpage
: number of channels pageperPage
: number of channels per page Example:
const messages: MessagesResponse = await client.message().getMessages(channelId, page, perPage)
The function returns the list of messages and meta information for paging.
Send messages
If a user wants to start a new conversation, he will need to create a new channel and send a message to it.
To send a new message please use function message().sendMessage(messagePayload)
and provide message payload with all required information.
The mandatory parameters for message payload:
message.uuid
: the generated unique Version 4 UUID, needed to eliminate message duplicatesmessage.type
: the message typemessage.content
: the JSON content of message what depends on message typechannels
: the list of channel ids to send the message in For message type MessageType.Text JSON content should contain parametertext
, for example:
{
"text":"Message"
}
Example:
const messagePayload: MessagePayload = {
message: {
uuid: 'ab999e7d-d0c8-4e21-9ef1-6c16b6d669f3',
type: MessageType.Text,
content: '{}'
},
channels: ['1']
}
const message: SendMessageResponse = await client.message().sendMessage(messagePayload)
The function returns the list of saved messages.
Update message statuses
When a client is receiving messages delivery requests should sent to mark the messages as delivered.
To make message as delivered, please use message().setMessageDelivered(messageId)
function and pass id of message as argument.
const status: MessageDeliveredResponse = await client.message().setMessageDelivered(messageId)
The function returns a result object with the message and channel ids.
When a client is reading messages seen request should sent for last viewed message to mark all previous messages as seen.
To send seen request, please use message().setMessageSeen(messageId)
function and pass id of message as argument.
const status: MessageSeenResponse = await client.message().setMessageSeen(messageId)
The function returns a result object with the message and channel ids.
Block users
A user can block any other user. The block just rejects sending messages for the blocked users.
To control blocking a user can block or unblock any participant.
For blocking, please use block().blockUser(userId)
function and pass uuid of the blocked user.
const blockedUser: BlockedUser = await client.block().blockUser(userId)
For unblocking, please use block().unblockUser(userId)
function and pass uuid of the blocked user.
await client.block().unblockUser(userId)
To get a list of blocked users, please use block().getUserBlocks()
function.
const blocks: BlocksResponse = await client.block().getUserBlocks()
Interfaces
interface Config {
accessToken: string
}
interface GlobalidMessagingClient {
getConfig (): Config
subscribe (callback: (channel: string, notification: ServiceNotification) => void): string
unsubscribe (token: string): boolean
channel (): ChannelService
message (): MessageService
block (): BlockService
}
enum ChannelType {
Service = 'SERVICE',
Presence = 'PRESENCE',
Personal = 'PERSONAL',
}
interface ChannelPayload {
uuid: string
type: ChannelType
exposed: boolean
participants: string[]
title?: string
description?: string
image_url?: string
}
interface Channel {
id: string
uuid: string
alias: string
type: ChannelType
exposed: boolean
title?: string
description?: string
image_url?: string
deleted: boolean
created_by: string
updated_by?: string
created_at: string
updated_at?: string
participants: string[]
unread_count: number
message?: Message
}
interface Channels {
channels: Channel[]
}
interface ChannelsResponse extends PagingResponse {
data: Channels
}
interface Counter {
id: string
unread_count: number
}
interface Counters {
counters: Counter[]
}
interface CountersResponse extends PagingResponse {
data: Counters
}
enum MessageType {
Text = 'TEXT',
}
interface SendMessage {
uuid: string
type: MessageType
content: string
}
interface MessagePayload {
message: SendMessage
channels: string[]
}
interface Message {
id: string
uuid: string
channel_id: string
sequence_id: number
type: MessageType
author: string
content: object
delivered: boolean
deleted: boolean
created_at: string
updated_at?: string
}
interface MessagesWithSeen {
messages: Message[]
message_seen?: Message
}
interface MessagesResponse extends PagingResponse {
data: MessagesWithSeen
}
interface SendMessageResponse extends Array<Message> {
}
interface MessageDeliveredResponse {
message_id: string
channel_id: string
user_id: string
delivered_at: string
}
interface MessageSeenResponse {
id: string
message_id: string
channel_id: string
gid_uuid: string
seen_at: string
}
interface BlockedUser {
id: string
user_id: string
blocked_by: string
blocked_at: string
}
interface BlockedUsers {
blocked_users: BlockedUser[]
}
interface BlocksResponse extends PagingResponse {
data: BlockedUsers
}
enum NotificationAction {
NewChannelCreated = 'NEW_CHANNEL_CREATED',
NewMessage = 'NEW_MESSAGE_RECEIVED',
SeenStatus = 'SEEN_STATUS_RECEIVED',
DeliveryStatus = 'DELIVERY_STATUS_RECEIVED',
UserBlocked = 'USER_BLOCKED',
UserUnblocked = 'USER_UNBLOCKED',
}
interface ServiceNotification {
action: string
sender: string
payload: object
}