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 🙏

© 2025 – Pkg Stats / Ryan Hefner

du-chat-sdk-js

v1.1.6

Published

Du Chat Sdk

Readme

DuChatSDKJS

npm version

DU 채팅 SDK API

Dingdonu website: click here Dingdonu Document website: click here

Table of Contents

Features

  • Du의 Web/JS용 채팅엔진 SDK
  • 시스템알림/링크알림/그룹채팅/1:1문의 성격의 채팅방 생성
  • 최신순 방 리스트 오더링 및 방 입장, 나가기, 초대, 내보내기 등의 API지원
  • 쉽고 빠르게 채팅개발
  • Vue.js, React.js 및 Vanila Js에서 구현가능
  • Typescript 기반으로 제작되어 type 사용가능

Installing

Using npm:

$ npm install du-chat-sdk-js

Using yarn:

$ yarn add axios

DataStructure

Room: 룸에 대한 데이터 Room은 RoomManager의 getRooms 메세드롤 통해서 가져올 수 있음 NOTE: 새로운 Room이 추가 되거나 업데이트 혹은 삭제, 마지막 메세지 업데아트 등으로 room list가 변경될 경우 내부적으로 자동으로 업데아트 됨!

enum RoomType {
  SYSTEM_ALARM = "SYSTEM_ALARM",
  ALARM = "ALARM",
  GROUP = "GROUP",
  INQUIRY = "INQUIRY"
}
enum ListenMessageEventType {
    CREATE = "CREATE",
    UPDATE = "UPDATE",
    DELETE = "DELETE"
}
type MessageReceivedCallback = (result: {
    eventType: ListenMessageEventType;
    message: Message;
}) => void

Room {
  //properties
  id: string;
  roomType: RoomType;
  profileUrl: string | null;
  link: {
    sid: string;
    name: string;
  } | null; //링크정보
  joinUsers: [JoinUser]; //룸의 참여한 유저 목록
  rules: RoomRules;
  meta?: Record<string, any> | null;
  lastMessage: Message | null; //룸의 마지막 메세지
  unReadMsgCount: number; //읽지않은 메세지 수
  createdAt: Date;
  master?: JoinUser; //룸생성자(방장)
  isActive: boolean; //유저가 조인되어있는지의 여부
  messages: Message[]; //룸의 메세지 목록

  //method
  onMessageReceived(callback: MessageReceivedCallback): void;
  offMessageReceived(): void;
  joinRoom(): Promise<boolean>;
  joinOutRoom(): Promise<boolean>;
  getMessagesByMessageId(params: MessageListParams): Promise<Message[]>;
  updateLastReadMessage(): Promise<boolean>;
  updateRoomSetting(updateData: UpdateRoomSettingDto): Promise<boolean>;
  kickOutUsers(targetUserIds: [string]): Promise<boolean>;
  inviteRoom(targetUserIds: [string]): Promise<boolean>;
  sendTextMessage(text: string): Promise<boolean>;
  sendFileMessage(file: File): Promise<boolean>;
}

Message: 메세지에 대한 데이터 MessageRoomgetMessagesByMessageId 의 메세드를 통해 가져올 수 있음 getMessagesByMessageId를 호출 후 Roommessages 프로퍼티는 내부적으로 messages를 업데이트함! NOTE: 새로운 Message이 추가 되거나 업데이트 혹은 삭제 등으로 Room.messages가 변경될 경우 내부적으로 자동으로 업데아트 됨!

enum MessageType {
    TEXT = "TEXT",
    PHOTO = "PHOTO",
    VIDEO = "VIDEO",
    FILE = "FILE",
    CARD = "CARD",
    ADMIN = "ADMIN"
}

interface MessageAuthor {
  authorId: string;
  nickName: string;
  profileUrl: string | null;
}
interface MessageFile {
    name: string;
    path: string;
    size: number;
    thumbnail?: string | null;
    duration?: number | null;
}
interface MessageData {
  type: MessageType;
  content: {
    fileName?: string;
    text?: string;
    files?: MessageFile[];
  };
}
Message {
  id?: string;
  roomId: string;
  syncKey: string;
  author: MessageAuthor;
  data: MessageData;
  createdAt: Date;
  isMe: boolean;
  isActive: boolean;
  isSent: boolean;
  progress: number;
}

API

BasicConnect

const { ChatManager, ChatEnv } = require('du-chat-sdk');
//or
import { ChatManager } from 'du-chat-sdk-js'
const options: {
  reconnectionDelay?: number; //default: 1000
  reconnection?: boolean; //default: true
  withCredentials?: boolean; //default: true
} = {}
const duChat = new ChatManager(ChatEnv.DEV, options)
//API:auth 로그인후 획득한 token
duChat.connect(token, options)

GetUserInfo

현재 접속한 유저정보

const user = duChat.getUser()

ConnectionHandler

onConnected: 소켓연결 완료 콜백 onDisConnected: 소켓연결 끊어짐 콜백 onConnectError: 소켓연결 에러 콜백

duChat.onConnected(() => {
  console.log("connected!")
  //get rooms!
})
duChat.onDisConnected(() => {
  console.log("disconnected!")
})
duChat.onConnectError(() => {
  console.log("connect error")
})

GetRooms

채팅방 리스트 가져오기(Get Rooms)

NOTE: onConnected 콜백함수에서 채팅방 리스트를 조회해야함! 소켓이 연결이 되지 않으면 채팅api call 불가!

import { RoomManager, FilterRooomsDto, Room } from "du-chat-sdk-js"
duChat.onConnected(() => {
  console.log("connected!")
  //get rooms!
  const roomManager: RoomManager = duChat.getRoomManager()
  try {
    const params: FilterRooomsDto? = {
      roomType: ChatRoomType.GROUP;
      linkSid: "linkSid";
    }
    const rooms: Room[] = await roomManager.getRooms(params)
  } catch (e) {
    console.error(e)
  }
})

List of params |param|Type|Description| |------|---|---| |roomType|ChatRoomType|SYSTEM_ALARM(전체시스템알림)|ALARM(링크알림)|GROUP(그룹채팅)|INQUIRY(1:1문의)| |linkSid|string|링크의 sid|

Room Manager

RoomManager {
  rooms: Room[];
  messageListParams(): MessageListParams;
  getRooms(payload?: FilterRooomsDto): Promise<Room[]>;
  addEventListener(event: string, callback: any): void;
  removeEventListener(event: string): void;
  onRoomUpdated(callback: UpdatedRoomCallback, filter?: {roomType: string, linkSid: string, masterUser?: boolean}): void;
  offRoomUpdated(): void;
}

JoinRoom

채팅방 선택시 채팅방에 입장 및 신규메세지 이벤트 리스너를 등록

NOTE: 채팅방 입장시 호출 채팅방에 입장후 채팅방에 대한 신규메세지 이벤트 리스너를 등록

enum ListenMessageEventType {
  CREATE = "CREATE",
  UPDATE = "UPDATE",
  DELETE = "DELETE"
}

1. 채팅방 입장시

try {
  await room.joinRoom()
  room.onMessageReceived((result: {
    eventType: ListenMessageEventType;
    message: Message;
  }) => {
    if(eventType == ListenMessageEventType.CREATE){
      console.log("신규메세지!", message)
    }else if(eventType == ListenMessageEventType.UPDATE){
      console.log("업데이트된 메세지", message)
    }else if(eventType == ListenMessageEventType.DELETE){
      console.log("삭제된 메세지", message)
    }
  })
}catch(e){
  //joinRoom 에러발생
}

2. 채팅방 아웃시

try {
  await room.joinOutRoom()
  room.offMessageReceived()
}catch(e){
  //joinOutRoom 에러발생
}

GetMessagesInRoom

채팅방 선택시 채팅방에 대한 메세지 목록 가져오기

NOTE: 채팅방 입장시 호출

interface MessageListParams {
  messageId?: string; //특정메세지를 기준으로 이전|이후 메세지를 호출할때 사용, null 또는 undefined 일때는 최근메세지를 가져옴
  isPrevious: boolean; //이전|이후 의 기준으로 사용, true일땐 messages ordering이 DESC 기준이며, false 일땐 ASC 기준
  count?: number; //가져올 메세지 목록 수, 기본값은 10
}

룸의 최근메세지 리스트를 DESC 기준으로 호출하는 example

try {
  const roomManager = duChat.getRoomManager()
  const params: MessageListParams = roomManager.messageListParams()
  params.count = 20
  params.isPrevious = true
  await room.getMessagesByMessageId(params)  
}catch(e){
  //getMessagesByMessageId 에러발생
}

UpdateLastReadMessage

채팅방에 대한 메세지 목록 가져온후, 마지막메세지를 읽음처리한다.

try {
  await room.updateLastReadMessage()
}catch(e){
  //updateLastReadMessage 에러발생
}

UpdateRoomSetting

채팅방의 이름(Room.name) 혹은 룰(Room.rules)를 업데이트

NOTE: name 혹은 rules는 optional한 값이지만 두데이터중 업데이트할 데이터 한가지는 필수임

interface UpdateRoomSettingDto {
  name?: string;
  rules?: {
    canInviteMemebrs: boolean; //회원 룸 초대가능여부
    canLeaveOutRoom: boolean; //회원 룸 탈퇴가능여부
    canCopyMessage: boolean; //메세지를 복사 가능여부
    canCaptureMessage: boolean; //화면 캡쳐 가능여부
    canDeleteMessage: boolean; //메세지 삭제 가능여부(현재 메세지 삭제기능은 지원하지 않습니다.)
    canShareMessage: boolean; //메세지 공유 가능여부(현재 메세지 공유기능은 지원하지 않습니다.)
    canShowMemberList: boolean; //메세지 공유 가능여부(룸 회원 show/hidden)
    isFreezed: boolean; //true일 경우 메세지 전송 및 방설정 변경 불가 
  };
}
try {
  const updateData: UpdateRoomSettingDto = {
    name: "변경할 채팅방 이름",
    rules: {
      canInviteMemebrs: true;
      canLeaveOutRoom: true;
      canCopyMessage: true;
      canCaptureMessage: true;
      canDeleteMessage: true;
      canShareMessage: true;
      canShowMemberList: true;
      isFreezed: true;
    }
  }
  await room.updateRoomSetting(updateData)
}catch(e){
  //updateRoomSetting 에러발생
}

KickOutUsers

마스터(방장)가 룸안에 있는 회원을 내보내기

NOTE: 마스터일 경우에만 가능

try {
  await room.kickOutUsers(["userId"])
}catch(e){
  //kickOutUsers 에러발생
}

InviteRoom

마스터(방장)가 룸으로 회원을 초대

NOTE: 마스터일 경우에만 가능 Response: Promise<boolean>

try {
  await room.inviteRoom(["userId"])
}catch(e){
  //kickOutUsers 에러발생
}

SendTextMessage

텍스트 메세지 보내기

NOTE: 해당 메세드를 호출할 경우 내부적으로 Room.messages가 업데이트됨 Response: Promise<boolean>

try {
  await room.sendTextMessage("text 메세지 전송...")
  //room.messages의 마자막 메세지는 `text 메세지 전송...`으로 업데이트됨
}catch(e){
  //sendTextMessage 에러발생
}

SendFileMessage

파일 메세지 보내기

NOTE: 해당 메세드를 호출할 경우 내부적으로 Room.messages가 업데이트됨 Response: Promise<boolean>

try {
  await room.sendFileMessage(file)
}catch(e){
  //sendFileMessage 에러발생
}

NOTE: 파일 메세지를 전송시 Message.data.typeFILE이 되며 전송 완료시 VIDEO|PHOTO|FILE 로 변경됨 NOTE: 메세지를 전송하는 Message.progress가 업데이트 됨

//Vue.js
//메세지 전송시 Vue example
<template>
  <div class="message-box-wrap" v-if="message.data.type == 'FILE'">
    <div>
      <a v-if="message.isSent" :href="fileUrl" target="_blank">
        {{ message.data.content.files[0].name }}
      </a>
      <div v-else>
        {{ message.data.content.fileName }} 업로드중
        <b-progress :value="message.progress" :max="1" />
      </div>
    </div>
  </div>
</template>

ErrorCodes

|Error|내용|비고| |------|---|---| |CLIENT_ID_NO_EXISTS|socket client의 아이디가 존재하지 않음|유효하지 않은 커넥션이므로 connect 재요청후 다시시도| |ROOM_NO_EXISTS|방정보가 존재하지 않음|잘못된 roomId를 보냄| |FILE_NO_EXISTS_WITH_SYNC_KEY|파일업로드시 syncKey에 해당되는 데이터가 존재하지 않음|파일전송을 처음부터 다시시도| |SEND_FILE_IS_EMPTY|파일업로드시 전송한 파일데이터가 존재하지 않음|파일전송 다시시도| |WRONG_TARGET_USER_IDS|회원초대시 target_user_ids에 유효한 회원아이디가 한개도 존재하지 않음|target_user_ids에 유효한 회원정보를 전달| |JOIN_USER_ALREADY_EXISTS|회원초대시 target_user_ids가 전부 이미 방에 존재하는 회원일 경우|target_user_ids에 유효한 회원정보를 전달|