@sonatel-os/juf
Version:
The community SDK for Orange Money, SMS, Email & Sonatel APIs on the Orange Developer Platform.
180 lines (161 loc) • 7.52 kB
JavaScript
;Object.defineProperty(exports, "__esModule", {value: true}); function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
var _chunkUD6WYISCcjs = require('./chunk-UD6WYISC.cjs');
var _chunkTSJ7NWVTcjs = require('./chunk-TSJ7NWVT.cjs');
var _chunkW5WEVJMXcjs = require('./chunk-W5WEVJMX.cjs');
// src/communication/communication.structure.js
var _superstruct = require('superstruct');
var EmailStructure = _superstruct.object.call(void 0, {
subject: _superstruct.string.call(void 0, ),
to: _superstruct.string.call(void 0, ),
from: _superstruct.string.call(void 0, ),
body: _superstruct.string.call(void 0, ),
html: _superstruct.optional.call(void 0, _superstruct.boolean.call(void 0, ))
});
var DateTimeString = _superstruct.define.call(void 0, "DateTimeString", (value) => {
return typeof value === "string" && !isNaN(Date.parse(value));
});
var SmsStructure = _superstruct.object.call(void 0, {
body: _superstruct.string.call(void 0, ),
to: _superstruct.string.call(void 0, ),
confidential: _superstruct.optional.call(void 0, _superstruct.boolean.call(void 0, )),
scheduledFor: _superstruct.optional.call(void 0, DateTimeString),
senderName: _superstruct.string.call(void 0, )
});
// src/communication/communicationService.js
var Communication = class _Communication {
/** @private @type {Authentication} */
#authService;
/** @private @type {import('axios').AxiosInstance} */
#client;
/** @private */
#logger;
/**
* Creates a Communication instance with injectable dependencies.
*
* @param {object} deps - Dependencies for the communication service.
* @param {Authentication} deps.authService - Authentication service instance.
* @param {import('axios').AxiosInstance} deps.client - HTTP client instance.
* @param {object} deps.logger - Logger instance with error/warn/info/debug methods.
*/
constructor({ authService, client, logger: logger2 }) {
this.#authService = authService;
this.#client = client;
this.#logger = logger2;
}
/**
* Factory method to initialize Communication with default dependencies.
* @method init
* @memberof Service\Communication
* @param {object} [deps] - Optional shared dependencies.
* @param {Authentication} [deps.authService] - Shared auth instance (avoids duplicate token fetches).
* @returns {Communication} An initialized instance of Communication.
*/
static init({ authService } = {}) {
return new _Communication({
authService: authService || _chunkUD6WYISCcjs.authenticationService_default.init(),
client: _chunkW5WEVJMXcjs.requester_default.bootstrap({ baseURL: _chunkW5WEVJMXcjs.getApiUrl.call(void 0, ) }),
logger: _chunkW5WEVJMXcjs.logger.child("communication")
});
}
/**
* Sends an email through the Apigee API.
*
* @async
* @method sendEmail
* @memberof Service\Communication
* @param {object} emailParams - Parameters for the email to be sent.
* @param {string} emailParams.subject - The subject of the email.
* @param {string} emailParams.to - The email address of the recipient.
* @param {string} emailParams.from - The email address of the sender.
* @param {string} emailParams.body - The plaintext body of the email.
* @param {boolean} [emailParams.html] - Whether the body is HTML (optional).
* @returns {Promise<{ id: string, status: string }>} The response from the Apigee API.
* @throws {import('../core/errors.js').ValidationError} When input validation fails.
* @throws {import('../core/errors.js').ExternalServiceError} When the API request fails.
*
* @example
* communication.sendEmail({
* subject: 'Hello!',
* to: 'recipient@example.com',
* from: 'sender@example.com',
* body: '<p>This is a test email.</p>',
* html: true
* });
*/
async sendEmail({ subject, to, from, body, html }) {
_chunkTSJ7NWVTcjs.validate.call(void 0, { subject, to, from, body, html }, EmailStructure, "sendEmail");
const headers = await this.#getAuthHeaders();
const payload = {
subject,
from,
to,
body,
...html && { html }
};
return this.#sendRequest(_chunkTSJ7NWVTcjs.EMAIL_URI, payload, headers);
}
/**
* Sends an SMS through the Apigee API.
*
* @async
* @method sendSMS
* @memberof Service\Communication
* @param {object} smsParams - Parameters for the SMS to be sent.
* @param {string} smsParams.body - The message body of the SMS.
* @param {boolean} [smsParams.confidential=true] - Whether the message is confidential.
* @param {string} [smsParams.scheduledFor] - Scheduled time (ISO 8601 format).
* @param {string} smsParams.senderName - The name of the sender.
* @param {string} smsParams.to - The phone number of the recipient.
* @returns {Promise<{ id: string, status: string }>} The response from the Apigee API.
* @throws {import('../core/errors.js').ValidationError} When input validation fails.
* @throws {import('../core/errors.js').ExternalServiceError} When the API request fails.
*
* @example
* communication.sendSMS({
* body: 'This is a test SMS.',
* to: '+1234567890',
* senderName: 'MyApp'
* });
*/
async sendSMS({ body, confidential = true, scheduledFor, senderName, to }) {
_chunkTSJ7NWVTcjs.validate.call(void 0, { body, confidential, scheduledFor, senderName, to }, SmsStructure, "sendSMS");
const headers = await this.#getAuthHeaders();
const payload = {
body,
channel: _chunkW5WEVJMXcjs.SMS_CHANNEL,
confidential,
...scheduledFor && { scheduledFor },
...senderName && { senderName },
to
};
return this.#sendRequest(_chunkTSJ7NWVTcjs.SMS_URI, payload, headers);
}
/**
* @private
* @returns {Promise<{ Authorization: string }>} Authorization headers.
*/
async #getAuthHeaders() {
const { access_token, token_type } = await this.#authService.debug();
return _chunkTSJ7NWVTcjs.buildAuthHeader.call(void 0, access_token, token_type);
}
/**
* @private
* @param {string} uri - The API endpoint path.
* @param {object} payload - The request payload.
* @param {object} headers - The request headers.
* @returns {Promise<object>} The response data.
* @throws {import('../core/errors.js').ExternalServiceError} On request failure.
*/
async #sendRequest(uri, payload, headers) {
try {
const { data } = await this.#client.post(uri, payload, { headers });
return data;
} catch (error) {
this.#logger.error("Communication request failed", { uri, status: _optionalChain([error, 'access', _ => _.response, 'optionalAccess', _2 => _2.status]) });
throw _chunkW5WEVJMXcjs.fromAxiosError.call(void 0, error, "Request failed. Please check your input and try again.");
}
}
};
var communicationService_default = Communication;
exports.EmailStructure = EmailStructure; exports.SmsStructure = SmsStructure; exports.communicationService_default = communicationService_default;
//# sourceMappingURL=chunk-WRKKDVFU.cjs.map