connect-mongodb with mongolab - node.js

Im using heroku mongolab add-on for my expressjs web app. How can I use process.env.MONGOLAB_URI env variable with connect-mongodb?

According to Heroku docs, the URI format for a MongoLab Single-node plan is:
mongodb://dbuser:dbpass#host:port/dbname
You can use a regular expression (and/or other String functions) to extract required variables for creating your MongoStore:
function createDBSettings(mongoLabURI) {
var dbSettings = {},
regexp = /^mongodb:\/\/(\w+):(\w+)#(\w+):(\w+)\/(\w+)$/,
matches = regexp.match(mongoLabURI);
dbSettings.dbname = matches[5];
dbSettings.host = matches[3];
dbSettings.port = matches[4];
dbSettings.username = matches[1];
dbSettings.password = matches[2];
return dbSettings;
}
var MongoStore = require('connect-mongo')(express);
var store = new MongoStore(createDBSettings(process.env.MONGOLAB_URI));
You should be able to do the same for Cluster plan URIs.
Have a look at node-mongodb-native source code. URI parsing happens on MongoClient.connect().

Related

Amazon Translate - Formality Setting in .Net?

When trying to use the Formality setting (https://aws.amazon.com/about-aws/whats-new/2022/10/amazon-translate-formality-customization-support-dutch-korean-mexican-spanish/ ) in code behind (.Net), I keep getting System.NullReferenceException: 'Object reference not set to an instance of an object.'
Here's the code I'm running - everything works as expected until I add in request.Settings.Formality = "FORMAL";`
using (var client = new AmazonTranslateClient(awsCredentials, selectedRegion))
{
var request = new Amazon.Translate.Model.TranslateTextRequest();
request.Text = toTranslate;
request.SourceLanguageCode = sourceLanguage;
request.TargetLanguageCode = translateLanguage;
request.Settings.Formality = "FORMAL";
`Looking at the limited examples in other languages from the AWS documentation doesn't indicate anything else that's needed. I also tried the Profanity setting and the same results - System.NullReferenceException.
I also tried making the call later via the using statement that looks like this with the same error:`
var response = client.TranslateTextAsync(request).GetAwaiter().GetResult();
response.AppliedSettings.Formality = translationFormality;
`
Updated code with solution that worked for me:
using (var client = new AmazonTranslateClient(awsCredentials, selectedRegion))
{
var request = new Amazon.Translate.Model.TranslateTextRequest();
request.Text = toTranslate;
request.SourceLanguageCode = sourceLanguage; // SourceLanguageItem.LanguageCode;
request.TargetLanguageCode = translateLanguage; // TranslateLanguageItem.LanguageCode;
TranslationSettings settings = new TranslationSettings();
settings.Formality = "FORMAL";
request.Settings = settings;

Trying to convert my Azure.Storage.Blobs upload code to the new nuget 12.10 and just cannot figure it out. It seemed much simplier in 12.8

I'm trying to update my upload and delete code for Azure.Storage.Blobs 12.10 version and just not having any luck. This is how I used to do it in 12.8:
'''
var name = Guid.NewGuid().ToString();
var fullUri = new UriBuilder()
{
Scheme = "https",
Host = "MyStorageAccount.blob.core.windows.net",
Path = $"myimages/{App.User.EmailAddress}/{name}.jpg",
Query = subToken
};
var blobClient = new BlobClient(fullUri.Uri);
try
{
using var myStream = File.OpenRead(file.Path);
await blobClient.UploadAsync(myStream);
myStream.Close();
'''
All the examples on github are using the default storage connections string and not a SaS token. I have a serverless function that gets me a SaS token and I already have the container created. I just need a simple sample that uses a pre-existing SaS token and container. Any ideas would be appreciated very much.
John
EDIT: This is this 12.10 code I have been trying but it doesn't seem to like the URI.
'''
var name = Guid.NewGuid().ToString();
var blobUri = new BlobUriBuilder(new Uri(
$"https://myAccount.blob.core.windows.net/blobcontainer/{App.User.EmailAddress}/{name}.jpg?{subToken}"));
var completeUri = blobUri.ToUri();
var blobClientNew = new BlobClient(completeUri, null);
using var myStream3 = File.OpenRead(file.Path);
await blobClientNew.UploadAsync(myStream3);
myStream3.Close();
'''

Using NodeJs Style function callbacks with ArangoJS 3.x

Is it possible to use NodeJs like function Callbacks with ArangoJs 3.x;
I have seen that ArangoJs 3.x using .then method (promises)..
But I am using NodeJs 4.4 .. so i can't use .then method there.. Can I use nodejs like function callbacks for arangojs 3.x ?
Quoting the ArangoJS github page:
// ES2015-style
import arangojs, {Database, aql} from 'arangojs';
let db1 = arangojs(); // convenience short-hand
let db2 = new Database();
let {query, bindVars} = aql`RETURN ${Date.now()}`;
// or plain old Node-style
var arangojs = require('arangojs');
var db1 = arangojs();
var db2 = new arangojs.Database();
var aql = arangojs.aql(['RETURN ', ''], Date.now());
var query = aql.query;
var bindVars = aql.bindVars;
// Using a complex connection string with authentication
let host = process.env.ARANGODB_HOST;
let port = process.env.ARANGODB_PORT;
let database = process.env.ARANGODB_DB;
let username = process.env.ARANGODB_USERNAME;
let password = process.env.ARANGODB_PASSWORD;
let db = arangojs({
url: `http://${username}:${password}#${host}:${port}`,
databaseName: database
});
// Using ArangoDB 2.8 compatibility mode
let db = arangojs({
arangoVersion: 20800
});
Isn't that exactly what you were looking for?

Using node.js to display helpscout metrics

I am hoping someone can point me in the right direction.
I would like to use metrics-helpscout to bring back data that I can use for a dashboard. I am not having any luck. This is also my first time using node.js so I apologize in advance.
Here is what I have tried so far.
Following the instructions on github I used npm to install segmentio/metrics, metrics-helpscout and metrics-express.
I created a file called metrics.js and added this...
var Metrics = require('metrics');
var expressMetrics = require('metrics-express');
var helpscout = require('metrics-helpscout');
var express = require('metrics-express/node_modules/express');
var app = express();
console.log('start' );
var zzz = Metrics()
.every('1m', helpscout('myapi-key', ['my-mailbox-id']))
.on('helpscout active tickets', function (metric) {
console.log('helpscout update:' + metric.latest() );
});
var xxx = Metrics()
.every('1m', helpscout('myapi-key', ['my-mailbox-id']));
var date = new Date();
var val = 3;
var key = 'test';
var ddd = Metrics().set(key, val, date);
app.use('/', expressMetrics(xxx))
.listen(7002);
I then started the file by running node metrics.js
I opened a browser and hit the url and port and I just got back
[]
On the metrics express page example i used the var xxx. I thought I would get back a list of all the supported metrics. I then tested just using my var ddd and it did return my value. I am sure I am missing something or a lot.
Any help is appreciated.
Just in case it matters I am using ArchLinux.
Welp I figured it out. I generated a new API key and it worked.

Apache Thrift with nodejs example

I am trying to use Apache Thrift for passing messages between applications implemented in different languages. It is not necessarily used as RPC, but more for serializing/deserializing messages.
One application is in node.js. I am trying to figure out how Apache thrift works with node.js, but I can't find too much documentation and examples, except for one tiny one regarding Cassandra at:
https://github.com/apache/thrift/tree/trunk/lib/nodejs
Again, I don't need any procedures declared in the .thrift file, I only need to serialize a simple data structure like:
struct Notification {
1: string subject,
2: string message
}
Can anyone help me with an example?
I finally found the answer to this question, after wasting a lot of time just by looking at the library for nodejs.
//SERIALIZATION:
var buffer = new Buffer(notification);
var transport = new thrift.TFramedTransport(buffer);
var binaryProt = new thrift.TBinaryProtocol(transport);
notification.write(binaryProt);
At this point, the byte array can be found in the transport.outBuffers field:
var byteArray = transport.outBuffers;
For deserialization:
var tTransport = new thrift.TFramedTransport(byteArray);
var tProtocol = new thrift.TBinaryProtocol(tTransport);
var receivedNotif = new notification_type.Notification();
receivedNotif.read(tProtocol);
Also the following lines need to be added to the index.js file from the nodejs library for thrift:
exports.TFramedTransport = require('./transport').TFramedTransport;
exports.TBufferedTransport = require('./transport').TBufferedTransport;
exports.TBinaryProtocol = require('./protocol').TBinaryProtocol;
Plus there is also at least one bug in the nodejs library.
The above answer is wrong, because it tries to use outBuffers directly, which is an array of buffers. Here is a working example of using thrift with nodejs:
var util = require('util');
var thrift = require('thrift');
var Notification = require('./gen-nodejs/notification_types.js').Notification;
var TFramedTransport = require('thrift/lib/thrift/transport').TFramedTransport;
var TBufferedTransport = require('thrift/lib/thrift/transport').TBufferedTransport;
var TBinaryProtocol = require('thrift/lib/thrift/protocol').TBinaryProtocol;
var transport = new TFramedTransport(null, function(byteArray) {
// Flush puts a 4-byte header, which needs to be parsed/sliced.
byteArray = byteArray.slice(4);
// DESERIALIZATION:
var tTransport = new TFramedTransport(byteArray);
var tProtocol = new TBinaryProtocol(tTransport);
var receivedNotification = new Notification();
receivedUser.read(tProtocol);
console.log(util.inspect(receivedNotification, false, null));
});
var binaryProt = new TBinaryProtocol(transport);
// SERIALIZATION:
var notification = new Notification({"subject":"AAAA"});
console.log(util.inspect(notification, false, null));
notification.write(binaryProt);
transport.flush();
DigitalGhost is right, the previous example is wrong.
IMHO the outBuffers is a private property to the transport class and should not be accessed.

Resources