@memberjunction/actions-bizapps-lms
Version:
LMS system integration actions for MemberJunction
187 lines • 7.31 kB
JavaScript
;
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.LearnWorldsBaseAction = void 0;
const global_1 = require("@memberjunction/global");
const base_lms_action_1 = require("../../base/base-lms.action");
const actions_1 = require("@memberjunction/actions");
/**
* Base class for all LearnWorlds LMS actions.
* Handles LearnWorlds-specific authentication and API interaction patterns.
*/
let LearnWorldsBaseAction = class LearnWorldsBaseAction extends base_lms_action_1.BaseLMSAction {
lmsProvider = 'LearnWorlds';
integrationName = 'LearnWorlds';
/**
* LearnWorlds API version
*/
apiVersion = 'v2';
/**
* Current action parameters (set by the framework)
*/
params;
/**
* Makes an authenticated request to LearnWorlds API
*/
async makeLearnWorldsRequest(endpoint, method = 'GET', body, contextUser) {
if (!contextUser) {
throw new Error('Context user is required for LearnWorlds API calls');
}
// Get company ID from action params
const companyId = this.getParamValue(this.params, 'CompanyID');
if (!companyId) {
throw new Error('CompanyID parameter is required');
}
// Get the integration credentials
const integration = await this.getCompanyIntegration(companyId, contextUser);
// Get API credentials (from env vars or database)
const credentials = await this.getAPICredentials(integration);
if (!credentials.apiKey) {
throw new Error('API Key is required for LearnWorlds integration');
}
// Get the school domain from ExternalSystemID or environment
const schoolDomain = integration.ExternalSystemID || this.getCredentialFromEnv(companyId, 'SCHOOL_DOMAIN');
if (!schoolDomain) {
throw new Error('School domain not found. Set in CompanyIntegration.ExternalSystemID or environment variable');
}
// Build the full URL
const baseUrl = `https://${schoolDomain}/api/${this.apiVersion}`;
const fullUrl = `${baseUrl}/${endpoint}`;
// Prepare headers
const headers = {
'Authorization': `Bearer ${credentials.apiKey}`,
'Accept': 'application/json',
'Content-Type': 'application/json',
'Lw-Client': 'MemberJunction'
};
try {
const response = await fetch(fullUrl, {
method,
headers,
body: body ? JSON.stringify(body) : undefined
});
if (!response.ok) {
const errorText = await response.text();
let errorMessage = `LearnWorlds API error: ${response.status} ${response.statusText}`;
try {
const errorJson = JSON.parse(errorText);
if (errorJson.error) {
errorMessage = `LearnWorlds API error: ${errorJson.error.message || errorJson.error}`;
}
else if (errorJson.message) {
errorMessage = `LearnWorlds API error: ${errorJson.message}`;
}
}
catch {
errorMessage += ` - ${errorText}`;
}
throw new Error(errorMessage);
}
const result = await response.json();
return result;
}
catch (error) {
if (error instanceof Error) {
throw error;
}
throw new Error(`LearnWorlds API request failed: ${error}`);
}
}
/**
* Makes a paginated request to LearnWorlds API
*/
async makeLearnWorldsPaginatedRequest(endpoint, params = {}, contextUser) {
const results = [];
let page = 1;
let hasMore = true;
const limit = params.limit || 50;
while (hasMore) {
const queryParams = new URLSearchParams({
...params,
page: page.toString(),
limit: limit.toString()
});
const response = await this.makeLearnWorldsRequest(`${endpoint}?${queryParams}`, 'GET', undefined, contextUser);
if (response.data && Array.isArray(response.data)) {
results.push(...response.data);
}
// Check if there are more pages
if (response.meta && response.meta.page < response.meta.totalPages) {
page++;
}
else {
hasMore = false;
}
// Respect max results if specified
const maxResults = this.getParamValue(this.params, 'MaxResults');
if (maxResults && results.length >= maxResults) {
return results.slice(0, maxResults);
}
}
return results;
}
/**
* Convert LearnWorlds date format to Date object
*/
parseLearnWorldsDate(dateString) {
// LearnWorlds sometimes returns timestamps as seconds since epoch
if (typeof dateString === 'number') {
return new Date(dateString * 1000);
}
return new Date(dateString);
}
/**
* Format date for LearnWorlds API (ISO 8601)
*/
formatLearnWorldsDate(date) {
return date.toISOString();
}
/**
* Map LearnWorlds user status to standard status
*/
mapUserStatus(status) {
const statusMap = {
'active': 'active',
'inactive': 'inactive',
'suspended': 'suspended',
'blocked': 'suspended'
};
return statusMap[status.toLowerCase()] || 'inactive';
}
/**
* Map LearnWorlds enrollment status
*/
mapLearnWorldsEnrollmentStatus(enrollment) {
if (enrollment.completed) {
return 'completed';
}
if (enrollment.expired) {
return 'expired';
}
if (enrollment.suspended || !enrollment.active) {
return 'suspended';
}
return 'active';
}
/**
* Calculate progress from LearnWorlds data
*/
calculateProgress(progressData) {
return {
percentage: progressData.percentage || 0,
completedUnits: progressData.completed_units || 0,
totalUnits: progressData.total_units || 0,
timeSpent: progressData.time_spent || 0
};
}
};
exports.LearnWorldsBaseAction = LearnWorldsBaseAction;
exports.LearnWorldsBaseAction = LearnWorldsBaseAction = __decorate([
(0, global_1.RegisterClass)(actions_1.BaseAction, 'LearnWorldsBaseAction')
], LearnWorldsBaseAction);
//# sourceMappingURL=learnworlds-base.action.js.map