KMsg
Defined in: packages/messaging/src/k-msg.ts:260
High-level messaging facade for sending messages through configured providers.
KMsg provides a unified API for sending various message types (SMS, LMS, MMS, ALIMTALK, FRIENDTALK, RCS, etc.) through multiple providers with automatic routing, template interpolation, and lifecycle hooks.
Key features:
- Unified
send()API for all message types - Automatic provider routing based on message type
- Template variable interpolation with
#{variable}syntax - Lifecycle hooks for monitoring and tracking
- Batch sending with concurrency control
- Optional persistence strategies
Examples
섹션 제목: “Examples”Basic usage with a single provider:
import { KMsg } from '@k-msg/messaging';import { SolapiProvider } from '@k-msg/provider/solapi';
const kmsg = new KMsg({ providers: [ new SolapiProvider({ apiKey: process.env.SOLAPI_API_KEY!, apiSecret: process.env.SOLAPI_API_SECRET!, defaultFrom: '01000000000', }), ],});
// Send SMS (type is inferred when omitted)const result = await kmsg.send({ to: '01012345678', text: 'Hello, World!',});
if (result.isSuccess) { console.log('Message sent:', result.value.messageId);}Multi-provider setup with routing:
import { KMsg } from '@k-msg/messaging';import { IWINVProvider } from '@k-msg/provider';import { SolapiProvider } from '@k-msg/provider/solapi';
const kmsg = new KMsg({ providers: [ new SolapiProvider({ apiKey: '...', apiSecret: '...' }), new IWINVProvider({ apiKey: '...' }), ], routing: { defaultProviderId: 'solapi', byType: { ALIMTALK: 'iwinv', }, },});
// ALIMTALK will be routed to IWINVawait kmsg.send({ type: 'ALIMTALK', to: '01012345678', templateId: 'AUTH_OTP', variables: { code: '123456' },});Constructors
섹션 제목: “Constructors”Constructor
섹션 제목: “Constructor”new KMsg(
config):KMsg
Defined in: packages/messaging/src/k-msg.ts:287
Creates a new KMsg instance with the specified configuration.
Parameters
섹션 제목: “Parameters”config
섹션 제목: “config”KMsgConfig
Configuration object containing providers and optional settings
Returns
섹션 제목: “Returns”KMsg
Throws
섹션 제목: “Throws”Error if config is invalid or providers array is empty
Example
섹션 제목: “Example”const kmsg = new KMsg({ providers: [new SolapiProvider({ apiKey: '...', apiSecret: '...' })], routing: { defaultProviderId: 'solapi' }, defaults: { sms: { autoLmsBytes: 90 } },});Methods
섹션 제목: “Methods”healthCheck()
섹션 제목: “healthCheck()”healthCheck():
Promise<{healthy:boolean;issues:string[];providers:Record<string,ProviderHealthStatus>; }>
Defined in: packages/messaging/src/k-msg.ts:384
Performs a health check on all configured providers.
Checks the health status of each provider and aggregates the results. Useful for monitoring and determining if the messaging system is operational.
Returns
섹션 제목: “Returns”Promise<{ healthy: boolean; issues: string[]; providers: Record<string, ProviderHealthStatus>; }>
A promise resolving to health check results containing:
healthy:trueif all providers are healthy,falseotherwiseproviders: Map of provider IDs to their health statusissues: Array of error messages for any unhealthy providers
Example
섹션 제목: “Example”const health = await kmsg.healthCheck();if (!health.healthy) { console.error('Provider issues:', health.issues);}send()
섹션 제목: “send()”Call Signature
섹션 제목: “Call Signature”send(
input):Promise<Result<SendResult,KMsgError>>
Defined in: packages/messaging/src/k-msg.ts:465
Sends a single message and returns a Result.
This method normalizes the input, selects an appropriate provider based on
routing configuration, and sends the message. Template variables in the
message text are interpolated if variables are provided.
Parameters
섹션 제목: “Parameters”input
섹션 제목: “input”The message to send. Can be a single SendInput or an array.
When type is omitted, the message is treated as SMS and may be upgraded
to LMS based on content length and defaults.sms.autoLmsBytes.
Returns
섹션 제목: “Returns”Promise<Result<SendResult, KMsgError>>
A promise resolving to:
- For single input:
Result<SendResult, KMsgError> - For array input:
BatchSendResultwith individual results
Examples
섹션 제목: “Examples”Send an SMS:
const result = await kmsg.send({ to: '01012345678', text: 'Hello!' });if (result.isSuccess) { console.log('Sent:', result.value.messageId);} else { console.error('Failed:', result.error.message);}Send ALIMTALK with template variables:
const result = await kmsg.send({ type: 'ALIMTALK', to: '01012345678', templateId: 'AUTH_OTP', variables: { code: '123456', name: 'John' },});Send multiple messages (batch):
const batchResult = await kmsg.send([ { to: '01011112222', text: 'Hello 1' }, { to: '01033334444', text: 'Hello 2' },]);console.log(`Total: ${batchResult.total}, Results: ${batchResult.results.length}`);Call Signature
섹션 제목: “Call Signature”send(
input):Promise<BatchSendResult>
Defined in: packages/messaging/src/k-msg.ts:466
Sends a single message and returns a Result.
This method normalizes the input, selects an appropriate provider based on
routing configuration, and sends the message. Template variables in the
message text are interpolated if variables are provided.
Parameters
섹션 제목: “Parameters”input
섹션 제목: “input”The message to send. Can be a single SendInput or an array.
When type is omitted, the message is treated as SMS and may be upgraded
to LMS based on content length and defaults.sms.autoLmsBytes.
Returns
섹션 제목: “Returns”Promise<BatchSendResult>
A promise resolving to:
- For single input:
Result<SendResult, KMsgError> - For array input:
BatchSendResultwith individual results
Examples
섹션 제목: “Examples”Send an SMS:
const result = await kmsg.send({ to: '01012345678', text: 'Hello!' });if (result.isSuccess) { console.log('Sent:', result.value.messageId);} else { console.error('Failed:', result.error.message);}Send ALIMTALK with template variables:
const result = await kmsg.send({ type: 'ALIMTALK', to: '01012345678', templateId: 'AUTH_OTP', variables: { code: '123456', name: 'John' },});Send multiple messages (batch):
const batchResult = await kmsg.send([ { to: '01011112222', text: 'Hello 1' }, { to: '01033334444', text: 'Hello 2' },]);console.log(`Total: ${batchResult.total}, Results: ${batchResult.results.length}`);sendOrThrow()
섹션 제목: “sendOrThrow()”sendOrThrow(
input):Promise<SendResult>
Defined in: packages/messaging/src/k-msg.ts:502
Sends a single message and throws on failure.
This is a convenience method that unwraps the Result, returning the
SendResult on success or throwing the KMsgError on failure.
Useful when you want to use try/catch error handling instead of
checking result.isSuccess.
Parameters
섹션 제목: “Parameters”input
섹션 제목: “input”The message to send (single message only, not an array)
Returns
섹션 제목: “Returns”Promise<SendResult>
A promise resolving to SendResult on success
Throws
섹션 제목: “Throws”KMsgError if the message fails to send
Example
섹션 제목: “Example”try { const result = await kmsg.sendOrThrow({ to: '01012345678', text: 'Hello!', }); console.log('Sent:', result.messageId);} catch (error) { console.error('Send failed:', error.message);}builder()
섹션 제목: “builder()”
staticbuilder():KMsgBuilder
Defined in: packages/messaging/src/k-msg.ts:361
Creates a new fluent builder for constructing KMsg instances.
The builder provides a chainable API for configuring providers, routing, defaults, and hooks.
Returns
섹션 제목: “Returns”A new KMsgBuilder instance
Example
섹션 제목: “Example”const kmsg = KMsg.builder() .addProvider(new SolapiProvider({ apiKey: '...', apiSecret: '...' })) .withRouting({ defaultProviderId: 'solapi' }) .withDefaults({ sms: { autoLmsBytes: 90 } }) .build();create()
섹션 제목: “create()”
staticcreate(config):KMsg
Defined in: packages/messaging/src/k-msg.ts:340
Creates a KMsg instance with the specified configuration.
This is a factory method alias for the constructor, useful for functional-style code or when you prefer named factory methods.
Parameters
섹션 제목: “Parameters”config
섹션 제목: “config”KMsgConfig
Configuration object containing providers and optional settings
Returns
섹션 제목: “Returns”KMsg
A new KMsg instance
Example
섹션 제목: “Example”import { KMsg } from '@k-msg/messaging';import { SolapiProvider } from '@k-msg/provider/solapi';
const kmsg = KMsg.create({ providers: [ new SolapiProvider({ apiKey: process.env.SOLAPI_API_KEY!, apiSecret: process.env.SOLAPI_API_SECRET!, defaultFrom: '01000000000', }), ], routing: { defaultProviderId: 'solapi' },});