GAE - Having environment variables play nice with node.js apps - javascript

It seems like the environment variables in app.yaml are rendered in Python-like strings, where booleans like true become True and empty variables becomes None. Anyone have ideas on how to make it play nice with javascript without doing explicit conversion for all my variables?
const MY_ENV_VAR = (process.env.MY_ENV_VAR === 'None') ? null : process.env.MY_ENV_VAR;
Yes, I can write some function to do it. Wondering if anyone has a clever solution.

The only additional available configurations related to Javascript are for Node.js and they are quite simple. As per the official documentation of the app.yaml file, the option Javascript related is to set the runtime and that's it, unfortunately. There is not direct way to configure better usage for the environment variables.
Considering that and that, I agree with you, having better handling of environemt variables in Javascript would be better for a lot of cases. Due to that, I would recommend you to raise a Feature Request in Google's Public Issue Tracker, so they can take a look at it and verify the possibility of implementing it in the future.
Let me know if the information helped you!

Related

Check presence of object property during bulding phase

I am looking for a solution that helps me achieve this:
I would like to have at 'build' time an error throwed if I try doing this:
var ciao = {
wow: 'ciaoooo',
}
console.log(ciao.wowe); // this should be an error because the prop does not exist
I have tried Typescript and it does the jobs, but it seems an overkill use it only for this. I was wondering if there was something for ESLint or something else that can help me with this type of problem.
You're asking for features of a statically typed language. If you want reliable information about variables on build time, you'll need this "overkill" of defining interfaces and types. TypeScript, however, is optionally typed, which might be a good compromise if you want static types for your public interfaces.
If you want type checking but don't want to use a transpiler, you could also try Flow which tries to derive type information just from your code as much as possible. However, its capabilities without additional type information are very limited.
Concerning your actual question: I think it would be possible to derive type information within module (or file) boundaries with ESLint or Babel. As long as you are using that object just within these boundaries, static analysis can probably help you. But beyond that, I don't think it's reliably feasible because of the dynamic nature of JavaScript. Unfortunately, I don't know such a rule or plugin.
ESLint doesn't have a rule like that. It would be very hard to create a rule that would be able to catch all possible cases for this. ESLint relies on Escope to track declared variables, but Escope doesn't track object properties, and there are just too many ways to add a property to a declared object.

Closure Compiler: How to separate and control compilation/minification passes?

The Google Closure Compiler is a powerful compiler and minifier for JS, which gives a lot of optimization options such as renaming variables, removing dead codes, collapsing variable declarations, rewriting control flow structures and etc.
What I want is to separately apply one or some of these optimizations on an input JS program. For example, I may want to rename variables with short names, but not to remove dead codes. How can I achieve this kind of detailed compilation pass control? Does the source code of CC expose specific interfaces to do this customization, or I should write my own pass(If so, how am I supposed to start?).
The command line features do offer several options for controlling the compilation, but are insufficient to fit what I want above. Since the source code is kinda complicated and few detailed design documentation can be found, I am truly stuck here. Any insights would be appreciated, thanks :)
Take a look at DefaultPassConfig. That class lists all the passes that are run during the compilation, based on what options are set in the CompilerOptions. Some of the CompilerOptions can be controlled from the command line, but we generally try to keep the compiler relatively simple and easy to use, and not ask users to make decisions about a bunch of different compiler flags. Plus, there are some passes that actually increase the code size, but they do it in such a way that it makes it easier for some later pass to decrease it afterwards.
Of course if you're just experimenting with the compiler or trying to understand how it works, you can turn on and off whichever passes you want, either by adding new flags, or just modifying DefaultPassConfig directly.

Writing reusable javascript modules & libraries.

I have been using javascript for a while now, and have authored my first content that has been used by other people.
The main reaction has been that my content does not play well with other code.
Unfortunately javascript does not have a lot of the normal tools for creating non-conflicting libraries, like namespaces and classes.
So what are the basic standards and tools for writing non-conflicting libraries in JS?
Javascript is a beautiful and broken programing language. Many programers coming from other languages often find its nature quite confusing if not down right annoying.
Javascript is missing a lot of the tools classical languages use to create clean classes and interfaces. But this does not mean that you can't write great libraries in JS, it just means that you need to learn how to use the tools it offers.
IMO the best resources on the subject of good modular code are:
Douglas Crockford's : javascript the good parts
Adequately Good's : Module Pattern: In-Depth
Paul Irish's : 10 things I learned from the jQuery Source
In all of these, the issue of conflicting code is addressed with at least the following two practices.
IFFE Wrapper
(function(dependency , undefined ) {
...dostuff...
})(dependency)
Wrapping your library in a IFFE is incredibly useful because it makes an immediate closure.This keeps you from over-populating the global namespace.
In addition : the above code Passes in the libraries dependencies as parameters. This both improves performance, and reduces side effects. For example jQuery passes in window via:(function(window){})(window)
Last but not least, we add but don't define the parameter undefined. This is often referred to as the idiot test. If someone changed undefined somewhere else in their code it could easily cause all kinds of trouble for your library. (function(undefined) {})()fixes this by "Not defining undefined" thus making it work as intended.
Conflict Handler
var _myLibrary = window.myLibrary;//Backs up whatever myLibrary's old value was
myLibrary = function(){...dostuff...};
myLibrary.prototype = {
getConflict : function() {
return window.myLibrary === myLibrary ?
_myLibrary || false : false;
};
}
Conflict Methods are very important when you do not know what other libraries yours will be used with. The above method is similar to jQuery's 'noConflict'.
In short, getConflict returns the overwritten myLibrary variable. If nothing was overwritten, then it returns false.
Having it return false is extremely useful as it can be used in an if statement like so.
if(myLibrary.getConflict()){
var foo = Object.create(myLibrary.getConflict());
}

Minimize and protect function names inside objects or in the global scope

I have tried to minimize my javascript files using YUI compressor, but to no end, I cannot get the names of functions inside objects to minimize. I have tried to minimize function names in the global scope, but have come to understand this is not possible. Is there any way to minimize javascript code in a way that renames the function names also? Perhaps by encapsulating them in an object somehow? Other than obfuscating, which I have read has quality implications, I cannot think of any other way to protect client side code. Thank You.
Closure-compiler does this when you use ADVANCED_OPTIMIZATIONS. Be warned however, that it does it to everything unless you take specific steps to prevent this. Converting a large code base to be compatible with ADVANCED_OPTIMIZATIONS can be daunting.
See Which Compilation Level is Right for Me?
If you are writing a library that others will consume, there are even more considerations.

Why am I finding Javascript/jQuery so difficult to get right?

My background is in C and I've picked up PHP, mySQL, HTML, CSS without too much issue.
But I'm finding Javascript/jQuery surprisingly difficult to get right.
Very frustrating.
Why?
It seems to violate a number of traditional programming principles (e.g. variable scope)
Undefined variables seem to appear out of nowhere and already have values associated with them. For example (from the jQuery docs):
$("a").click(function(event) {
event.preventDefault();
$('<div/>')
.append('default ' + event.type + ' prevented')
.appendTo('#log');
});
What exactly is "event"? Do I have to use this variable name? Should I just assume that this object is magically instantiated with the right stuff and I can use any of the methods list at the JQuery API?
There seems to be bunch of random rules (e.g. return false to stop a default action, but sometimes this doesn't work?)
Non-deterministic behavior when debugging. (e.g. I refresh the browser, try something and get result X for JS variables I'm watching in Firebug. I refresh again and I get result Y?)
Very messy looking code that is hard to follow. What happens when? I'm using Firebug and Chrome Developer Tools, but I'm not getting enough visibility.
It seems like everyday there's some random JS "rule" that comes up that I've never seen before in any of my JS books or tutorials.
What do I need to do to make Javascript/jQuery more deterministic, controlled, and logical to me?
Are there any resources that explain Javascript's quirks/gotchas?
Thanks!
1) It seems to violate a number of traditional programming principles (e.g. variable scope)
You need to declare variables using var, else it will go into the global scope.
2) Undefined variables seem to appear out of nowhere and already have values associated with them (how did this happen?)
This is possibly related to 1) and/or 4).
3) There seems to be bunch of random rules (e.g. return false to stop a default action, but sometimes this doesn't work?)
You need to let the handler return false as well. E.g. form onsubmit="return functionname()". You also need to return from the "main" function, not only from a closure (a function inside a function), referring to your previous question. It would only return into the "main" function and continue on.
4) Non-deterministic behavior when debugging. (e.g. I refresh the browser, try something and get result X for JS variables I'm watching in Firebug. I refresh again and I get result Y?)
Probably the code was executed before the HTML DOM was finished populating. You need to hook on window.onload or $(document).ready() whenever you want to execute stuff during page load.
5) Very messy looking code that is hard to follow. What happens when? I'm using Firebug and Chrome Developer Tools, but I'm not getting enough visibility.
I bet that you're talking about jQuery source? It's just a large library. You should after all not worry about this when debugging. Rather worry about your own code. However, make sure that you're looking at the unminified version of jQuery's source code.
See also:
JavaScript: the bad parts
What should every JavaScript programmer know
Douglas Crockford's "Javascript: The Good Parts" was an invaluable resource. Javascript plays a lot more like Lua, Lisp, or Python than C, it just happens to LOOK like C.
Link provided to Amazon; I snagged mine from O'Reilly.
To be honest, I think you have a good understanding. Some of my hangups were similar. The way that I have been moving on is "well, if that's the way it is, then that's the way it is". Just accept the idiosyncrasies and plow forward. PHP does some of the same things (variables can show up out of nowhere, etc...). Just code the way you want to code and if it works, then great!
Then after you get to that point start breaking out the profiler and see if there's anything that you can optimize.
Here are a couple of things:
If you understand CSS, then jQuery selectors should be easy. As far as the code goes, that's straightforward too if you can deal with chaining and JSON. EDIT: also, the jQuery documentation on everything is EXCELLENT! And There is no shortage of jQuery experts here on SO to help us noobs (and hopefully we can return the favor for newer noobs).
There is a scope to work with. (Basically) anything written outside of a function or object is in global scope. If you are inside of an object or function and use var then that sets the variable's scope
Javascript isn't like a C-based language (C++ or PHP even). It uses prototypes to deal with class/object relationships rather than a subclassing scheme.
The #1 thing that threw me for a loop is that any JS that appears anywhere on the page or that was included in <script> tags is fair game. If you have a global variable in one script, you can use that same variable in a completely different script and it will work. That may be what you mean about variables showing up out of nowhere. Also, there are some DOM based variables that can just "show up" too.
Anyways, I think that if you just plow ahead, you'll get some "AHA" moments. I'm a relative noob to programming, but I continually grow as long as I don't hang up on something that doesn't have too much of an impact on actually making the code run.
It's a language based on prototypal inheritance and is influenced by functional programming languages and the paradigm so it isn't completely just OO/Procedural like other languages. Variables are implied globals unless declared with var.
Please include an example?
return false exits out of the function as with any language's return statement. preventDefault() would be the DOM method to cancel the default behaviour of a link
Javascript is used primarily on the client side. Since there are many user agents, each of them have a different implementation of the DOM, which is very inconsistent, moreso than JS itself. Again, please include a real example to get a definitive answer.
You'll find messy looking code in any language, and maybe your lack of understanding perceives the code as messy, when in fact it isn't so bad. Or maybe you're looking at some minified/obfuscated code.
I recommend http://eloquentjavascript.net/ for learning aspects of Javascript.
Things you'll learn from the link above
lambdas
closures
Prototypal inheritance
Event based programming
Debugging
DOM
"JavaScript: The Good Parts" by Douglas Crockford is a good start
In your case, the appendices ("the bad parts" and "the awful parts") might be the most interesting :)
Crockford's "Javascript: The Good Parts" gives some common JS patterns that help with variable privatization and scoping. This is for javascript in general. For jQuery I just use the API. Also the Yui Theatre videos on javascript are quite good
Javascript can be a little tricky and some of it's functional aspects confuses people. If you actually learn and understand the language you'll find it really useful, most people just randomly start using it and then just hate.
Read javascript the good parts by crockford, it's really helpful: http://javascript.crockford.com/
Also make sure you understand closure. It's a fundamental that people don't get but often use.
In terms of variable scope, there are local and global variables. One of the gotchyas of variable scope can be seen in this example:
var thisIsAGlobalVariable
function anon () {
var thisIsALocalVariable
thisIsAGlobalVariable = 5; //if you don't use the var prefix inside a fn, it becomes global
}
You are finding it difficult because:
javascript has another kind of syntax.
javascript is dificult to debug
javascript has no autocompletion like c# etc) ?or does it
javascript has illogical rules (they become logical once you are known with them)
everything can be done in 1000 ways, and when you search for a solution, you will find 2000 answers :) where c#, php mostly have a good practice function u "should/could" use
However, I started using js/jquery a half year ago, with the same reasoning as you do, and I stuck to it, and now I use it daily to enhance my webapps.
I just love it (especcially jquery). It is a life saver, I know what and where to look, I can do about anything with it.
Everything seems logical.
If I can give you one advice: javascript/jquery is a sour apple, but just hang in there, bit trough and you won't regret it.
also, a loooot of people use it and are always willing to lend a hand if needed (I know I do)
Javascript is tricky. You don't have a compiler watching your back. To compensate, unit testing becomes more important. I've been doing my unit testing with jQuery/QUnit, but I recently started using Jasmine (http://github.com/pivotal/jasmine) and I recommend it 200%. Its a great testing framework.
If you're not familiar with testing, or testing with javascript, I'd highly recommend finding unit tests for other OSS javascript projects (hopefully for code you could use) and seeing how they test it.
With unit tests, you'll make the same mistakes, but catch them much sooner and with less grief. And if your tests are good, the mistakes won't come back after you fix tham.
I don't know how much UI design you have done in C, but the event variable only shows up when it is sent by the caller and the handler needs to, well, handle the object. If you do reading on event object, the confusion in q #2 should go away.
There is no event handling in PHP, so I think you have not came across this issue in the past. JavaScript is a programming language with its own purpose, so it was designed to work for that specific purpose.
Maybe you have to link your code to an HTML onclick="event()" button to fire off as the event.

Categories

Resources