How webpack HotModuleReplacementPlugin works and what does it do? - javascript

(I'm not good at English, if there is any problem that I did not describe clearly, please remind me to modify),
I often see some questions or articles about why webpack hmr does not work or why my webpack dev server config is invalid or how to config webpack hmr.
But has anyone tried to study the working principle behind webpack hmr in the past, The HotModuleReplacementPlugin.js has nearly 400 lines of code, what it is actually doing, I know he will generate a runtime code to insert into the entry, but I want to know,what does it do by subscribing to these hooks? If anyone knows, can you briefly describe it to me? I am trying to understand him at the moment, but it is a bit difficult with my ability, but I am very interested in webpack, and I will be grateful!!!🌈
ps:
// source code
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers #sokra
*/
"use strict";
const { SyncBailHook } = require("tapable");
const { RawSource } = require("webpack-sources");
const Template = require("./Template");
const ModuleHotAcceptDependency = require("./dependencies/ModuleHotAcceptDependency");
const ModuleHotDeclineDependency = require("./dependencies/ModuleHotDeclineDependency");
const ConstDependency = require("./dependencies/ConstDependency");
const NullFactory = require("./NullFactory");
const ParserHelpers = require("./ParserHelpers");
module.exports = class HotModuleReplacementPlugin {
constructor(options) {
this.options = options || {};
this.multiStep = this.options.multiStep;
this.fullBuildTimeout = this.options.fullBuildTimeout || 200;
this.requestTimeout = this.options.requestTimeout || 10000;
}
apply(compiler) {
const multiStep = this.multiStep;
const fullBuildTimeout = this.fullBuildTimeout;
const requestTimeout = this.requestTimeout;
const hotUpdateChunkFilename =
compiler.options.output.hotUpdateChunkFilename;
const hotUpdateMainFilename = compiler.options.output.hotUpdateMainFilename;
console.log("multiStep:",multiStep,"fullBuildTimeout:",fullBuildTimeout,"requestTimeout:",requestTimeout,"hotUpdateChunkFilename:",hotUpdateChunkFilename,"hotUpdateMainFilename:",hotUpdateMainFilename)
compiler.hooks.additionalPass.tapAsync(
"HotModuleReplacementPlugin",
callback => {
console.log("HotModuleReplacementPlugin-compiler hooks additionalPass multiStep",multiStep)
if (multiStep) return setTimeout(callback, fullBuildTimeout);
return callback();
}
);
const addParserPlugins = (parser, parserOptions) => {
parser.hooks.expression
.for("__webpack_hash__")
.tap(
"HotModuleReplacementPlugin",
ParserHelpers.toConstantDependencyWithWebpackRequire(
parser,
"__webpack_require__.h()"
)
);
parser.hooks.evaluateTypeof
.for("__webpack_hash__")
.tap(
"HotModuleReplacementPlugin",
ParserHelpers.evaluateToString("string")
);
parser.hooks.evaluateIdentifier.for("module.hot").tap(
{
name: "HotModuleReplacementPlugin",
before: "NodeStuffPlugin"
},
expr => {
return ParserHelpers.evaluateToIdentifier(
"module.hot",
!!parser.state.compilation.hotUpdateChunkTemplate
)(expr);
}
);
// TODO webpack 5: refactor this, no custom hooks
if (!parser.hooks.hotAcceptCallback) {
parser.hooks.hotAcceptCallback = new SyncBailHook([
"expression",
"requests"
]);
}
if (!parser.hooks.hotAcceptWithoutCallback) {
parser.hooks.hotAcceptWithoutCallback = new SyncBailHook([
"expression",
"requests"
]);
}
parser.hooks.call
.for("module.hot.accept")
.tap("HotModuleReplacementPlugin", expr => {
console.log("HotModuleReplacementPlugin- parser.hooks module.hot.accept expr",JSON.stringify(expr))
if (!parser.state.compilation.hotUpdateChunkTemplate) {
return false;
}
if (expr.arguments.length >= 1) {
const arg = parser.evaluateExpression(expr.arguments[0]);
let params = [];
let requests = [];
if (arg.isString()) {
params = [arg];
} else if (arg.isArray()) {
params = arg.items.filter(param => param.isString());
}
if (params.length > 0) {
params.forEach((param, idx) => {
const request = param.string;
const dep = new ModuleHotAcceptDependency(request, param.range);
dep.optional = true;
dep.loc = Object.create(expr.loc);
dep.loc.index = idx;
parser.state.module.addDependency(dep);
requests.push(request);
});
if (expr.arguments.length > 1) {
parser.hooks.hotAcceptCallback.call(
expr.arguments[1],
requests
);
parser.walkExpression(expr.arguments[1]); // other args are ignored
return true;
} else {
parser.hooks.hotAcceptWithoutCallback.call(expr, requests);
return true;
}
}
}
});
parser.hooks.call
.for("module.hot.decline")
.tap("HotModuleReplacementPlugin", expr => {
console.log("HotModuleReplacementPlugin- parser.hooks module.hot.decline expr",JSON.stringify(expr))
if (!parser.state.compilation.hotUpdateChunkTemplate) {
return false;
}
if (expr.arguments.length === 1) {
const arg = parser.evaluateExpression(expr.arguments[0]);
let params = [];
if (arg.isString()) {
params = [arg];
} else if (arg.isArray()) {
params = arg.items.filter(param => param.isString());
}
params.forEach((param, idx) => {
const dep = new ModuleHotDeclineDependency(
param.string,
param.range
);
dep.optional = true;
dep.loc = Object.create(expr.loc);
dep.loc.index = idx;
parser.state.module.addDependency(dep);
});
}
});
parser.hooks.expression
.for("module.hot")
.tap("HotModuleReplacementPlugin", ParserHelpers.skipTraversal);
};
compiler.hooks.compilation.tap(
"HotModuleReplacementPlugin",
(compilation, { normalModuleFactory }) => {
const hotUpdateChunkTemplate = compilation.hotUpdateChunkTemplate;
if (!hotUpdateChunkTemplate) return;
compilation.dependencyFactories.set(ConstDependency, new NullFactory());
compilation.dependencyTemplates.set(
ConstDependency,
new ConstDependency.Template()
);
compilation.dependencyFactories.set(
ModuleHotAcceptDependency,
normalModuleFactory
);
compilation.dependencyTemplates.set(
ModuleHotAcceptDependency,
new ModuleHotAcceptDependency.Template()
);
compilation.dependencyFactories.set(
ModuleHotDeclineDependency,
normalModuleFactory
);
compilation.dependencyTemplates.set(
ModuleHotDeclineDependency,
new ModuleHotDeclineDependency.Template()
);
compilation.hooks.record.tap(
"HotModuleReplacementPlugin",
(compilation, records) => {
if (records.hash === compilation.hash) return;
records.hash = compilation.hash;
records.moduleHashs = {};
for (const module of compilation.modules) {
const identifier = module.identifier();
records.moduleHashs[identifier] = module.hash;
}
records.chunkHashs = {};
for (const chunk of compilation.chunks) {
records.chunkHashs[chunk.id] = chunk.hash;
}
records.chunkModuleIds = {};
for (const chunk of compilation.chunks) {
records.chunkModuleIds[chunk.id] = Array.from(
chunk.modulesIterable,
m => m.id
);
}
}
);
let initialPass = false;
let recompilation = false;
compilation.hooks.afterHash.tap("HotModuleReplacementPlugin", () => {
let records = compilation.records;
if (!records) {
initialPass = true;
return;
}
if (!records.hash) initialPass = true;
const preHash = records.preHash || "x";
const prepreHash = records.prepreHash || "x";
if (preHash === compilation.hash) {
recompilation = true;
compilation.modifyHash(prepreHash);
return;
}
records.prepreHash = records.hash || "x";
records.preHash = compilation.hash;
compilation.modifyHash(records.prepreHash);
});
compilation.hooks.shouldGenerateChunkAssets.tap(
"HotModuleReplacementPlugin",
() => {
if (multiStep && !recompilation && !initialPass) return false;
}
);
compilation.hooks.needAdditionalPass.tap(
"HotModuleReplacementPlugin",
() => {
if (multiStep && !recompilation && !initialPass) return true;
}
);
compilation.hooks.additionalChunkAssets.tap(
"HotModuleReplacementPlugin",
() => {
const records = compilation.records;
if (records.hash === compilation.hash) return;
if (
!records.moduleHashs ||
!records.chunkHashs ||
!records.chunkModuleIds
)
return;
for (const module of compilation.modules) {
const identifier = module.identifier();
let hash = module.hash;
module.hotUpdate = records.moduleHashs[identifier] !== hash;
}
const hotUpdateMainContent = {
h: compilation.hash,
c: {}
};
for (const key of Object.keys(records.chunkHashs)) {
const chunkId = isNaN(+key) ? key : +key;
const currentChunk = compilation.chunks.find(
chunk => chunk.id === chunkId
);
if (currentChunk) {
const newModules = currentChunk
.getModules()
.filter(module => module.hotUpdate);
const allModules = new Set();
for (const module of currentChunk.modulesIterable) {
allModules.add(module.id);
}
const removedModules = records.chunkModuleIds[chunkId].filter(
id => !allModules.has(id)
);
if (newModules.length > 0 || removedModules.length > 0) {
const source = hotUpdateChunkTemplate.render(
chunkId,
newModules,
removedModules,
compilation.hash,
compilation.moduleTemplates.javascript,
compilation.dependencyTemplates
);
const filename = compilation.getPath(hotUpdateChunkFilename, {
hash: records.hash,
chunk: currentChunk
});
compilation.additionalChunkAssets.push(filename);
compilation.assets[filename] = source;
hotUpdateMainContent.c[chunkId] = true;
currentChunk.files.push(filename);
compilation.hooks.chunkAsset.call(currentChunk, filename);
}
} else {
hotUpdateMainContent.c[chunkId] = false;
}
}
const source = new RawSource(JSON.stringify(hotUpdateMainContent));
const filename = compilation.getPath(hotUpdateMainFilename, {
hash: records.hash
});
compilation.assets[filename] = source;
}
);
const mainTemplate = compilation.mainTemplate;
mainTemplate.hooks.hash.tap("HotModuleReplacementPlugin", hash => {
hash.update("HotMainTemplateDecorator");
});
mainTemplate.hooks.moduleRequire.tap(
"HotModuleReplacementPlugin",
(_, chunk, hash, varModuleId) => {
return `hotCreateRequire(${varModuleId})`;
}
);
mainTemplate.hooks.requireExtensions.tap(
"HotModuleReplacementPlugin",
source => {
const buf = [source];
buf.push("");
buf.push("// __webpack_hash__");
buf.push(
mainTemplate.requireFn +
".h = function() { return hotCurrentHash; };"
);
return Template.asString(buf);
}
);
const needChunkLoadingCode = chunk => {
for (const chunkGroup of chunk.groupsIterable) {
if (chunkGroup.chunks.length > 1) return true;
if (chunkGroup.getNumberOfChildren() > 0) return true;
}
return false;
};
mainTemplate.hooks.bootstrap.tap(
"HotModuleReplacementPlugin",
(source, chunk, hash) => {
source = mainTemplate.hooks.hotBootstrap.call(source, chunk, hash);
return Template.asString([
source,
"",
hotInitCode
.replace(/\$require\$/g, mainTemplate.requireFn)
.replace(/\$hash\$/g, JSON.stringify(hash))
.replace(/\$requestTimeout\$/g, requestTimeout)
.replace(
/\/\*foreachInstalledChunks\*\//g,
needChunkLoadingCode(chunk)
? "for(var chunkId in installedChunks)"
: `var chunkId = ${JSON.stringify(chunk.id)};`
)
]);
}
);
mainTemplate.hooks.globalHash.tap(
"HotModuleReplacementPlugin",
() => true
);
mainTemplate.hooks.currentHash.tap(
"HotModuleReplacementPlugin",
(_, length) => {
if (isFinite(length)) {
return `hotCurrentHash.substr(0, ${length})`;
} else {
return "hotCurrentHash";
}
}
);
mainTemplate.hooks.moduleObj.tap(
"HotModuleReplacementPlugin",
(source, chunk, hash, varModuleId) => {
return Template.asString([
`${source},`,
`hot: hotCreateModule(${varModuleId}),`,
"parents: (hotCurrentParentsTemp = hotCurrentParents, hotCurrentParents = [], hotCurrentParentsTemp),",
"children: []"
]);
}
);
// TODO add HMR support for javascript/esm
normalModuleFactory.hooks.parser
.for("javascript/auto")
.tap("HotModuleReplacementPlugin", addParserPlugins);
normalModuleFactory.hooks.parser
.for("javascript/dynamic")
.tap("HotModuleReplacementPlugin", addParserPlugins);
compilation.hooks.normalModuleLoader.tap(
"HotModuleReplacementPlugin",
context => {
context.hot = true;
}
);
}
);
}
};
const hotInitCode = Template.getFunctionContent(
require("./HotModuleReplacement.runtime")
);
console.log("hotInitCode",hotInitCode)

Related

JS API client throws 'Uncaught (in promise) TypeError: e.join is not a function' after 40 requests

Here is my code (it takes a csv file as input, does some API calls, and outputs the results as another csv file):
let allRows = [];
async function fileToLines(file) {
return new Promise((resolve, reject) => {
reader = new FileReader();
reader.onload = function (e) {
parsedLines = e.target.result.split(/\r|\n|\r\n/);
resolve(parsedLines);
};
reader.readAsText(file);
});
}
document
.getElementById('fileInput')
.addEventListener('change', async function (e) {
var file = e.target.files[0];
if (file != undefined) {
fileToLines(file).then(async id => {
console.log(id)
console.log(parsedLines)
console.log(typeof id);
var idInt = id.map(Number);
var idFiltered = id.filter(function (v) { return v !== '' });
console.log(idFiltered)
if (file != undefined) {
allRows = [];
}
for (let id of idFiltered) {
const row = await getRelease(id);
allRows.push(row);
}
download();
});
}
});
function debounce(inner, ms = 0) {
let timer = null;
let resolves = [];
return function (...args) {
// Run the function after a certain amount of time
clearTimeout(timer);
timer = setTimeout(() => {
/* Get the result of the inner function, then apply it to the resolve function of
each promise that has been created since the last time the inner function was run */
let result = inner(...args);
resolves.forEach(r => r(result));
resolves = [];
}, ms);
return new Promise(r => resolves.push(r));
};
}
const throttleFetch = debounce(fetch, 2500);
function getRelease(idFiltered) {
return throttleFetch(`https://api.discogs.com/releases/${idFiltered}`, {
headers: {
'User-Agent': '***/0.1',
'Authorization': 'key=***, secret=***',
},
}).then(response => response.json())
.then(data => {
if (data.message === 'Release not found.') {
return { error: `Release with ID ${idFiltered} does not exist` };
} else {
const id = data.id;
const delimiter = document.getElementById("delimiter").value || "|";
const artists = data.artists ? data.artists.map(artist => artist.name) : [];
const barcode = data.identifiers.filter(id => id.type === 'Barcode')
.map(barcode => barcode.value);
var formattedBarcode = barcode.join(delimiter);
const country = data.country || 'Unknown';
const genres = data.genres || [];
const formattedGenres = genres.join(delimiter);
const labels = data.labels ? data.labels.map(label => label.name) : [];
const formattedLabels = labels.join(delimiter);
const catno = data.labels ? data.labels.map(catno => catno.catno) : [];
const formattedCatNo = catno.join(delimiter);
const styles = data.styles || [];
const formattedStyles = styles.join(delimiter);
const tracklist = data.tracklist ? data.tracklist
.map(track => track.title) : [];
const formattedTracklist = tracklist.join(delimiter);
const year = data.year || 'Unknown';
const format = data.formats ? data.formats.map(format => format.name) : [];
const qty = data.formats ? data.formats.map(format => format.qty) : [];
const descriptions = data.formats ? data.formats
.map(descriptions => descriptions.descriptions) : [];
const preformattedDescriptions = descriptions.toString()
.replace('"', '""').replace(/,/g, ', ');
const formattedDescriptions = '"' + preformattedDescriptions + '"';
console.log(idFiltered,
artists,
format,
qty,
formattedDescriptions,
formattedLabels,
formattedCatNo,
country,
year,
formattedGenres,
formattedStyles,
formattedBarcode,
formattedTracklist
)
return [idFiltered,
artists,
format,
qty,
formattedDescriptions,
formattedLabels,
formattedCatNo,
country,
year,
formattedGenres,
formattedStyles,
formattedBarcode,
formattedTracklist
];
}
});
}
function download() {
const ROW_NAMES = [
"release_id",
"artist",
"format",
"qty",
"format descriptions",
"label",
"catno",
"country",
"year",
"genres",
"styles",
"barcode",
"tracklist"
];
var csvContent = "data:text/csv;charset=utf-8,"
+ ROW_NAMES + "\n" + allRows.map(e => e.join(",")).join("\n");
var encodedUri = encodeURI(csvContent);
var link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", "my_data.csv");
document.body.appendChild(link); // Required for Firefox
link.click();
}
The app passes tests for 5, 10, 20, or 30 lines of input, but when I try 40, I get this error:
Uncaught (in promise) TypeError: e.join is not a function
csvContent file:///D:/DOWNLOADS/CODE/***/csv.js:151
download file:///D:/DOWNLOADS/CODE/***/csv.js:151
<anonymous> file:///D:/DOWNLOADS/CODE///***/csv.js:38
async* file:///D:/DOWNLOADS/CODE/***/csv.js:20
I really don't know why that would be. Any ideas please? TIA.
Apparently I need to add more details but IDK what?

How to get id from link using js

I'm using wschat wordpress plugin. I'm passing link with the conversation id. If there is conversation id we need to get id and activate the particular user conversation.
I'm passing link as https://brookstone220.com/wp-admin/admin.php?page=wschat_chat&cid=3
and the js file will bw:
admin_chat.js:
import {WSChat, formatDate} from './chat';
import { AdminApiConnector } from './admin_api_connector';
import { AdminPusherConnector } from './admin_pusher_connector';
import { EVENTS } from './events';
import { EmojiButton } from '#joeattardi/emoji-button';
import UserMetaInfo from './components/user_meta_info.html'
jQuery(document).ready(function() {
const wrapper = jQuery('.wschat-wrapper');
if (wrapper.length === 0) {
return;
}
const CONVERSATION_TEMPLATE = `
<div class="friend-drawer friend-drawer--onhover" data-conversation-id="{{CONVERSATION_ID}}">
<img class="profile-image" src="https://ui-avatars.com/api/?rounded=true&name=Guest" alt="">
<div class="text">
<h6>{{NAME}}</h6>
<p class="last-message text-truncate">{{LAST_MESSAGE}}</p>
</div>
<span class="time small d-none">{{TIMESTAMP}}</span>
<span class="unread-count badge rounded-pill align-self-center">{{UNREAD_COUNT}}</span>
</div>
<hr>`;
const CHAT_BUBBLE_TEMPLATE = `
<div class="row g-0 w-100 message-item" data-message-id="{{MESSAGE_ID}}">
<div class="col-xs-10 col-md-9 col-lg-6 {{OFFSET}}">
<div class="chat-bubble chat-bubble--{{POS}}">
{{CONTENT}}
</div>
<span class="time">{{TIMESTAMP}}</span>
</div>
</div>`;
const CONVERSATION_TEMPLATE_DEFAULTS = {
'{{CONVERSATION_ID}}': '',
'{{LAST_MESSAGE}}': 'left',
'{{TIMESTAMP}}': '',
'{{NAME}}': '',
};
const BUBBLE_TEMPLATE_DEFAULTS = {
'{{OFFSET}}': '',
'{{POS}}': 'left',
'{{CONTENT}}': '',
'{{TIMESTAMP}}': '',
'{{MESSAGE_ID}}': '',
};
jQuery.ajaxSetup({
data: {
wschat_ajax_nonce: wschat_ajax_obj.nonce
}
});
var chat = new WSChat(jQuery('.wschat-wrapper'), {
connector: wschat_ajax_obj.settings.communication_protocol === 'pusher' ? AdminPusherConnector : AdminApiConnector,
api: {
endpoint: wschat_ajax_obj.ajax_url,
interval: 3000,
wschat_ajax_nonce: wschat_ajax_obj.nonce,
pusher: {
key: wschat_ajax_obj.settings.pusher.app_key,
cluster: wschat_ajax_obj.settings.pusher.cluster,
}
},
alert: {
url: wschat_ajax_obj.settings.alert_tone_url
},
header: {
status_text: wschat_ajax_obj.settings.widget_status === 'online' ? wschat_ajax_obj.settings.header_online_text : wschat_ajax_obj.settings.header_offline_text,
}
});
if (wschat_ajax_obj.settings) {
for(let key in wschat_ajax_obj.settings.colors) {
key && chat.$el.get(0).style.setProperty(key, '#' +wschat_ajax_obj.settings.colors[key]);
}
}
setInterval(() => {
chat.connector.start_conversation();
}, 5000);
const chat_panel = chat.$el.find('.chat-panel');
const conversation_panel = chat.$el.find('.conversation-list');
const chat_panel_header = chat.$el.find('.chat-panel-header');
const chat_tray_box = chat.$el.find('.chat-box-tray');
const message_input = jQuery('#wschat_message_input');
const MESSAGE_INFO = {
min: 0,
max: 0,
};
let PAST_REQUEST_IS_PENDING = false;
let SCROLL_PAUSED = false;
let DISABLE_SCROLL_LOCK = false;
const SCROLL_OFFSET = 100;
const replaceConversation = (conversation) => {
let item = conversation_panel.find('[data-conversation-id='+conversation.id+']');
if (item.length === 0 ) {
return false;
}
item.find('.time').text(conversation.updated_at);
item.find('.last-message').text( conversation.recent_message ? conversation.recent_message.body.text : '');
item.find('.unread-count').text(conversation.unread_count || '');
if (conversation.is_user_online) {
item.addClass('online');
} else {
item.removeClass('online');
}
return true;
};
const sortConversation = () => {
const new_conversation_panel = conversation_panel.clone();
const items = [];
new_conversation_panel.find('[data-conversation-id]').each(function (i, item) {
items.push(item);
});
items.sort((a, b) => {
let timestamp1 = jQuery(a).find('.time').html();
let timestamp2 = jQuery(b).find('.time').html();
return strToDate(timestamp2) - strToDate(timestamp1);
});
new_conversation_panel.html('');
items.forEach((item) => {
new_conversation_panel.append(item);
});
conversation_panel.html(new_conversation_panel.html());
};
const strToDate = (timestamp) => {
let [date1, time1] = timestamp.split(' ');
date1 = date1.split('-');
time1 = time1.split(':');
return parseInt(date1.join('') + time1.join(''));
};
const showNoConversation = () => {
const no_conversation_alert = jQuery('.no-conversation-alert');
conversation_panel.append(no_conversation_alert.removeClass('d-none'));
}
chat.on(EVENTS.WSCHAT_ON_NO_CONVERSATIONS, () => {
showNoConversation();
});
chat.on(EVENTS.WSCHAT_ON_FETCH_CONVERSATIONS, (conversations) => {
conversations.forEach(conversation => {
if (replaceConversation(conversation)) {
return;
}
CONVERSATION_TEMPLATE_DEFAULTS['{{CONVERSATION_ID}}'] = conversation.id;
CONVERSATION_TEMPLATE_DEFAULTS['{{NAME}}'] = conversation.user.meta.name;
CONVERSATION_TEMPLATE_DEFAULTS['{{TIMESTAMP}}'] = formatDate(conversation.updated_at);
CONVERSATION_TEMPLATE_DEFAULTS['{{LAST_MESSAGE}}'] = conversation.recent_message ? conversation.recent_message.body.text : '';
CONVERSATION_TEMPLATE_DEFAULTS['{{UNREAD_COUNT}}'] = conversation.unread_count || '';
let row_template = CONVERSATION_TEMPLATE;
row_template = row_template.replace(new RegExp(Object.keys(CONVERSATION_TEMPLATE_DEFAULTS).join('|'), 'g'), match => CONVERSATION_TEMPLATE_DEFAULTS[match]);
row_template = jQuery(row_template);
if (conversation.is_user_online) {
row_template = row_template.addClass('online');
}
if (conversation.user && conversation.user.meta.avatar) {
row_template.find('img.profile-image').attr('src', conversation.user.meta.avatar)
}
conversation_panel.append(row_template);
});
sortConversation();
setTimeout(() => {
let activeItem = conversation_panel.find('.active[data-conversation-id]').length
activeItem === 0 && conversation_panel.find('[data-conversation-id]').eq(0).click();
}, 1000);
});
chat.on(EVENTS.WSCHAT_ON_SET_CONVERSATION, (data) => {
data.user &&
chat_panel_header.find('.username').text(data.user.meta.name);
let info = chat.$el.find('.user-meta-info').html(UserMetaInfo);
chat_panel_header.parent().removeClass('d-none')
info.find('.name').html(data.user.meta.name);
info.find('.browser').html(data.user.meta.browser);
info.find('.os').html(data.user.meta.os);
info.find('.device').html(data.user.meta.device);
info.find('.url').html(data.user.meta.current_url);
message_input.focus();
MESSAGE_INFO.min = 0;
MESSAGE_INFO.max = 0;
DISABLE_SCROLL_LOCK = true;
resizeChat();
setTimeout(() => DISABLE_SCROLL_LOCK = false, 1000);
});
chat.on(EVENTS.WSCHAT_ON_FETCH_MESSAGES, (data) => {
for (let i = 0; i < data.messages.length; i++) {
let row = data.messages[i];
if (row.is_agent === true) {
BUBBLE_TEMPLATE_DEFAULTS['{{OFFSET}}'] = 'offset-lg-6 offset-md-3 offset-xs-2';
BUBBLE_TEMPLATE_DEFAULTS['{{POS}}'] = 'right';
} else {
BUBBLE_TEMPLATE_DEFAULTS['{{OFFSET}}'] = '';
BUBBLE_TEMPLATE_DEFAULTS['{{POS}}'] = 'left';
}
BUBBLE_TEMPLATE_DEFAULTS['{{MESSAGE_ID}}'] = row.id;
BUBBLE_TEMPLATE_DEFAULTS['{{CONTENT}}'] = row.body.formatted_content;
BUBBLE_TEMPLATE_DEFAULTS['{{TIMESTAMP}}'] = formatDate(row.created_at);
let row_template = CHAT_BUBBLE_TEMPLATE;
row_template = row_template.replace(new RegExp(Object.keys(BUBBLE_TEMPLATE_DEFAULTS).join('|'), 'g'), match => BUBBLE_TEMPLATE_DEFAULTS[match]);
if (MESSAGE_INFO.min === 0) {
chat_panel.append('<span data-message-id="0"></span>');
}
if (MESSAGE_INFO.min > row.id) {
chat_panel.find('[data-message-id='+MESSAGE_INFO.min+']').before(row_template);
MESSAGE_INFO.min = row.id;
}
if (MESSAGE_INFO.max === 0 || MESSAGE_INFO.max < row.id) {
chat_panel.find('[data-message-id='+MESSAGE_INFO.max+']').after(row_template);
MESSAGE_INFO.max = row.id;
scrollIfNotPaused();
}
if (MESSAGE_INFO.min === 0) {
scrollIfNotPaused();
}
MESSAGE_INFO.min = MESSAGE_INFO.min || row.id;
MESSAGE_INFO.max = MESSAGE_INFO.max || row.id;
}
if (DISABLE_SCROLL_LOCK === true) {
scrollIfNotPaused();
}
});
chat.on(EVENTS.WSCHAT_ON_PONG, (data) => {
let drawer = chat_panel_header.find('.friend-drawer');
let row_template = conversation_panel.find('[data-conversation-id='+data.id+']');
let row_unread_count = row_template.find('.unread-count');
let header_unread_count = chat_panel_header.find('.unread-count');
chat_panel_header.find('.status').text(data.status);
header_unread_count.text(data.unread_count);
row_unread_count.text(data.unread_count || '');
if (data.unread_count) {
header_unread_count.removeClass('d-none');
} else {
header_unread_count.addClass('d-none');
}
if (data.is_online) {
drawer.addClass('online');
row_template.addClass('online');
} else {
drawer.removeClass('online');
row_template.removeClass('online');
}
});
const scrollIfNotPaused = () => {
if (SCROLL_PAUSED === false || DISABLE_SCROLL_LOCK === true) {
chat_panel[0].scrollTop = chat_panel[0].scrollHeight;
}
}
const send_btn = jQuery('#wschat_send_message').on('click', function() {
let msg = message_input.val();
if (msg.trim() === '' && chat.trigger(EVENTS.WSCHAT_CAN_SEND_EMPTY_MESSAGE, false, true) === false) {
return false;
}
chat.sendMessage({
// Type is text by default now, it needs to changed based on the selection content
wschat_ajax_nonce: wschat_ajax_obj.nonce,
type: 'text',
'content[text]': message_input.val()
});
message_input.val('').focus();
});
message_input.keyup(function(e) {
e.key === 'Enter' && send_btn.click();
});
message_input.on('focus', function() {
let unread_count = chat_panel_header.find('.unread-count').text();
if (parseInt(unread_count) > 0) {
chat.trigger(EVENTS.WSCHAT_ON_READ_ALL_MESSAGE);
}
});
chat_panel_header.on('click', '.user-meta-info-toggle', function () {
chat.$el.find('.conversation-wrapper .user-meta-info').toggleClass('d-none');
});
conversation_panel.on('click', '[data-conversation-id]', function() {
chat_panel.html('');
let item = jQuery(this);
let converssation_id = item.data('conversation-id');
conversation_panel.find('[data-conversation-id]').removeClass('active');
item.addClass('active')
chat.connector.join_conversation(converssation_id);
});
chat_panel.on('scroll', function () {
if (DISABLE_SCROLL_LOCK) {
SCROLL_PAUSED = false;
return;
}
if (this.scrollTop < SCROLL_OFFSET) {
if (PAST_REQUEST_IS_PENDING === false) {
PAST_REQUEST_IS_PENDING = true;
chat.connector.get_messages({
after: 0,
before: MESSAGE_INFO.min
});
setTimeout(() => PAST_REQUEST_IS_PENDING = false, 500);
}
}
if (this.offsetHeight + this.scrollTop >= this.scrollHeight - SCROLL_OFFSET) {
SCROLL_PAUSED = false;
} else {
SCROLL_PAUSED = true;
}
});
const resizeChat = () => {
const window_height = jQuery(window).height() - chat.$el.offset().top;
const height = window_height - (
chat_panel_header.height()*2 + chat_tray_box.height()
);
conversation_panel.css({
'min-height': height + 'px'
});
chat_panel.css({
'min-height': height + 'px'
});
};
jQuery(window).resize(() => resizeChat());
resizeChat();
const emojiPicker = document.getElementById('wschat_emoji_picker');
const emoji = new EmojiButton({
style: 'twemoji',
rootElement: emojiPicker.parentElement,
position: 'top'
});
emojiPicker.addEventListener('click', function() {
emoji.togglePicker();
});
emoji.on('emoji', function(selection) {
console.log(selection)
message_input.val(message_input.val() + selection.emoji).focus();
setTimeout(() => message_input.focus(), 500)
});
// Attachment toggler
chat.$el.find('#attachment_picker').click(function (e) {
e.preventDefault();
chat.$el.find('.attachment-list').toggleClass('show d-none');
});
chat.$el.find('.attachment-list').on('click','button', function () {
chat.$el.find('#attachment_picker').click();
});
});
Can someone help me on this? How to get id using this js file and activate the conversation?
Here is what I used for my project to get URL parameters.
var getParameter = function getParameter(param) {
var pageURL = window.location.search.substring(1), // Get current URL substrings
urlVars = pageURL.split('&'), // Split on all "&" for more than one.
parameterName,
i;
for (i = 0; i < urlVars.length; i++) {
// Get the value of the parameter.
parameterName = urlVars[i].split('=');
// Return the value of the parameter if it has the same name as param
if (parameterName[0] === param) {
return typeof parameterName[1] === undefined ? true : decodeURIComponent(parameterName[1]);
}
}
return false;
};
var cID = getParameter('cid');

How to get activate particular conversation chat

I'm using wschat wordpress plugin. I'm passing link with the conversation id. If there is conversation id we need to get id and activate the particular user conversation.
I'm passing link as https://brookstone220.com/wp-admin/admin.php?page=wschat_chat&cid=3
and the js file will be shown below:
admin_chat.js:
import {WSChat, formatDate} from './chat';
import { AdminApiConnector } from './admin_api_connector';
import { AdminPusherConnector } from './admin_pusher_connector';
import { EVENTS } from './events';
import { EmojiButton } from '#joeattardi/emoji-button';
import UserMetaInfo from './components/user_meta_info.html'
jQuery(document).ready(function() {
const wrapper = jQuery('.wschat-wrapper');
if (wrapper.length === 0) {
return;
}
const CONVERSATION_TEMPLATE = `
<div class="friend-drawer friend-drawer--onhover" data-conversation-id="{{CONVERSATION_ID}}">
<img class="profile-image" src="https://ui-avatars.com/api/?rounded=true&name=Guest" alt="">
<div class="text">
<h6>{{NAME}}</h6>
<p class="last-message text-truncate">{{LAST_MESSAGE}}</p>
</div>
<span class="time small d-none">{{TIMESTAMP}}</span>
<span class="unread-count badge rounded-pill align-self-center">{{UNREAD_COUNT}}</span>
</div>
<hr>`;
const CHAT_BUBBLE_TEMPLATE = `
<div class="row g-0 w-100 message-item" data-message-id="{{MESSAGE_ID}}">
<div class="col-xs-10 col-md-9 col-lg-6 {{OFFSET}}">
<div class="chat-bubble chat-bubble--{{POS}}">
{{CONTENT}}
</div>
<span class="time">{{TIMESTAMP}}</span>
</div>
</div>`;
const CONVERSATION_TEMPLATE_DEFAULTS = {
'{{CONVERSATION_ID}}': '',
'{{LAST_MESSAGE}}': 'left',
'{{TIMESTAMP}}': '',
'{{NAME}}': '',
};
const BUBBLE_TEMPLATE_DEFAULTS = {
'{{OFFSET}}': '',
'{{POS}}': 'left',
'{{CONTENT}}': '',
'{{TIMESTAMP}}': '',
'{{MESSAGE_ID}}': '',
};
jQuery.ajaxSetup({
data: {
wschat_ajax_nonce: wschat_ajax_obj.nonce
}
});
var chat = new WSChat(jQuery('.wschat-wrapper'), {
connector: wschat_ajax_obj.settings.communication_protocol === 'pusher' ? AdminPusherConnector : AdminApiConnector,
api: {
endpoint: wschat_ajax_obj.ajax_url,
interval: 3000,
wschat_ajax_nonce: wschat_ajax_obj.nonce,
pusher: {
key: wschat_ajax_obj.settings.pusher.app_key,
cluster: wschat_ajax_obj.settings.pusher.cluster,
}
},
alert: {
url: wschat_ajax_obj.settings.alert_tone_url
},
header: {
status_text: wschat_ajax_obj.settings.widget_status === 'online' ? wschat_ajax_obj.settings.header_online_text : wschat_ajax_obj.settings.header_offline_text,
}
});
if (wschat_ajax_obj.settings) {
for(let key in wschat_ajax_obj.settings.colors) {
key && chat.$el.get(0).style.setProperty(key, '#' +wschat_ajax_obj.settings.colors[key]);
}
}
setInterval(() => {
chat.connector.start_conversation();
}, 5000);
const chat_panel = chat.$el.find('.chat-panel');
const conversation_panel = chat.$el.find('.conversation-list');
const chat_panel_header = chat.$el.find('.chat-panel-header');
const chat_tray_box = chat.$el.find('.chat-box-tray');
const message_input = jQuery('#wschat_message_input');
const MESSAGE_INFO = {
min: 0,
max: 0,
};
let PAST_REQUEST_IS_PENDING = false;
let SCROLL_PAUSED = false;
let DISABLE_SCROLL_LOCK = false;
const SCROLL_OFFSET = 100;
const replaceConversation = (conversation) => {
let item = conversation_panel.find('[data-conversation-id='+conversation.id+']');
if (item.length === 0 ) {
return false;
}
item.find('.time').text(conversation.updated_at);
item.find('.last-message').text( conversation.recent_message ? conversation.recent_message.body.text : '');
item.find('.unread-count').text(conversation.unread_count || '');
if (conversation.is_user_online) {
item.addClass('online');
} else {
item.removeClass('online');
}
return true;
};
const sortConversation = () => {
const new_conversation_panel = conversation_panel.clone();
const items = [];
new_conversation_panel.find('[data-conversation-id]').each(function (i, item) {
items.push(item);
});
items.sort((a, b) => {
let timestamp1 = jQuery(a).find('.time').html();
let timestamp2 = jQuery(b).find('.time').html();
return strToDate(timestamp2) - strToDate(timestamp1);
});
new_conversation_panel.html('');
items.forEach((item) => {
new_conversation_panel.append(item);
});
conversation_panel.html(new_conversation_panel.html());
};
const strToDate = (timestamp) => {
let [date1, time1] = timestamp.split(' ');
date1 = date1.split('-');
time1 = time1.split(':');
return parseInt(date1.join('') + time1.join(''));
};
const showNoConversation = () => {
const no_conversation_alert = jQuery('.no-conversation-alert');
conversation_panel.append(no_conversation_alert.removeClass('d-none'));
}
chat.on(EVENTS.WSCHAT_ON_NO_CONVERSATIONS, () => {
showNoConversation();
});
chat.on(EVENTS.WSCHAT_ON_FETCH_CONVERSATIONS, (conversations) => {
conversations.forEach(conversation => {
if (replaceConversation(conversation)) {
return;
}
CONVERSATION_TEMPLATE_DEFAULTS['{{CONVERSATION_ID}}'] = conversation.id;
CONVERSATION_TEMPLATE_DEFAULTS['{{NAME}}'] = conversation.user.meta.name;
CONVERSATION_TEMPLATE_DEFAULTS['{{TIMESTAMP}}'] = formatDate(conversation.updated_at);
CONVERSATION_TEMPLATE_DEFAULTS['{{LAST_MESSAGE}}'] = conversation.recent_message ? conversation.recent_message.body.text : '';
CONVERSATION_TEMPLATE_DEFAULTS['{{UNREAD_COUNT}}'] = conversation.unread_count || '';
let row_template = CONVERSATION_TEMPLATE;
row_template = row_template.replace(new RegExp(Object.keys(CONVERSATION_TEMPLATE_DEFAULTS).join('|'), 'g'), match => CONVERSATION_TEMPLATE_DEFAULTS[match]);
row_template = jQuery(row_template);
if (conversation.is_user_online) {
row_template = row_template.addClass('online');
}
if (conversation.user && conversation.user.meta.avatar) {
row_template.find('img.profile-image').attr('src', conversation.user.meta.avatar)
}
conversation_panel.append(row_template);
});
sortConversation();
setTimeout(() => {
let activeItem = conversation_panel.find('.active[data-conversation-id]').length
activeItem === 0 && conversation_panel.find('[data-conversation-id]').eq(0).click();
}, 1000);
});
chat.on(EVENTS.WSCHAT_ON_SET_CONVERSATION, (data) => {
data.user &&
chat_panel_header.find('.username').text(data.user.meta.name);
let info = chat.$el.find('.user-meta-info').html(UserMetaInfo);
chat_panel_header.parent().removeClass('d-none')
info.find('.name').html(data.user.meta.name);
info.find('.browser').html(data.user.meta.browser);
info.find('.os').html(data.user.meta.os);
info.find('.device').html(data.user.meta.device);
info.find('.url').html(data.user.meta.current_url);
message_input.focus();
MESSAGE_INFO.min = 0;
MESSAGE_INFO.max = 0;
DISABLE_SCROLL_LOCK = true;
resizeChat();
setTimeout(() => DISABLE_SCROLL_LOCK = false, 1000);
});
chat.on(EVENTS.WSCHAT_ON_FETCH_MESSAGES, (data) => {
for (let i = 0; i < data.messages.length; i++) {
let row = data.messages[i];
if (row.is_agent === true) {
BUBBLE_TEMPLATE_DEFAULTS['{{OFFSET}}'] = 'offset-lg-6 offset-md-3 offset-xs-2';
BUBBLE_TEMPLATE_DEFAULTS['{{POS}}'] = 'right';
} else {
BUBBLE_TEMPLATE_DEFAULTS['{{OFFSET}}'] = '';
BUBBLE_TEMPLATE_DEFAULTS['{{POS}}'] = 'left';
}
BUBBLE_TEMPLATE_DEFAULTS['{{MESSAGE_ID}}'] = row.id;
BUBBLE_TEMPLATE_DEFAULTS['{{CONTENT}}'] = row.body.formatted_content;
BUBBLE_TEMPLATE_DEFAULTS['{{TIMESTAMP}}'] = formatDate(row.created_at);
let row_template = CHAT_BUBBLE_TEMPLATE;
row_template = row_template.replace(new RegExp(Object.keys(BUBBLE_TEMPLATE_DEFAULTS).join('|'), 'g'), match => BUBBLE_TEMPLATE_DEFAULTS[match]);
if (MESSAGE_INFO.min === 0) {
chat_panel.append('<span data-message-id="0"></span>');
}
if (MESSAGE_INFO.min > row.id) {
chat_panel.find('[data-message-id='+MESSAGE_INFO.min+']').before(row_template);
MESSAGE_INFO.min = row.id;
}
if (MESSAGE_INFO.max === 0 || MESSAGE_INFO.max < row.id) {
chat_panel.find('[data-message-id='+MESSAGE_INFO.max+']').after(row_template);
MESSAGE_INFO.max = row.id;
scrollIfNotPaused();
}
if (MESSAGE_INFO.min === 0) {
scrollIfNotPaused();
}
MESSAGE_INFO.min = MESSAGE_INFO.min || row.id;
MESSAGE_INFO.max = MESSAGE_INFO.max || row.id;
}
if (DISABLE_SCROLL_LOCK === true) {
scrollIfNotPaused();
}
});
chat.on(EVENTS.WSCHAT_ON_PONG, (data) => {
let drawer = chat_panel_header.find('.friend-drawer');
let row_template = conversation_panel.find('[data-conversation-id='+data.id+']');
let row_unread_count = row_template.find('.unread-count');
let header_unread_count = chat_panel_header.find('.unread-count');
chat_panel_header.find('.status').text(data.status);
header_unread_count.text(data.unread_count);
row_unread_count.text(data.unread_count || '');
if (data.unread_count) {
header_unread_count.removeClass('d-none');
} else {
header_unread_count.addClass('d-none');
}
if (data.is_online) {
drawer.addClass('online');
row_template.addClass('online');
} else {
drawer.removeClass('online');
row_template.removeClass('online');
}
});
const scrollIfNotPaused = () => {
if (SCROLL_PAUSED === false || DISABLE_SCROLL_LOCK === true) {
chat_panel[0].scrollTop = chat_panel[0].scrollHeight;
}
}
const send_btn = jQuery('#wschat_send_message').on('click', function() {
let msg = message_input.val();
if (msg.trim() === '' && chat.trigger(EVENTS.WSCHAT_CAN_SEND_EMPTY_MESSAGE, false, true) === false) {
return false;
}
chat.sendMessage({
// Type is text by default now, it needs to changed based on the selection content
wschat_ajax_nonce: wschat_ajax_obj.nonce,
type: 'text',
'content[text]': message_input.val()
});
message_input.val('').focus();
});
message_input.keyup(function(e) {
e.key === 'Enter' && send_btn.click();
});
message_input.on('focus', function() {
let unread_count = chat_panel_header.find('.unread-count').text();
if (parseInt(unread_count) > 0) {
chat.trigger(EVENTS.WSCHAT_ON_READ_ALL_MESSAGE);
}
});
chat_panel_header.on('click', '.user-meta-info-toggle', function () {
chat.$el.find('.conversation-wrapper .user-meta-info').toggleClass('d-none');
});
conversation_panel.on('click', '[data-conversation-id]', function() {
chat_panel.html('');
let item = jQuery(this);
let converssation_id = item.data('conversation-id');
conversation_panel.find('[data-conversation-id]').removeClass('active');
item.addClass('active')
chat.connector.join_conversation(converssation_id);
});
chat_panel.on('scroll', function () {
if (DISABLE_SCROLL_LOCK) {
SCROLL_PAUSED = false;
return;
}
if (this.scrollTop < SCROLL_OFFSET) {
if (PAST_REQUEST_IS_PENDING === false) {
PAST_REQUEST_IS_PENDING = true;
chat.connector.get_messages({
after: 0,
before: MESSAGE_INFO.min
});
setTimeout(() => PAST_REQUEST_IS_PENDING = false, 500);
}
}
if (this.offsetHeight + this.scrollTop >= this.scrollHeight - SCROLL_OFFSET) {
SCROLL_PAUSED = false;
} else {
SCROLL_PAUSED = true;
}
});
const resizeChat = () => {
const window_height = jQuery(window).height() - chat.$el.offset().top;
const height = window_height - (
chat_panel_header.height()*2 + chat_tray_box.height()
);
conversation_panel.css({
'min-height': height + 'px'
});
chat_panel.css({
'min-height': height + 'px'
});
};
jQuery(window).resize(() => resizeChat());
resizeChat();
const emojiPicker = document.getElementById('wschat_emoji_picker');
const emoji = new EmojiButton({
style: 'twemoji',
rootElement: emojiPicker.parentElement,
position: 'top'
});
emojiPicker.addEventListener('click', function() {
emoji.togglePicker();
});
emoji.on('emoji', function(selection) {
console.log(selection)
message_input.val(message_input.val() + selection.emoji).focus();
setTimeout(() => message_input.focus(), 500)
});
// Attachment toggler
chat.$el.find('#attachment_picker').click(function (e) {
e.preventDefault();
chat.$el.find('.attachment-list').toggleClass('show d-none');
});
chat.$el.find('.attachment-list').on('click','button', function () {
chat.$el.find('#attachment_picker').click();
});
});
Can someone help me on this? How to activate the conversation by getting id from url?
Also, i don't know what type of js they are used can any one let me know?

How to call aysnc function getAffiliatesCodes() inside other async function

this is the first function , i have this function getAffliateCodesAsync() my requirement is to call this method from inside other function (function -2 >> generateCriBodyWithCreParameter(..))
and pass the returning value of >>(function-1) getAffliateCodesAsync(), into the third function and use that value in (function -3) checkLessorMagnitudeCode(..) and use the returning value of function-2 in function-3 at place where codeList is used, Please help
//function-1.
async function getAffliateCodesAsync(){
console.debug("==AFFILIATE_CODES==");
const ApplicationParameter = loopback.getModel('ApplicationParameter');
const applicationParamFieldValue = await ApplicationParameter.find({
where: {
fieldName: 'AFFILIATE_CODES'
},
fields: ['fieldValue']
});
return (applicationParamFieldValue.length)? applicationParamFieldValue.map(entity => String(entity['fieldValue'])):[];
}
//2.function-2
const generateCriBodyWithCreParameter = (positions, lotNumber, cutOffDate) => {
const CreParameter = loopback.getModel('CreParameter');
let creId = 1;
const positionData = [];
const content = [];
return CreParameter.find()
.then((creParameterList) => {
const promises = positions.map((position) => {
const cutOffDatePreviousMonth = getCutOffDatePreviousMonth(position.accountingDate);
return positionNativeProvider.getPositionInformationForPreviousCutOffDateForCriApf(
position, cutOffDatePreviousMonth)
.then((positionRetrieved) => {
const positionLowerCase = _.mapKeys(position, (value, key) => _.toLower(key));
const creParameters = _.filter(creParameterList, {
flowType: 'MI',
event: 'POSITION',
liabilityAmortizationMethod: position.liabilityAmortizationMethod
});
for (const creParameter of creParameters) {
const atollAmountValue = getAtollAmountValue(positionLowerCase, creParameter);
if (atollAmountValue && matchSigns(atollAmountValue, creParameter.amountSign)) {
const lineGenerated = checkContractLegalStatusForCri(position, creParameter,
atollAmountValue, content, creId, lotNumber, cutOffDate, positionRetrieved);
//No Line is generated in this case so the creId must not incremente
if (lineGenerated !== -1) {
positionData.push({
positionId: position.id,
creId
});
creId++;
}
}
}
});
});
return Promise.all(promises)
.then(() => {
return {
contentCreBody: content.join('\n'),
positionData
};
});
});
};
//function -3
const checkLessorMagnitudeCode = (lessorMagnitudeCode,codeList=[]) => {
if (!lessorMagnitudeCode) return false;
if (_.size(lessorMagnitudeCode) === 5 &&
(_.startsWith(lessorMagnitudeCode, 'S') || _.startsWith(lessorMagnitudeCode, 'T'))
&& codeList.includes(lessorMagnitudeCode)) {
return true;
}
return false;
};
//above codelist where I want to use the returning value

how to wait for function to execute and then go next javascript

I have a 2 function,
inside my runConfigComplianceDeviceOnClick I am calling the getDeviceRunningCompliance function to get some other data and based on both the results I have to return an object,
But What I am observing my data from the getDeviceRunningCompliance (Axios request to get data) function is not returned and it executes next lines,
but when I see in the console value is updated,
How to handle this case,
how to wait for the function to execute and then go next javascript? wanted to deal with asynchronous data then proceed further to the next lines...
/**
* #param {*} graphTable
*/
const runConfigComplianceDeviceOnClick = graphTable => {
let selectedDevices = graphTable.dTable.store.state.selectedRowsData;
let paramSelectedDevices;
let filteredSelectedDevices;
let finalParam;
let supportedDevices = true;
let some = getDeviceRunningCompliance(selectedDevices);
console.log("getDeviceRunningCompliance some ", some)
if (some.length) {
filteredSelectedDevices = selectedDevices.map(function(device, index) {
console.log("getDeviceRunningCompliance some filteredSelectedDevices", some)
if (notSupportedFamilies.includes(device.series)) {
// console.log(i18n.no_support_available_for_aireos);
supportedDevices = false;
} else {
// console.log(i18n.label_configuration_data_not_available);
supportedDevices = true;
}
let valsss = some.find(x => x.id === device.id);
console.log("valsss ", valsss)
return {
id: device.id,
hostname: device.hostname,
val: device.complianceStoreStatus.complianceStatus,
collectionStatus: device.collectionStatus,
series: device.series,
supportedDevices: supportedDevices
};
});
finalParam = filteredSelectedDevices.filter(function(val, index) {
return val.supportedDevices && val.val === "NON_COMPLIANT"; // this should be enable
});
paramSelectedDevices = JSON.stringify(finalParam);
localStorage.setItem("selectedDevicesConfigSync", paramSelectedDevices);
if (selectedDevices.length !== finalParam.length) {
toast({
message: finalParam.length + i18n.device_out_of_sync_for_start_vs_run,
flavor: "warning",
label: i18n.toast_header_running_configuration
});
}
shell.router.push(`/dna/provision/configuration-compliance`);
}
};
const getDeviceRunningCompliance = (selectedDevices) => {
let self = this;
let deviceRunningComplaince = [];
selectedDevices.forEach((val, index) => {
let obj = {};
getComplianceDetails(val.id).then(data => {
const complianceDetailsData = data;
if (complianceDetailsData) {
// this.setState({
// complianceDetailsData: data
// });
let cardStatus;
let complianceApiDataForConfig =
complianceDetailsData && complianceDetailsData.filter(config => config.complianceType === "RUNNING_CONFIG");
cardStatus =
complianceApiDataForConfig && complianceApiDataForConfig.length && complianceApiDataForConfig[0].status;
obj.id = val.id;
obj.runningStatus = cardStatus;
deviceRunningComplaince.push(obj);
// return cardStatus;
}
});
// deviceRunningComplaince.push(obj);
});
return deviceRunningComplaince;
};
This is how I solved this issue. Please comment if we can do this better.
/**
* #param {*} graphTable
*/
const runConfigComplianceDeviceOnClick = graphTable => {
let selectedDevices = graphTable.dTable.store.state.selectedRowsData;
let paramSelectedDevices;
let filteredSelectedDevices;
let finalParam;
let supportedDevices = true;
getDeviceRunningCompliance(selectedDevices).then(function(some) {
if (some.length) {
filteredSelectedDevices = selectedDevices.map(function(device, index) {
console.log("getDeviceRunningCompliance some filteredSelectedDevices", some);
if (notSupportedFamilies.includes(device.series)) {
// console.log(i18n.no_support_available_for_aireos);
supportedDevices = false;
} else {
// console.log(i18n.label_configuration_data_not_available);
supportedDevices = true;
}
let valsss = some.find(x => x.id === device.id);
console.log("valsss ", valsss);
return {
id: device.id,
hostname: device.hostname,
val: device.complianceStoreStatus.complianceStatus,
collectionStatus: device.collectionStatus,
series: device.series,
supportedDevices: supportedDevices
};
});
finalParam = filteredSelectedDevices.filter(function(val, index) {
return val.supportedDevices && val.val === "NON_COMPLIANT"; // this should be enable
});
paramSelectedDevices = JSON.stringify(finalParam);
localStorage.setItem("selectedDevicesConfigSync", paramSelectedDevices);
if (selectedDevices.length !== finalParam.length) {
toast({
message: finalParam.length + i18n.device_out_of_sync_for_start_vs_run,
flavor: "warning",
label: i18n.toast_header_running_configuration
});
}
shell.router.push(`/dna/provision/configuration-compliance`);
}
});
};
const getDeviceRunningCompliance = selectedDevices => {
let promiseData = selectedDevices.map((val, index) => {
return getComplianceDetails(val.id).then(data => {
let obj = {};
const complianceDetailsData = data;
if (complianceDetailsData) {
let cardStatus;
let complianceApiDataForConfig =
complianceDetailsData && complianceDetailsData.filter(config => config.complianceType === "RUNNING_CONFIG");
cardStatus =
complianceApiDataForConfig && complianceApiDataForConfig.length && complianceApiDataForConfig[0].status;
obj.id = val.id;
obj.runningStatus = cardStatus;
return obj;
}
});
});
return Promise.all(promiseData);
};

Categories

Resources