How to properly call multiple environment variables within a variable definition in Node - node.js

I have two environment variables that I have saved in my local local.env.js file. I'd like to use them in place of the username and password in the following code:
var admins = {
'frank': { password: 'mypassword' },
};
When I use the code below, I get an error (Unexpected token .):
var admins = {
process.env.BASIC_AUTH_USER: {password: process.env.BASIC_AUTH_PASSWORD},
};
Any suggestions on how to do this correctly?

In ES5 and earlier, a static object declaration cannot use a "computed" value for a property name - it must be a string literal. So, you have to use an actual line of code to assign the property using the obj[computedPropName] = value; syntax. In your specific case, that would look like this:
var admins = {};
admins[process.env.BASIC_AUTH_USER] = {password: process.env.BASIC_AUTH_PASSWORD};
In ES6, you can use a computed value in a static declaration if you enclose it in the array syntax like this:
var admins = {[process.env.BASIC_AUTH_USER]: {password: process.env.BASIC_AUTH_PASSWORD}};
See this description of new ES6 features and this MDN reference for some further description of this feature.
Portions of ES6 are available in some of the latest version of browsers, in runtime environments like node.js and, of course, you can use transpilers to code in ES6, but transpile to ES5 compatible code for many features. We are, of course, a ways away from being able to rely on native ES6 support for general cross browser use (thus the interest in transpilers now).

You can use array-like-notation, like so:
var admins = {};
admins[process.env.BASIC_AUTH_USER] = {
password: process.env.BASIC_AUTH_PASSWORD
};
If BASIC_AUTH_USER is "Frank" and BASIC_AUTH_PASSWORD is "potatosalad" then you will end up with an object like this:
admins: {
Frank: {
password: 'potatosalad'
}
}

Try this
admins = {};
admins[process.env.BASIC_AUTH_USER] = {password: process.env.BASIC_AUTH_PASSWORD};

Related

Is there any function's result value must be used specifier In Typescript?

I want to specify that the function's return value must be used using typescript.
There is an attribute [[nodiscard]] in c++. Is there any similar attribute in Typescript?
Example:
function setSomeFields(someThing: MyClass) {
const other = new MyClass();
other.value = someThing.value;
//...
return other;
}
//...
// wanted: error or warning
setSomeFields(myClass);
// correct
const newMyClass = setSomeFields(myClass);
There was a discussion on eslint to for a no-unused-return-value rule that would give you the warning you want but a rule like that was never included. For now, the SonarJS plugin for eslint does seem to have such a rule.

populate object properties using lambda expression in typescript

Newbie Alert! I feel silly asking this question but I need someone to teach me the correct syntax.
I have code that looks like this:
let thing: INewThing;
thing.personId = another.personId;
thing.address = another.work.address;
thing.greades = another.subjectInfo.grades;
thing.isCurrent = another.student.isCurrent;
I know it can be written cleaner. I want to use a lamda expression, something like this:
let thing: INewThing => {
personId = another.personId,
address = another.work.address,
grades = another.subjectInfo.grades,
isCurrent = another.student.isCurrent
} as IThingUpdate;
I have looked and looked for an example. I have yet to find one that works for me. It's just syntax but no matter what I try it doesn't work.
You're just looking to create a new object, which is a pretty different thing from a "lambda" (function). Just declare the object. You don't need a function.
const thing = {
personId: another.personId,
address: another.work.address,
// use the correct spelling below - no 'greades'
grades: another.subjectInfo.grades,
isCurrent: another.student.isCurrent,
};
If the another is typed properly, that should be sufficient.
If the another object had more properties using the same path, another option would be to destructure those properties out, then declare the object with shorthand, eg:
const originalObj = { prop: 'val', nested: { foo: 'foo', bar: 'bar', unwanted: 'unwanted' } };
const { foo, bar } = originalObj.nested;
const thing = { foo, bar };
Destructuring like this, without putting the values into differently-named properties, helps reduce typos - if a property starts out, for example, as someLongPropertyName, putting it into a standalone identifier someLongPropertyName and then constructing an object with shorthand syntax ensures that the new object also has the exact property name someLongPropertyName (and not, for example, someLongPRopertyName - which isn't that uncommon of a mistake when using the more traditional object declaration format).
But since all the paths in your another object are different, this approach wouldn't work well in this particular situation.

What is the role of underscore in gjs?

In gjs docs I found that underscore is used to denote private variables, but what does it do when creating objects with new or calling methods? For example in default code that gets generated when creating extension:
...
let item = new PopupMenu.PopupMenuItem(_('Show Notification'));
item.connect('activate', () => {
Main.notify(_('Whatʼs up, folks?'));
});
this.menu.addMenuItem(item);
...
What you see there is the _() function, which is a shorthand for gettext(). In other words, it marks a string as translatable, and will load the translated string (if available) when it's run by the user.

Cannot pass array of string to function

I have this function:
function proc(unames: Array<string>){}
I try to pass it this:
import _ = require('lodash');
const usernames = _.flattenDeep([unames]).filter(function (item, index, arr) {
return item && arr.indexOf(item) === index;
});
const recipient = 'foobarbaz';
proc(usernames.concat(recipient));
I get this error:
Does anyone know how to mitigate this?
I tried this, and I get an even longer and crazier error:
function proc(unames: Array<string | ReadonlyArray<string>>){}
however, this made the error go away:
function proc(unames: Array<string | ReadonlyArray<any>>){}
not really sure what's going on.
The warning seems to be referring to the use of .concat() rather than proc().
When called on an Array, such as usernames, TypeScript is validating that the arguments given to .concat() are also Arrays.
To resolve the warning, you have a few options:
Since you're using Lodash, its own _.concat() allows for appending individual values, and TypeScript's validation should be aware of that:
const recipient = 'foobarbaz';
proc(_.concat(usernames, recipient));
Define recipient as an Array or wrap it when calling .concat():
const recipient = [ 'foobarbaz' ];
proc(usernames.concat(recipient));
const recipient = 'foobarbaz';
proc(usernames.concat( [recipient] ));
You may also be able to configure TypeScript to validate for a later version of ECMAScript. Between 5.1 and 2015 (6th edition) of the standard, the behavior of the built-in .concat() was changed to support individual values (by detecting spreadable).
For now, TypeScript is validating .concat() for 5.1 or older.

Calling function with callback defined as string

var method = 'serviceName.MethodName'
I Just want to call it like
serviceName.methodName(function(output callback){
});
Is there any approach to call it.thanks
There are two methods that I can think of now.
JS eval
You can use the javascript eval function to convert any string into code snippet like below. Although eval is a quick solution but should not be used unless you dont have any other option by your side.
var method = 'UserService.getData';
eval(method)();
Factory pattern
Use a below pattern to get the service
You would need to define the services in such a manner that you can access them using a pattern.
var Services = {
// UserService and AccountsService are again objects having some callable functions.
UserService : {getData: function(){}, getAge: function(){}},
AccountsService : {getData: function(){}, getAge: function(){}},
// getService is the heart of the code which will get you the required service depending on the string paramter you pass.
getService : function(serviceName){
var service = '';
switch(serviceName){
case 'User':
service = this.UserService;
break;
case 'Accounts':
service = this.AccountsService;
break;
}
return service;
}
}
You can use get the required service with below code
Services.getService('User')
I'm not aware of any way you can resolve the serviceName part of that string to an object, without using eval. So obviously you need to be extremely careful.
Perhaps:
if (method.match(/^[a-zA-Z0-9_]+\.[a-zA-Z0-9_]+$/) {
var servicePart = eval(method.split('.')[0]);
var methodPart = method.split('.')[1];
servicePart[methodPart](...)
}
There are two separate problems in your question:
How to access object property by property name (string)?
How to access object by it's name (string)?
Regarding the first problem - it is easy to access object property by string using the following notation:
const myObject = {
myProp: 1,
};
console.log(myObject['myProp']);
And regarding the second problem - it depends on what serviceName is:
if it is a property of some other object, then use someObject['serviceName']['MethodName']
if it is a local variable, consider using a Map (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) to associate strings with objects;

Resources