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

@skybaer0804/spark-messaging-client

v1.0.2

Published

Spark Messaging Server를 위한 Socket.IO 클라이언트 SDK

Readme

Spark Messaging Client SDK

Spark Messaging Server를 위한 Socket.IO 클라이언트 SDK입니다. 실시간 메시징, 방 기능, 에러 처리 등을 제공하는 간결하고 확장 가능한 API를 제공합니다.

설치

npm install spark-messaging-client

또는

yarn add spark-messaging-client

빠른 시작

기본 사용법

import SparkMessaging from 'spark-messaging-client';

// SDK 초기화
const client = new SparkMessaging({
    serverUrl: 'http://localhost:3000',
    projectKey: 'default-project-key-12345',
});

// 연결 성공 이벤트
client.onConnected((data) => {
    console.log('연결 성공:', data.message);
    console.log('Socket ID:', data.socketId);
});

// 메시지 수신
client.onMessage((data) => {
    console.log('메시지 수신:', data);
});

// 메시지 전송
client.sendMessage('chat', 'Hello, World!', 'user123');

환경 변수 사용

브라우저 환경:

window.SPARK_MESSAGING_CONFIG = {
    SERVER_URL: 'http://localhost:3000',
    PROJECT_KEY: 'your-project-key',
};

import SparkMessaging from 'spark-messaging-client';
const client = new SparkMessaging(); // 환경 변수에서 자동 로드

Node.js 환경:

export SERVER_URL=http://localhost:3000
export PROJECT_KEY=your-project-key

API 문서

초기화

new SparkMessaging(options?)

SDK 인스턴스를 생성합니다.

옵션:

interface SparkMessagingOptions {
    serverUrl: string; // 서버 URL (필수)
    projectKey: string; // 프로젝트 키 (필수)
    autoConnect?: boolean; // 자동 연결 (기본값: true)
    reconnection?: boolean; // 자동 재연결 (기본값: true)
    reconnectionAttempts?: number; // 재연결 시도 횟수 (기본값: 5)
    reconnectionDelay?: number; // 재연결 지연 시간(ms) (기본값: 1000)
}

예제:

const client = new SparkMessaging({
    serverUrl: 'http://localhost:3000',
    projectKey: 'your-key',
    autoConnect: false, // 수동 연결
});

연결 관리

connect(): Promise<void>

서버에 연결합니다. autoConnect: false로 설정한 경우 수동으로 호출해야 합니다.

await client.connect();

disconnect(): void

연결을 종료합니다.

client.disconnect();

isConnected(): boolean

연결 상태를 확인합니다.

if (client.isConnected()) {
    console.log('연결됨');
}

getSocketId(): string | undefined

현재 Socket ID를 가져옵니다.

const socketId = client.getSocketId();

메시지 API

sendMessage(type, content, user?)

일반 메시지를 전송합니다.

파라미터:

  • type: 메시지 타입 ('chat' | 'notification' | 'system' | 'test')
  • content: 메시지 내용
  • user: 사용자 ID (선택)
client.sendMessage('chat', 'Hello!', 'user123');

onMessage(callback): () => void

메시지 수신 콜백을 등록합니다. 구독 해제 함수를 반환합니다.

const unsubscribe = client.onMessage((data) => {
    console.log('메시지:', data);
});

// 나중에 구독 해제
unsubscribe();

sendRoomMessage(room, type, content, user?)

특정 방에 메시지를 전송합니다.

client.sendRoomMessage('room-1', 'chat', 'Hello Room!', 'user123');

onRoomMessage(callback): () => void

방 메시지 수신 콜백을 등록합니다.

client.onRoomMessage((data) => {
    console.log('방 메시지:', data);
});

방 API

joinRoom(roomName): Promise<void>

방에 입장합니다.

try {
    await client.joinRoom('my-room');
    console.log('방 입장 성공');
} catch (error) {
    console.error('방 입장 실패:', error);
}

leaveRoom(roomName): Promise<void>

방에서 나갑니다.

await client.leaveRoom('my-room');

getJoinedRooms(): string[]

현재 참여 중인 방 목록을 가져옵니다.

const rooms = client.getJoinedRooms();
console.log('참여 중인 방:', rooms);

isInRoom(roomName): boolean

특정 방에 참여 중인지 확인합니다.

if (client.isInRoom('my-room')) {
    console.log('방에 참여 중입니다');
}

이벤트 핸들링

onConnected(callback): () => void

연결 성공 이벤트를 처리합니다.

client.onConnected((data) => {
    console.log('연결됨:', data.message);
    console.log('Socket ID:', data.socketId);
});

onError(callback): () => void

에러 이벤트를 처리합니다.

client.onError((error) => {
    console.error('에러:', error.message);
    if (error.code) {
        console.error('에러 코드:', error.code);
    }
});

유틸리티

getOptions(): SparkMessagingOptions

현재 설정을 가져옵니다.

const options = client.getOptions();
console.log('서버 URL:', options.serverUrl);

완전한 예제

import SparkMessaging from 'spark-messaging-client';

// 1. SDK 초기화
const client = new SparkMessaging({
    serverUrl: 'http://localhost:3000',
    projectKey: 'default-project-key-12345',
});

// 2. 이벤트 핸들링
client.onConnected((data) => {
    console.log('✅ 연결 성공:', data.message);

    // 연결 후 메시지 전송
    client.sendMessage('chat', 'Hello!', 'user123');
});

client.onMessage((data) => {
    console.log('📥 메시지 수신:', data);
});

client.onError((error) => {
    console.error('❌ 에러:', error.message);
});

// 3. 방 기능 사용
async function roomExample() {
    try {
        // 방 입장
        await client.joinRoom('chat-room');

        // 방 메시지 수신
        client.onRoomMessage((data) => {
            console.log('📥 방 메시지:', data);
        });

        // 방 메시지 전송
        client.sendRoomMessage('chat-room', 'chat', 'Hello Room!', 'user123');

        // 나중에 방 나가기
        await client.leaveRoom('chat-room');
    } catch (error) {
        console.error('방 작업 실패:', error);
    }
}

// 4. 연결 종료 (필요시)
// client.disconnect();

타입 정의

SDK는 TypeScript로 작성되었으며 완전한 타입 정의를 제공합니다.

import type {
    MessageData,
    RoomMessageData,
    ConnectedData,
    ErrorData,
    SparkMessagingOptions,
    MessageCallback,
    RoomMessageCallback,
} from 'spark-messaging-client';

테스트

서버가 실행 중인 상태에서 테스트를 실행합니다:

# 서버 실행 (다른 터미널)
npm run dev

# SDK 테스트 실행
npm test

환경 변수로 서버 URL과 키를 지정할 수 있습니다:

SERVER_URL=http://localhost:3000 PROJECT_KEY=your-key npm test

빌드

npm run build

빌드된 파일은 dist/ 디렉토리에 생성됩니다:

  • dist/index.js - CommonJS 형식
  • dist/index.esm.js - ES Module 형식
  • dist/index.d.ts - TypeScript 타입 정의

개발

# 개발 모드 (watch 모드)
npm run dev

라이선스

MIT

문서

프로젝트 학습 및 개발을 위한 문서:

  • FRONTEND_SETUP.md - 프론트엔드 설정 가이드 (설정 파일 예시 포함)
  • DEVELOPER_GUIDE.md - 개발자 가이드 (기술 스택, 아키텍처, API 레퍼런스, 이벤트 시스템, 개발 가이드)
  • DEPLOYMENT.md - npm 배포 가이드

참고