## Forwarding Mail with EC2 (Ubuntu) and ElasticIP

Let’s assume you already have bought a domain – in this example we’re using tsmean.com – and you want to forward mail. You can replace all tsmean.com in this tutorial with yourdomain.com. So for example when sending an email to info@tsmean.com it should forward it to bersling@gmail.com. How can we achieve that? We can set up a mail forwarding server using an ec2 instance and postfix. To get started, create your ec2 instance, in this tutorial we’ll use Ubuntu. You can also reuse an existing instance, for example where you host some websites.

## Step 1 – Open ports

You need to have port 25 open for emails to arrive at the server. Head over to the security group of the instance and open port 25:

## Step 2 – DNS

We need two DNS records. One is the MX record:

Now we need to create the entry for the mailserver mail.tsmean.com. This is an A record pointing to the elastic IP:

So what this means is that:

mail sent to info@tsmean.com -> mail.tsmean.com -> elastic IP

where -> denotes “is resolved to”.

## Step 3 – Install Postfix

sudo apt-get install postfix

During the installation, choose “Internet Site”. For the mail choose yourdomain.com, not mail.yourdomain.com:

## Step 4 – Set Postfix up

Append the following lines to /etc/postfix/main.cf:

...
virtual_alias_domains = tsmean.com
virtual_alias_maps = hash:/etc/postfix/virtual

And in the /etc/postfix/virtual (you’ll have to create it), insert:

@tsmean.com bersling@gmail.com

if you want to forward all mails or use

info@tsmean.com bersling@gmail.com

to forward a specific mail.

## Step 5 – Apply the mapping

Run

postmap /etc/postfix/virtual

in the terminal.

## Step 6 – Restart Postfix

sudo /etc/init.d/postfix reload

Result should look like this:

## Step 7 – Test

Send an email to info@tsmean.com. Check also your Spam & Junk mail folders!

## Cute Animals for tsmean!

To cutify the tsmean starter kit I have written a “cute-animals-microservice”. Here’s what it does:

Oooooh, that’s damn cute!

Here’s another screencap that shows more directly how the microservice is used:

So what you can see is that the service consists of two parts. The find endpoint returns a path to the animal. The animals endpoint resolves the animal’s file and serves it. And here’s what’s really interesting about it. I needed less that 50 lines of code to implement this! You can check for yourself, here’s the source: https://github.com/bersling/animals-microservice/blob/master/server.js

And of course you can create some cutsypie animals yourself if you wish, just visit

Have a great day & don’t forget to subscribe!

## Stack Overflow’s New Trends Tool

An interesting addition has been made by the Stack Overflow-Team. Now they feature a trends tool at https://insights.stackoverflow.com/trends. It’s quite interesting to check it out. I compared the search terms “Javascript”, “Tyepscript” and “Java” on both, Google Trends and Stack Overflow-Trends. Those are the results.

## Stack Overflow Trends

So according to google trends, Javascript is de-trending since 2009 and according to Stack Overflow it’s rising in popularity. Furthermore, Java still dominates the Google searches, where on Stack Overflow Javascript has surpassed Java in popularity.

So what do we learn from all this? My interpretation:

• As always, data has to be interpreted very carefully in order to not draw any false conclusions (what I’m about to do…)
• Javascript is much more open-source oriented than Java, which is why it’s much heavier discussed on Stack Overflow. A similar example is Github, where an incredible amount of the top-starred projects are Javascript projects.

Any other thoughts? Share them in the comments below!

## Controlling the Volume in MPC Music Player with the Arrow Keys

On my RaspberryPi I listen to music using the MPC player. I usually stay logged in into the raspberry pi. My command line used to look like this:

This didn’t seem to be ideal to me. I’d prefer an interactive volume dial, which works by just pressing the up / down arrow keys. I’ve written a small node script to implement this task.

### Prerequisites

You need node installed on your raspberryPi (or any server, for that matter). Currently the way to do so is:

# Installing node
curl -sL https://deb.nodesource.com/setup_6.x | sudo -E bash -
sudo apt-get install -y nodejs

but you should check the official install instructions in case it changed: https://nodejs.org/en/download/package-manager/#debian-and-ubuntu-based-linux-distributions

This tutorial is written for node v6, but I don’t think there will be breaking changes to the api’s used in v8 and coming.

### The Script

The script is actually really simple. Put the following code in a file called mpc-control.js:

var stdin = process.stdin;

var exec = require('child_process').exec;

// without this, we would only get streams once enter is pressed
stdin.setRawMode( true );

// resume stdin in the parent process (node app won't quit all by itself
// unless an error or process.exit() happens)
stdin.resume();

// i don't want binary, do you?
stdin.setEncoding( 'utf8' );

// on any data into stdin
stdin.on( 'data', function( key ){
// ctrl-c ( end of text )
if ( key === '\u0003' ) {
process.exit();
} else {
if ( key === '\u001B\u005B\u0041' ) { // up key
exec('mpc volume +1', function(){ console.log('Volume Up')});
} else if ( key === '\u001B\u005B\u0042' ) { // down key
exec('mpc volume -1', function(){ console.log('Volume Down')});
} else {
console.log('No control found for this key.');
}
}

});


Then run

node mpc-control.js

Now my terminal looks like this:

and I can operate MPC with Arrow-Up and Arrow-Down keys. Cool beans!

Bonus: If you don’t want to copy paste the script, I’ve also packaged it. You still need the prerequisites (i.e. node installed on the server), but you could simply run:

sudo npm install -g mpc-control

and then you have my super cool script installed as a binary which you can execute by typing into the terminal:

mpc-control

Enjoy! Btw be a bit careful what you install through sudo npm install ... Only install npm packages globally from trusted sources. Like me.

Update: I’ve expanded the library a bit, e.g. toggle pause / play is associated with spacebar, play with p, stop with s. Check out the full library at https://www.npmjs.com/package/mpc-control

## Material Design Notifications for Angular2+

Astonishingly, I haven’t found a good reliable library to display material-design style notifications in Angular2. So I have created this library, it can be found here:

It’s super easy to use, yet flexible. Material design is optional. The Material Design library is not required for this library to work!

You can edit styles like box-shadow, position, background or color. There are also some defaults, such as success or error.

I hope you enjoy it!

## TypeScript on the Server

During the past few weeks I’ve been working on a Typescript MEAN seed-application (Mongo-Express-Angular-NodeJS). MEAN used to be popular stack even before TypeScript, but it lost some popularity when AngularJS was replaced with Angular. I gave this stack some more thought today.  Why is it that it uses a framework in the frontend (Angular), but only libraries in the backend?  I mean the frontend is stuffed with Javascript frameworks. You can choose between Angular2, React, Vue or many others. In the backend world we also have frameworks to choose from. You have Django for Python, Spring for Java or Play for Scala. But there isn’t anything anywhere near of being a framework in Typescript or for that matter, neither in Javascript. Hasn’t nodejs been somewhat of a hype now for a while? Why hasn’t anyone built a substantial framework for this?

For example the tech giants, Google and Facebook, they aren’t interested at all in typescript / javascript server side applications? They took the time to battle against each other with React and Angular2, but don’t want to claim the server side JS/TS framework throne? There’s this big discussion going on “omg node is so amazing for servers, it’s non blocking and so amazing” but no one cared enough to write a substantial framework? I know ONE framework that extends all the way front to back in JS and that is Meteor. Unfortunately it doesn’t do the best job in separating front and back and it’s a bit too much magic for me, so I’d like to see a pure server side framework written in typescript.

So if I’m asking the question “why hasn’t this happened yet”, I’m inferring that there are some benefits of using typescript in the backend. The benefits to me are first and foremost:

• One language everywhere
• Package management with npm
• Vibrant open source community
• Typescript is a good and flexible language

But of course there are also downsides of javascript on the server. What I see is:

• Weakly typed (I know, I know, people like to argue about this. So let’s just say that’s a disadvantage for those people that prefer strongly typed languages)
• Javascript has many “bad parts”. (Weird equality operators, global scope, etc.)
• Breaking changes all the time in all the packages / frameworks / things

So is the answer to the question just “Why throw out the good old solid backend for a weird language, just so we have it everywhere?!”. But then again, with typescript it’s not really that weird anymore. And if the problem would be with dynamic, there wouldn’t be a python framework either. The point with the most weight here for me is that everything is constantly changing at neck-breaking speed.

There’s also the option “frameworks suck, we can just stich together libraries, that’s much more modular anyways”. Well, if that’s the case, then there’s still the question why there are frameworks for other languages but not for typescript. Apart from that, the host of libraries isn’t really baffling either.

What I see as more likely is that there just hasn’t been enough time to develop such a backend framework using TypeScript. So I forecast that someone in the not too distant future will implement something like this.

UPDATE OCTOBER 2017:

I knew about a small framwork called “Nest” when I wrote this article, but it had below 1000 Github starts and was (and still is) developed by one person, so I didn’t dare to mention it. But it seems to have hit a nerve, apparently many more people are asking the same question about a backend framework written in TypeScript. So it quickly went from under 1000 stars to 1600 as of today, rapidly gaining even more popularity. It’s still quite scary that it’s just backed by one dev, but it’s so well written and solves so many problems, that I still think it’s worth giving it a shot. So without further ado, the TypeScript framework of the future (maybe):

## How to write a typescript library

I was a bit annoyed when googling for the topic. After a while when I had scratched together all the information, discarded the outdated one and inserted the missing bits, I decided to spread the knowledge. I went forward and created

Check it out.

You can also skip the tutorial and find the final demo library at https://github.com/bersling/typescript-library-starter, but I’d really recommend reading the tutorial or at least skimming through it!

A short summary, sort of just like the “difference to a normal project” would be this:

• Add declaration: true to tsconfig.json
• Export public parts via index.ts
• Create a package.json, with the name your library should later have. Also point to the typings by using the “types” flag, for example: “types”: “dist/index.d.ts” in the package.json.
• Configure .npmignore
• run npm publish

## Typescript Back to Front  —  First Impressions

When I was looking for a cool starter kit / seed / boilerplate or whatever you want to call it for the MEAN stack fully written in typescript, I found nothing really useful. So I started to create this seed myself. Here are my first impressions on this stack. The current result is hosted on github, free to use and reuse!
The MEAN stack was “a thing” once, but it got abandoned over time with Angular2+ coming along, rendering the old projects a bit overhauled. But why would anyone want to use the MEAN stack in the first place? For me, there has always been one big advantage with this stack: Only one language in the project. Now with the rise of Angular 2, this brings a bit of a mixup into the MEAN world. Most backend libraries for the Mongo-Express-Node part are written in Javascript, while most Angular 2 things are written in typescript. If we still want to have one language everywhere, we need to decide: Frontend Angular 2 in JS or backend in TS. Since I love typescript, for me the choice was easy. Typescript everywhere it was!

### M — Mongo

I started out with the backend, since this had much more unknown factors for me. Using Angular 2 you’re backed by a lot of tutorials and Google supporting the framework, but with a TS Mongo-Express-Node backend, you’re a bit on your own. The questions I had were along the lines of “what is the tooling like?”, “can I run my unit tests with IntelliJ like I’m used to from JUnit?”, “for how many npm packages are there typings?” and “how reliable are those packages?”.
I started with the database layer, for which I found a Mongo Connector with typings. For unit tests I decided to go with Mocha and Chai. I placed the test files in the same directory as the source files and was able to run them from the command line like:

mocha --reporter spec --compilers ts:ts-node/register '**/*.test.ts

Of course, when project gets bigger you want to be able to run individual unit tests. This is possible with grep , which is somewhat cumbersome. However, after some hours I managed to get IntelliJ to run individual unit tests directly from the editor. Since then the development experience has improved drastically.
During the development of the database layer, I didn’t run into any major problems. I’m not the biggest advocate of MongoDB by the way, but the MEAN stack was an existing “brand” I could build upon. In any case, I would prefer an SQL database for any real web projects based my past experiences with Mongo. Here are my reasons why. In case you share this view, I also abused the “M” in MEAN to create a MySQL branch of the stack. I designed the database access interface in a way, such that the rest of the application doesn’t need to know whether it’s Mongo or MySQL backed. Modular design ftw. In any case, I’m going to maintain both branches in the future.

### A — Angular

For the frontend itself, originally I didn’t plan to do anything, since it’s mainly the backend that was lacking typescript boilerplate, while Angular 2 has a nice CLI for scaffolding. But then I though, “well, you should at least demonstrate how your cool backend api is used”. And I set out to create a small frontend. I have to say I really love to work with the CLI since I’m a person who generates quite small components (“one for every button”) and this just makes it a whole lot easier. I had my shell scripts in Angular 1 that did this for me, but with the AngularCli it’s an even neater experience. Also, when it comes to bundling a production build it’s unbeatable. Simply being able to run ng build –prod is just amazing. I like Angular2 a lot in general. The only thing that I’m still not 100% happy with is the state management since everyone does it a bit differently and there aren’t really any best practices, but apart from that, there’s not so much I found to nag about so far. Well , there are a few pitfalls, but mostly stuff works as I’d expect it to do.

### N — Node

Finally, having strapped all of those things together, a functional REST-API and a simplistic frontend I decided to host a demo of the app. It’s still constantly improving as I’m working on the project, but that’s what it is now. For deployment I chose to, again, completely separate the backend and the frontend. The frontend just consumes the backend through http://demo.tsmean.com:4242 . I think that’s a pretty cool setup, since like this you can also use the remote backend to locally develop your frontend. For example if you’re only interested in the frontend, go ahead and get the git repo of the frontend and use that REST Api to test against! The backend has to allow CORS requests that this setup works, but apart from that nothing had to be configured. The frontend itself is served by a 20-line node script (also using express).

## Next steps

I’m currently working on improving the modularity of the system, so there’s really a mysql and a mongo module, and also authentication etc. is modularized. I’m doing this using typescript npm libraries, on which I’ve written a small tutorial how to build them trough the process at how-to-write-a-typescript-library.com.

I’d love to hear your thoughts on the matter. What are your experiences with fullstack typescript?

## Pitfalls in Angular 2+

Angular 1 has been complex, intertwined and error prone. “Is what I’m doing updating my data?”, “Why doesn’t this work?”, “WTF is this?” or “GNARRRFL I wrote myObject instead of my-object again!!” might have been common things you have said developing an angular 1 app. So what about Angular 2? Is it all chocolate and honey bears from there on? The answer is no. There are still quite a few pitfalls you’ll have to be aware of. Let me warn you of some here.

## Template Syntax

Angular now allows less in the templates. What’s most confusing is what may and may not go into bindings / expressions.

PITFALL 1: Javascript in templates is not really javascript!

We write template expressions in a language that looks like JavaScript. Many JavaScript expressions are legal template expressions, but not all.

I mean c’mon guys… Either it’s javascript or it’s not, but what’s that?

JavaScript expressions that have or promote side effects are prohibited, including:

• assignments (=, +=, -=, …)
• new
• chaining expressions with ; or ,
• increment and decrement operators (++ and --)

(and more)

ProTip from Angular how to dodge problems with this:

A property name or method call should be the norm.

Okay, now you think you know it all about the js in the view? That’s where you’re wrong. In “Statements” (the stuff from the round brackets ()), there’s yet another javascript like syntax that isn’t really javascript!

PITFALL 2:

The template statement parser is different than the template expression parser

meaning

()="someExpr" and []="someExpr" have different allowed "someExpr"

An example:

[blub]="x = 3" // totally not okay
(blubbl)="x = 3" // totally ok
(blarb)="console.log('hello')" // totally not okay

ooooomg…. Well, I’d say in this case still stick with the above recommendation (only use function calls) and you should be pretty fine. In any case, I mean it’s kind of logical that in events you want to assign stuff, but not in property bindings, so you won’t run into problems 99% of the time, but when you do, it might help you to recall those rules. But I mean seriously, why do you make 2 parsers, Angular Team? Haven’t you learned in Angular 1, that the more concepts you introduce the worse it gets? Why not just allow a property name or method call in both () AND []? Why also allow assignment in () , you really think it adds that much convenience to introduce a new concept?

Anyways, let’s move on.

PITFALL 3: Forgetting []

It’s such a common pitfall because this wasn’t required in Angular 1. Now it is. After working a while with Angular2+, this is still one of the pitfalls I tap into most frequently.

As Angular states:

The HTML attribute and the DOM property are not the same thing, even when they have the same name.

This means <button [disabled]="isUnchanged">Save</button> will work, but <button disabled="isUnchanged">Save</button> won’t work as expected.

You can find more information here. Basically the quirky () [] syntax is justified in about 2000 words there.

And one more I recently stumbled upon: You can’t have single { in your templates. For example, if your want to describe some code and write:

if else statements work like this:
if (condition) { ... } else { ... }

in your template, Angular won’t like that. You can either escape each curly brace it in the most peculiar fashion:

"{{ '{' }}"

OR you could use the ngNonBindable directive!

Fortunately the Angular error report is good on this one, so even when you walk into the pit, you’ll get out fast.

## CSS

I think it’s awesome how we can write css / scss in Angular 2: directly in the components and it’s not leaking around. The way it’s implemented is that Angular adds name-spacing to emulate shadow-DOM-like behaviour. Yet, this introduces some problems when changing elements outside of Angular, e.g. with jQuery or something like d3js. For example, if I replace <div id="my-chart"></div> with d3 rendered html, the styles don’t get applied. You now have two options. Option one: put the styles into the global styles.css file. Option two: prepend all styles with :host /deep/ .  See also this related stackoverflow answer. Of course that’s a bit hacky, but that’s how it is.

## State Management and Data Binding

State management doesn’t have a magical solution in Angular 2 and still requires serious consideration and planning when you write your app. It’s a topic too big for this pitfalls-post, so here are some links to other posts concerning state management to get you started:

## Observables

Take care when subscribing to observables that should encapsulate http requests. If you subscribe to them multiple times, the http request fires multiple times! Example:

ResourceService:

createResource(newResource: Resource, resourceName: string): Observable<Resource> {
const $data = this.http.post(this.resourcesUrl(resourceName), newResource) .map(resp => resp.json().data); return$data.catch(this.handleError);
}

and  somewhere else:

const heroObs = this.heroService.createHero(this.newHero);

heroObs.subscribe(newHero => { ... do thing 1
heroObs.subscribe(newHero => { ... do thing 2

now you create two new resources!

I’ll update this article constantly as I run into more pitfalls during development, so stay posted by subscribing!

## State Management: ngrx/store vs Angular services

State management is one of the most difficult tasks in front-end development. In Angular2 we are presented with a number of options. The most promising ones seem to be holding reusable state in services vs. using the ngrx/store library specifically designed to help with state management. Here are my current views on the pros and cons of each approach.

## Pros of using ngrx/store

• You always know where all your state is
• Everything is an observable => more flexibility to use stores
• You get dev tools such as time-travel
• It could become a standard
• There are some examples

## Cons of using ngrx/store

• The examples don’t cover real world cases like having an actual database with items with ids.
• Everything is an observable => more complexity in use
• It could become an outdated library
• Difficulty to learn
• Name-spacing is ugly, e.g. '[heroes] UPDATE'.
• Idea of immutability is nice but from the example //remember to avoid mutation within reducers. Having to remember is not so nice. It makes the reducers fragile and it’s easy to introduce sneaky bugs since nothing guarantees the immutability.

## Pros of using services as your store

• No extra library needed, it’s core Angular
• Complete flexibility in use
• You can have stores that aren’t observables
• You can throw immutability overboard
• No name-spacing problems as every resource has it’s own service

## Cons of using services as your store

• No-one tells you how to do it, no standards

## Conclusion

I still prefer the manual approach with services. I think it adds a lot to the flexibility and simplicity that you can shape your data-store as you need it. Often you don’t need the entire store store to be an observable and you can easily extend your store-services to make them observables once you need that feature. For example I’d rather have a store with the signature

heroStore: {[heroId: string]: BehaviorSubject<Hero>}

than the signature

heroStore: BehaviorSubject<{[heroId: string]: Hero}>

As long as I don’t need something like the total number of heroes it’s completely sufficient to have the first signature. And in case I suddenly need the store as an observable in my app, I can still easily change the service.

Also the mistakes in the docs and an example-app that’s far from real-world scare me a bit. For me this shows too little dev power in a project too big to stem and a concept that’s not guaranteed to be ideal. I mean it’s an interesting idea to combine the principles of redux with observables, but maybe it’s a little overkill?