match-when - Pattern Matching for Modern JavaScript

I was working on an internal tool at iAdvize during our hack days (fr). This tool is representing our micro-service architecture and every of its components in a near real-time graph (I may open-source it in the future).

Somewhere in the graph relationship code I thought wait a minute, would it be awesome to use some pattern-matching there? So I tried to write some syntax that could exist for it...

... and of course it failed.

It was 6PM so the good news was I would have all the time I wanted to see if it could be possible to implement a pattern-matching solution that was both syntaxically short, would work well with functional-style code while using JavaScript ES6 features for conciseness.

I ended up with this syntax:

Which works also that way:

Underneath it uses enhanced object literals, symbols and, sadly, JSON serialization/deserialization to pass object properties.

Later that night match-when was available on Github.


Managing various NodeJS version per projects

How to manage multiple projects with their own NodeJS version? 

Simple, use nvm.

But how do I automatically change NodeJS version?

Simple use a .nvmrc inside each project and a .env loaded by autoenv when cding inside the project to automatically change NodeJS version between project just by using cd.

It's not DRY, I want to stay DRY and don't duplicate NodeJS version inside both package.json and .nvmrc, what do I do?

Well, remove your .nvmrc and replace .env content by:

And now you're DRY :)


Automatic constraints as a team maturity accelerator for startups

I gave a talk at Polytech Nantes on how we use automated constraints at iAdvize and Redsmin to speed up our team maturity and efficiency as well as raising up the overall quality automatically. The slides are included below:


Be automatically notified when your SSL certificate is invalid


Today I received an email on Redsmin Support from @christiankakesa telling me that one of the SSL certificate we use for payments.redsmin.com was expired.


Indeed the payments website — that we use to recover failed Stripe payments thanks to Bestunning — was unusable with a NET::ERR_CERT_DATE_INVALID exception (on Google Chrome). We had not be notified automatically, I had not been notified automatically, it goes against everything I stand for and we had to fix this.


We already use Jenkins for a lot of things at Redsmin/Bringr (and now iAdvize) and it knows how to run jobs daily to check multiple things. Why not using it to verify SSL certificates validity as well?

So create a new jenkins job, configure it to be built daily (or even hourly) and run the shell script above:

Don't forget to configure email notifications in case of unstable build and you're done! Next time something's wrong with your website or app SSL certificate you will be notified.


[Book Review] 14 quotes I liked in Rework

I finally took the time to read Rework by Jason Fried & David Heinemeier Hansson from 37signals so as a memo, I'm sharing there the best parts I found:
"Workaholics aren't heroes. They don't save the day, they just use it up. The real hero is already home because she figured out a faster way to get things done."

"You want your customers to say, “This makes my life better.” You want to feel that if you stopped doing what you do, people would notice."

"The most important thing is to begin. So get a camera, hit Record, and start shooting."

"[...] keep in mind why you're doing what you're doing. Great businesses have a point of view, not just a product or sevice."

"Whenever you can, swap “Let's think about it” for “Let's decide on it.” Commit to making decisions. Don't wait for the perfect solution. Decide and move forward."

"When things aren't working, the natural inclination is to throw more at the problem. More people, time, and money. All that ends up doing is making the problem bigger. The right way to gi is the opposite direction: Cut back."

"The core of your business should be built around things that won't change. Things that people are going to want today and ten years from now."

"Interruption is the enemy of productivity"

"Meeting are toxic [...] set a timer. When it rings, meeting's over. Period."

"Make tiny decisions [...] When you make tiny decisions, you can't make big mistakes. These small decisions mean you can afford to change. There's no big penalty if you mess up. You just fix it."

"[...] you can't beat something who's making the rules. You need to redefine the rules, not just build something slightly better."

"[...] build an audience. Speak, write, blog, tweet, make videos [...]. Share information that's valuable and you'll [...] build a loyal audience."

"As a business owner, you should share everything you know [...]."

"Marketing is not a department [...]" everything you do (email, support, in-app error messages, phone calls, ...) is marketing.


PM2 tips - uncommon ssh port, cluster_mode and deploy troubleshooting

Note: PM2 own code quality is bad and cluster_mode is not production ready. I would not recommend to use PM2, anywhere. You have been warned.

How to use a different ssh port for PM2

Since pm2-deploy directly forward the host string to ssh, you can simply use:

"host": "HOSTNAME -p PORT"

inside the configuration file.

How to use cluster_mode in PM2

Make your app instances listen on port 8000 and pm2 will load-balance any request on 8080 to your app instances.

Troubleshooting pm2 deploy

pm2-deploy outputs its log into /tmp/pm2-deploy.log so if you don't understand why pm2 deploy is not working, a tail -f /tmp/pm2-deploy.log might help.


[Book Review] Mastering JavaScript Design Patterns

Mastering JavaScript Design Patterns (MJDP) is another book Packt graciously sent me. This book is divided in two parts. The first part is about Gang Of Four (GoF) classical Design Patterns the other part is about other well know patterns.

TL;DR: Overall the book is good enough and will be perfect for developers with little experience in software development.

However be careful with the following points below:
  • UML diagrams are not descriptive as they should be, "memberName" should not be written multiple times as class attributes
  • The part where the author said that singleton could not be created in JavaScript in a OOP way is plain wrong
  • In the Functional Programming chapter, JavaScript examples could have been written better. Using a for loop instead of map (IE9+) is disappointing (to say the least!)
  • The MV* chapter does not follow the Separation of Concerns principle well enough
    • View initialization and rendering are done inside the constructor (they should not be)
    • Model attributes are too often manipulated inside the controller
    • State information is duplicated (e.g. IsValid in ValidationResult)
    • A dispose (or release) method is missing for clean life-cycle management
    • bind (IE9+) should be used instead of the old _this workaround


[Book Review] AngularJS UI Development

Once again Packt graciously sent me AngularJS UI Development book for reviewing and I am grateful for that.
But I will be brief. It's one of the worst written "technical" book I've ever read.

  • silly chapter ordering and subject choices
  • chapter subjects are glanced over, chapters feel like unfinished copy/pasted tutorials
  • code samples should have never been approved during the review
    • separation of concerns is not respected most of the time
      • and by most of the time I mean 95% of the time, not 60%
    • there are so much state in these examples, everywhere
  • this book does not even talk about routing and state management
    • ... well, unless you wait until chapter 10 and consider a one-route single page application (SPA) good enough.
    • In a book about UI Development, view state management is essential so in my humble opinion the book should have started with it. 

When we think about AngularJS UI Development, the first library that come to mind is ui-router. Instead we have a chapter 3 about google maps integration, chapter 5 about ng-animate, chapter 6 about charts integration and so on...

Okay, let's stop there and just say that I won't recommend this book to anyone, ever.

If you are new to AngularJS and are looking for a serious book on that matter consider MEAN Web Development, at least this one is well written.


[BrainDump] Versioning an HTTP API

I sometime share privately what I call a #BrainDump over a specific subject I just learned or thought about. A #BrainDump can be described as a snapshot of my current state of mind (or state of art in the current blog post) over a particular subject.

First step, let's specify an API version

    • ... in the header
      • cons:
        • requires an http client (curl/postman) to test endpoint
      • ... with accept (accept: application/vnd.haveibeenpwned+json; version=2.0)
        • pros:
          • allow the client to specify both a schema and a version
        • cons:
          • just like the other solutions, this one is also not standard: "Per the RFC, accept headers should only be used to specify the media type. Versioning is not media type, therefore using accept headers is IMO misuse.source
      • ... with user-defined header  (X-VersionX-Restful-Interface-Version)
    • ... in the URI
      • pros:
        • easy to try GET requests directly from the browser
      • cons:
        • not standard per HTTP RFC
        • does not respect REST principle
      • ... inside a sub-domain (v1.api.domain.com)
        • pros:
          • easy to configure backends with a reverse-proxy
      • ... inside the path 
        • format: /v1/
          • pros:
            • easy to configure backends with a reverse-proxy
          • used by:
        • format: /YYYYMMDD
          • pros:
            • the client does not need to remember API version
            • the client only asks for the API that was working at YYYYMMDD
          • cons:
            • between the client development and release the API may have changed
          • used by:
      • ... inside the query-string (?v=1)
        • wait, what?
    • ... once the request has been authenticated
      • assumption: each requests needs the be authenticated, then retrieve what API version the authenticated user has configured
      • pros:
        • easy to do analytics on API version usage
        • easy to inform users that access soon-to-be-removed API version
      • cons:
        • an authentication step is required
        • a user can only access to one API version at a time
        • no explicit contract between the client and the server 
        • the API version selection is hidden from the client
      • used by:

Then handle multiple API versions server-side

    • ... forwarding each request to the right API server using a reverse-proxy
      • pros:
        • stale API servers are easier to remove from production
      • cons:
        • it requires (at least) 2 running servers per API version
        • need to maintain multiple HTTP servers (branch) with security patches
        • need to maintain multiple running API servers in various versions
    • ... putting every version inside a single-code base, servers are load-balanced
      • each running server have to handle multiple-versions
      • pros:
        • a lot less duplicated code between handlers
        • easier server management
      • cons:
        • business models are often poluted with old behaviours
    • ... using an API migration middleware server (this is a work-in-progress)
      • assumption: the latest API version always exposes more data than the previous one
        • In other words the huge limitation of that approach is that changes HAVE TO be additive
      • how it works:
        • HTTP front <-> API Middleware Server (APIMS) <-> Up-to-date API Server (APIS)
          • for latency, both the APIMS and the APIS SHOULD be on the same node
          • for availability, of course both the APMS and APIS should be replicated across servers
        • Each HTTP request SHOULD go through the APIMS
          • if the request specify v4 and that latest API version is v6 the middleware
          • APIMS receiving request from client (asking for v4)
            •  -> up(req) (v4->v5)
              •  -> up(req) (v5->v6)
                •  -> forward request to APIS
                  • APIS (v6) process the request
                • <- APIS response
              • <- down(res) (v6->v5)
            • <- down(res) (v5->v4)
          • APIMS sending response to client
          • Note: it should be possible to bypass the APIMS if the requested API version is the latest one
        • a migration file CAN be implemented for each new version (vN-1->vN). Each migration file should implement the above interface
          • up(req: Request, next : Function(error))
            • used to update an API request from vN to vN+1
            • if an `error` is specified in `next` the APIMS can directly answer the request thus breaking the contract
          • down(res: Response, next: Function(error))
            • used to downgrade an API response from vN to vN-1
      • pros:
        • API versioning is decoupled from the API server
        • developers only needs to deploy the latest API version
        • devops only need to ensure the latest API version is running
      • cons:
        • does not handle every case 
          • e.g. a piece of data was available in v1 but is not available in v2 thus the middleware can't add it on the down stage

This post is simply an overview of documented practice, if you know (or better: use) other way to version HTTP API, don't hesitate to share them in the comment section below!

[Book Review] MEAN Web Development

After my review of Getting Started With Grunt and Lodash essentials this time Packt Publishing contacted me to review MEAN Web Development. Since Redsmin was first built over the ME(A)N stack and a lot of our applications at Bringr are built using NodeJS/AngularJS I happily accepted the offer, below is the review I posted on amazon.

Chapter 1 Introduction to MEAN

This chapter begins with a brief introduction to the MEAN stack and is then a deep step by step guide on how to install and run MongoDB, NodeJS, NPM both on Windows, Mac OS X and Linux. It's the perfect starting point for newcomers. I will simply add that it's a better practice ? to install NodeJS using Node Version Manager (nvm) that with the official installation software.

Chapter 2 - Getting Started with NodeJS

After a brief history of why Ryan Dahl created NodeJS the author dives into explaining event-driven programming. You will learn how work an event loop and how a webserver with a non-blocking event-loop (nginx) differs from a blocking web-server (apache) in terms of concurrent access performance and memory consumption. Then you'll take a look at closures and why they are useful in callbacks. Finally you'll learn how to write your first NodeJS http server along with your first connect middleware.

Chapter 3 - Building an Express Web App

Time to go to the next step : writing your first Express application, managing sessions, using a template engine (EJS) and a routing scheme. This chapter takes the reader by the hand and is really descriptive on how to organize your application folder architecture and write your first application.
However instead of using configuration files by environments (e.g. production, staging and development) I would recommend the reader to use environment variables (using a module like common-env + autoenv) since it's a way more flexible approach. Another missing point is to warn the reader to add a "private:true" inside its package.json file otherwise it could publish its application on npm by mistake.

Chapter 4 - Introduction to Mongodb

Even if this chapter explains to new comers what MongoDB is, the author is clearly using too much superlative about MongoDB. It's important to recall that MongoDB is not a replacement for relational storage and that it must be used with care.

Chapter 5 - Introduction to Mongoose

Just like the previous chapter, this one is also well written. It explains each Mongoose features starting with schema, validation, virtuals, getter/setter and even DbRef. I would simply note that some conditionals in the code examples could be greatly simplified.

Chapter 6 - Managing User Auth Using Passport

Learn how to handle user creation/connection with PassportJS, using local auth or Facebook/Twitter/Google OAuth. The OAuth user creation mechanism described in the book does not allow a user to connect via multiple OAuth provider and is thus limited. The access_token refreshing mechanism, even if it's not implemented, should be at least given as an exercise for the reader.

Chapter 7 - Introduction AngularJS

Another really well written chapter, this time about AngularJS. From the history to the state of the art, you'll learn everything you need to know to build your first application with AngularJS from routing to services. Note that the authentication service code example does not respect the Inversion Of Control principle and should be rewritten to ask for $window.

Chapter 8 - Creating a MEAN CRUD Module

In this chapter, learn how to set CRUD (Create-Retrieve-Update-Delete) modules up from back (using mongoose) to front (using angularjs $ressource). The middleware approach to retrieve an article is subject to race-conditions. I will just add that a much more powerful alternative than ngressource is Restangular. Also I would advise the reader to prefer ui-router (built over a finite-state-machine with support for sub-views) over angular own router module.

Chapter 9 - Adding Real-time func. Using Socket.io

Next, learn how to communicate in real-time between the browser and the server using websocket. In order to do that you'll learn how to set socket.io up. Be careful about the socket.io session configuration example, the error management should really be improved.

Chapter 10 - Testing MEAN apps

Nice overview of what unit-testing and end-to-end (E2E) testing is about. You'll learn how to unit-test a MEAN application with Mocha and Karma using Jasmine as well as E2E testing with protactor.

Chapter 11 - Automating & Debugging MEAN Apps

The last chapter demonstrates how to configure grunt to automate code quality checking and testing. You will learn grunt, node-inspector (for nodejs debugging) and batarang (a browser extension for angularjs debugging).


MEAN Web Web Development is clearly a well written book that will be the perfect match for beginners in AngularJS and NodeJS!

[Fr] Les enjeux de l'information et de l'algorithmique dans notre société

Retranscription d'un échange avec Sébastien Onillon sur les enjeux actuels de l'information, l'algorithmique et le rôle de l'information dans notre société.


So it isn't possible to create a clean Singleton in JavaScript due to constructor restriction? Really?

As I am currently preparing a lecture on Design Patterns, I started to read the famous Design Patterns: Elements of Reusable Object-Oriented Software a.k.a the Gang of Four book as well as Les design patterns en Java and Mastering JavaScript Design Patterns.

Whether or not Design Patterns in oriented programming language are a language smell is another story (even if I could not personally agree more). I wanted to write about the following affirmations in Mastering JavaScript Design Patterns:

My first reaction  reading this was:
The second check inside the Wall constructor is hideous and we can definitely hide the constructor thanks to a closure, leveraging JavaScript functional nature. I thus gave this affirmation as an exercise for my students and here is a possible solution:

But we can go even further, why bother duplicating singleton logic when you can make a Singleton factory:

Note that the Singleton factory invocation must be alongside the internal implementation otherwise the JavaScript constructor could be instantiated multiple times.

Bonus: a lot of Singleton implementations available on Internet forgot to hide the constructor, even Addy Osmani books on JavaScript Design Patterns forgot this:

PS: The __proto__ trick for hiding the constructor is now widely supported (IE11+).

[Update] Supporting static methods and leveraging Object.create features instead of redefining __proto__.constructor:


Projet RCA - Génération scalable de vidéos personnalisées à forte valeur créative

Pour une première mise en contexte n'hésitez pas à lire le billet d'annonce du projet Le Père Noël RCA gâte les membres de la CEG. Escale a aussi écrit un beau billet résumant le travail de Mathieu et Killian sur la partie frontend "2015 démarre avec des voeux innovants pour rca".

Au côté de Mathieu Le Gac d'Escale et de Clément Perron de Doze Studio mon rôle dans ce projet a été de rendre possible, d'imaginer, de concevoir et d'implémenter une technologie scalable de génération de vidéo à forte valeur créative (e.g. motion design) personnalisées à la volée par des utilisateurs.

En toute franchise, nous allons décliner cette technologie dans d'autres projets donc je ne m'étendrai pas ici sur ses caractéristiques techniques. Ce que je peux par contre affirmer c'est que contrairement aux projets :

  • Facebook Loopback : Génération à la volée HTML/CSS3/JS avec ffmpeg/phantomjs (ou équivalent) pour la partie encodage.
  • Bref 30 ans : superposition via Flash de séquences vidéo pré-enregistrées.
  • HashTagMyAss : incrustation (non réaliste et donc de mauvaise qualité) d'images Instagram dans un template vidéo réalisé avec ImpossibleSoftware.

Notre technologie offre la possibilité à des artistes de permettre à des utilisateurs non technique de personaliser leurs créations afin de générer des vidéos de haute qualité graphique et dynamique dont voici un exemple :

Ce projet a été pour moi l'occasion de travailler sur d'autres technologies – génération de vidéos oblige – et sur d'autres environnements (Windows Server 2012...) dans des délais très courts (mais tenus !). Grâce à notre équipe très complémentaire et quelques pizzas j'ai pu développer en une soirée une première version du système de génération de vidéos personalisées à la volée !

Request-api - NodeJS request library as HTTP API

Yep. request-api.
« »
Made with on a hot august night from an airplane the 19th of March 2017.