putBotAlias not working in AWS LexModelBuildingService node.js - node.js

I've been trying to replace the existing LexBot Alias(named LATEST) with a newly created bot version.
Now, according to aws documentation
When you want to update a bot alias, set the checksum field to the checksum of the most recent revision of the $LATEST version.
I can see the Alias LATEST is using bot version 12 in the Lex Console.
I have tried getting the checksum using the following (I am using getBot(...) of LexModelBuildingService to get checksum of the bot):
using Alias name itself as version i.e. LATEST.
setting versionOrAlias in getBot method params as '$LATEST'.
Hardcoding the version to 12in getBot(..).
I have used checksum from the above scenarios, but the error seems to be same as
PreconditionFailedException: The checksum value doesn't match for the resource named 'LATEST'.
Here's code snippet
async putBotAlias(botVersionResponse){
let checksum;
await this.getBot(botVersionResponse.name,'12').then(botRes=>{ // have used 12, LATEST, $LATEST with same error
console.log("Checksum For Latest: " + botRes.checksum);
checksum = botRes.checksum;
});
var params = {
botName: botVersionResponse.name,
botVersion: (parseInt(botVersionResponse.version,10)).toString(),
name: 'LATEST',
checksum : checksum
};
// checksum: checksum
console.log("Params in putBotAlias : " + JSON.stringify(params));
return new Promise((resolve,reject)=>{
this.modelBuildingService.putBotAlias(params, function(err, data) {
if (err){
reject(err);
} // an error occurred
else{
console.log("Put Alias Response :::" + JSON.stringify(data));
resolve(data);
} // successful response
});
});
}
I am really at lost here as to what version exactly it wants.
Any help is greatly appreciated.
PS: Please mention any additional required information in comments.

Apparantly I was putting checksum of 'Bot' and not of the 'BotAlias' which I was trying to put.
Updated code gets the checksum of bot Alias :
async putBotAlias(botVersionResponse,aliasName){
let checksum;
if(typeof aliasName != "undefined"){
await this.getBotAlias(botVersionResponse.name,aliasName).then(res=>{
console.log("Checksum For Latest ALIAS : " + res.checksum);
checksum = res.checksum;
}).catch((err)=>{
console.log(" Unable to getBotAlias checksum " + err);
});
}
Silly mistake, but hope it helps anyone making it. :)

Related

Liquibase lib file has console.log which prints the DB credentials. Please find the line#47 of the attached liquibase lib file. how to stop it?

const LiquibaseTS = require('node-liquibase').Liquibase;
const POSTGRESQL_DEFAULT_CONFIG = require('node-liquibase').POSTGRESQL_DEFAULT_CONFIG;
const myConfig = {
...POSTGRESQL_DEFAULT_CONFIG,
changeLogFile: './changelog.xml',
url: 'jdbc:postgresql://localhost:5432/node_liquibase_testing',
username: 'postgres',
password: 'postgres123',
logLevel: 'info'
}
const instTs = new LiquibaseTS(myConfig);
instTs.update();
I've the above code in my index.js file.
I get the below console output when the line instTs.update(); get executed,
Running /Users/path1/path2/sampleapp/node_modules/node-liquibase/dist/liquibase/liquibase --changeLogFile="./changelog.xml" --url="jdbc:postgresql://localhost" --username="Postgres" --password="postgres123" --classpath="/Users/path1/path2/sampleapp/node_modules/node-liquibase/dist/drivers/postgresql-42.2.8.jar" --logLevel="info" update ...
when I debug the node-liquibase library I found that this console print is due to the line#47 of the file /Users/path1path2/sampleapp/node_modules/node-liquibase/dist/node-liquibase.cjs.development.js
the code snippet in the node-liquibase.cjs.development.js file is,
CommandHandler.spawnChildProcess = function spawnChildProcess(commandString) {
console.log("Running " + commandString + "...");
return new Promise(function (resolve, reject) {
child_process.exec(commandString, function (error, stdout, stderr) {
console.log('\n', stdout);
if (error) {
console.error('\n', stderr); // error.stderr = stderr;
return reject(error);
}
resolve(stdout);
});
});
};
return CommandHandler;
}();
as per that file, the line# 47 is very first line of the function
console.log("Running " + commandString + "...");
This code is printing the DB details/credentials in the console. Also I noticed that liquibase prints the DB details/credentials on the console along with the error for the changeset error scenario.
What I need?
I want to stop printing the DB credentials on the console during normal run.
During error scenario, I want only the liquibase error printed on the console. it should not print the error with db credentials on the console.
index.js code instTs.update(); is not throwing any exception during error scenario. How can we find/distinguish the error scenario. eg: changeset to insert a value where the table doesn't exist.
Any help greatly appreciated.
Since it prints out the configuration, your only option is probably to move the sensitive information to another spot liquibase can read configuration from.
If you make a liquibase.properties file with your password in it, I don't think that will show in the logs. I've not used the node-liquibase frontend much, so I don't know if you need to explicitly add a liquibasePropertiesFile setting to your config.
Alternately, if you use a newer version of liquibase (probably newer than what node-liquibase ships with by default, but there is a way to override that with the liquibase argument) you can set the password and other fields with environment variables as well, and those will not be logged.

How to render a page to pdf after a redirection?

QUESTION
I am trying to get a pdf of a report from a website which needs login. So I am first logging in to the website which then redirects to the page I want access to. I need to hook the onLoadFinished function to the page.render function. Here is the code I am using:
page.open(BASE_URL + Report_URL).then(function(status) {
console.log(status);
try{
page.evaluate(function(){
setTimeout(function(){
document.getElementById("username").value = "admin";
document.getElementById("password").value = "admin";
document.getElementById("submit").click();
},100)
})
page.property('onLoadFinished', function(status,page) {
console.log('==== onLoadFinished()');
try{
console.log(' status: ' + status );
page.render("report.pdf")
}catch(ex){
var fullMessage = "\nJAVASCRIPT EXCEPTION";
console.log(fullMessage);
}
},page);
}catch(ex){
var fullMessage = "\nJAVASCRIPT EXCEPTION";
console.log(fullMessage);
}
});
BUT,
Nothing happens, even exception does not come.
How can this be achieved? I want to chain the onloadFinished function to another function which can render the page as pdf...pls help!!
Environment
OS: Ubuntu 14
Node version (node -v): v6.2.2
package version: npm - 3.9.5
I solved it by using this.render instead of page.render.
Details here:- https://github.com/amir20/phantomjs-node/issues/675#issuecomment-312733078

What is the best way to run npm packages on demand as mircoservices without installing it locally?

Let's say I have these npm packages published to npm:
service1#v1.0
service1#v2.0
service2#v1.0
each package has a single function:
function run(extraStr) {
return 'package_name_and_version' + extraStr; // i.e. service1 v1.0 extraStr
}
And I want to write nodejs code that use the packages without installing it locally
var server = require("my-server-sdk");
// get(package_name, version, function_in_package, arguments, callback)
server.get('service1', '2.0', 'run', ['app1'], (err, result) => {
console.log(result); // this should print service1 v2.0 app1
});
where my-server-sdk is an sdk that interface with my server's api where it install the required packages and cache it for later use.
What is the best way to do that? what the security concerns and how to prevent any?
this is a simple diagram for what I want
NOTE: service1#v1.0
service1#v2.0
service2#v1.0
are just examples to any packages in npm i.e. lodash
Caching example:
Let's say we have TTL equal 60 minutes.
client1 requested a function from lodash and another function from underscore at 01:00.
Now in the server lodash and underscore are installed with timestamp 01:00.
client2 requested a function from underscore at 01:30 which get used instantly because underscore is installed before but it timestamp got updated to 1:30.
At 02:01 lodash get deleted because it didn't get used on the past TTL currenttime - lodash_timestamp > TTL but underscore stays because currenttime - underscore_timestamp < TTL
So when client3 request lodash at 02:30 it get intsalled again with 02:30 as a timestamp.
There is the npmi package which gives an API to npm install.
The logic I would use is:
Get the specific package and version from npm (install if is not already installed)
Require the package inside nodejs
Run the specified method with the specified parameters
Return the results to the client
var npmi = require('npmi');
var path = require('path');
function runModule(moduleName, moduleVersion, moduleMethod, moduleMethodParams) {
return new Promise((resolve, reject) => {
var options = {
name: moduleName, // your module name
version: moduleVersion, // expected version [default: 'latest']
forceInstall: false, // force install if set to true (even if already installed, it will do a reinstall) [default: false]
npmLoad: { // npm.load(options, callback): this is the "options" given to npm.load()
loglevel: 'silent' // [default: {loglevel: 'silent'}]
}
};
options.path = './' + options.name + "#" + options.version,
npmi(options, function(err, result) {
if (err) {
if (err.code === npmi.LOAD_ERR) console.log('npm load error');
else if (err.code === npmi.INSTALL_ERR) console.log('npm install error');
console.log(err.message);
return reject(err)
}
// installed
console.log(options.name + '#' + options.version + ' installed successfully in ' + path.resolve(options.path));
var my_module = require(path.resolve(options.path, "node_modules", options.name))
console.log("Running :", options.name + '#' + options.version)
console.log("Method :", moduleMethod);
console.log("With params :", ...moduleMethodParams)
resolve(my_module[moduleMethod](...moduleMethodParams))
});
})
}
runModule('lodash', '4.10.0', 'fill', [Array(3), 2])
.then(result => console.log("Result :", result))
runModule('lodash', '3.10.0', 'fill', [Array(3), 2])
.then(result => console.log("Result :", result))
You could see now that there are 2 created folders (lodash#3.10.0 , lodash#4.10.0) indicating the package name and version.
I have made the assumptions that npm is in path and the server has the permissions to install packages in current directory, also that the "MODULE_NAME#MODULE_VERSION" is a valid folder name under the current OS.

Laravel 5.4 Broadcast : Pusher->Error->WebSocketError

I just began to use Broadcasting with Pusher and Echo. My problem is that I'm getting an error and I can't find how to resolve it. The error message look pretty straigthfoward, but I have no idea where I should head to get rid of it.
My laravel is an upgrade from Laravel 5.3. I uncommented the App/Providers/BroadcastServiceProvider::class into config.php.
I created an event and set the Private channel.return new PrivateChannel('dealer.'$this->client->dealer_id);
I added the new channel into routes/channels.php
Broadcast::channel('dealer.{dealerId}', function ($user, $dealerId) {
return (int) $user->dealer_id === (int) $dealerId;
});
I added this to bootstrap.js
window.Echo = new Echo({
broadcaster: 'pusher',
key: 'my-secrect-key'
});
I also added everything to the .env file. Finally, I added the channel to the script at the end of the applayout.blade.php
Echo.private(`dealer.1`)
.listen('NewClient', (e) => {
console.log(e);
});
When I load the page, this is the error I got from the console:
Pusher : Error : {
"type":"WebSocketError",
"error":{
"type":"PusherError",
"data":{
"code":null,
"message":"Auth value for subscription to private-dealer.1 is invalid: should be of format 'key:signature'"
}
}
}
What am I missing/doing wrong?
Upgrading Laravel 5.3 to 5.4 you should make changes in your .env file
Change From:
PUSHER_KEY
PUSHER_SECRET
to
PUSHER_APP_KEY
PUSHER_APP_SECRET
Someone answered it on Laracast. Link

node.js + express error: cannot read property 'url' of undefined

I'm fairly new to Node.js, installing it to try out the DrupalChat (v7dev) module. I believe this problem is with either node.js or express, as I am beyond the stage where the chat module's settings are loaded. I am faced with the following output when trying to start the chat server
Extension loaded: drupalchat_nodejs.server.extension.js
Started http server.
info - socket.io started
node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^
TypeError: Cannot read property 'url' of undefined
at Function.handle (/usr/local/lib/node_modules/npm/node_modules/express/node_modules/connect/lib/proto.js:105:18)
at Server.app (/usr/local/lib/node_modules/npm/node_modules/express/node_modules/connect/lib/connect.js:60:31)
at Server.serverListening (/usr/local/lib/node_modules/npm/node_modules/socket.io/node_modules/policyfile/lib/server.js:136:16)
at Server.g (events.js:154:14)
at Server.emit (events.js:64:17)
at Array.1 (net.js:710:10)
at EventEmitter._tickCallback (node.js:192:40)
I remember when express installed, it gave a warning like ".... bugs['web'] should probably be bugs['url']" (I can't remember the prefix)
So is it that the server is trying to read an (API?) variable 'url' but its currently 'web'?
I have all the modules up to date, is it that I should downgrade? Or is there some way of working around this using another module?
EDIT:
line 201 is the last very line (delete authenticatedClients[authData.authToken];)... I just added to whole function for proper context
var authenticateClientCallback = function (error, response, body) {
if (error) {
console.log("Error with authenticate client request:", error);
return;
}
if (response.statusCode == 404) {
if (settings.debug) {
console.log('Backend authentication url not found, full response info:', response);
}
else {
console.log('Backend authentication url not found.');
}
return;
}
var authData = false;
try {
authData = JSON.parse(body);
}
catch (exception) {
console.log('Failed to parse authentication message:', exception);
if (settings.debug) {
console.log('Failed message string: ' + body);
}
return;
}
if (!checkServiceKey(authData.serviceKey)) {
console.log('Invalid service key "', authData.serviceKey, '"');
return;
}
if (authData.nodejsValidAuthToken) {
if (settings.debug) {
console.log('Valid login for uid "', authData.uid, '"');
}
setupClientConnection(authData.clientId, authData, authData.contentTokens);
authenticatedClients[authData.authToken] = authData;
}
else {
console.log('Invalid login for uid "', authData.uid, '"');
delete authenticatedClients[authData.authToken];
}
}
Per #thesnufkin's post, looks like the underlying express version currently pulled is not stable. Roll back to 2.5.9 and you should be good to go:
npm uninstall express
npm install express#2.5.9
As requested,
The v7 chat module from drupal is not stable. You should not use it in production.
Check bugs : http://drupal.org/project/issues/drupalchat?status=All&categories=All
Check forums : http://drupalchat7.botskool.co.in/?q=forum
Still looking for a new maintener:
"New maintainer wanted - please ping beejeebus if you're interested!".
nodejs module has this issue, so I don't think its related to the drupalchat server specifically. Here is the issue for that: http://drupal.org/node/1537702
The option to use node.js as backend in DrupalChat is currently under development. It also depends when (date on which) you downloaded the DrupalChat since the dev code is updated everyday, if new code is committed.
Please raise an issue for the same at this link - http://drupal.org/project/issues/drupalchat?status=All&categories=All.
Thanks,
darklrd

Resources