GUIPSS

👉 Articles tagged : es6

Simple and automatic HTTPS proxy with Greenlock, LetsEncrypt and node-http-proxy

Posted on: 2018-08-21
Categories: javascript - es6

Thanks to greenlock and node-http-proxy, creating a https proxy whith Let's Encrypt has never been easier. Basically, we just have to mix the two :

var Greenlock = require('greenlock');
var httpProxy = require('http-proxy');
var proxy = httpProxy.createProxyServer({});
var redir = require('redirect-https')();

// let's create ou greenlock server first

var greenlock = Greenlock.create({
  // check greenlock's doc for the entire code sample
});


require('http').createServer(greenlock.middleware(redir)).listen(80);

require('https').createServer(greenlock.tlsOptions, function (req, res) {
  // proxy request instead of serving content :
  return proxy.web(req, res, {
    target: 'https://another-server.com',
  });
}).listen(443);

😉


Vue.js : Pass all props to child components

Posted on: 2018-04-21

Passing all props from a component to a child component in Vue is generally considered not a good thing to do... but you might want to do it anyway because you know what you are doing 😉 I'll try to write a post on how to avoid such a pattern later, but here it is :

Let's say you are using a framework that provide you with a component named VMenu, and you want to wrap that component in your own component (MyMenu) and pass all the props :

export default {
  name : `MyMenu`,
  functional : true,
  render (createElement, context) {
    return createElement(`div`, {}, [
      createElement(`v-menu`, {
        props : {
          ...context.props,
          aPropYouWantToOverride : `value`,
        },
      }, [
        context.slots().default, //  also pass default slot to child
        createElement(`template`, { slot : `activator` }, context.slots().activator), // passing another named slot (named "activator")
      ]),
    ]);
  },
};

The important thing here is to create a functionnal component, because that will automatically take all the props given to our MyMenu component and put them in the context object.


Wait for a function if it returns a promise (but you're not sure it does)

Posted on: 2018-02-17
Categories: javascript - es6

If you are working on an npm module, a library or a plugin system, there is times where might want to call a function without being sur it returns a promise or not. Here is an example that may help you achieve what you want :

const returnsAPromise = () => Promise.resolve();
const returnsARejectedPromise = () => Promise.reject(`Error !`);
const returnsOne = () => 1;

const asyncFunction = async (unknwnFunction) => {

  await returnsAPromise();
  // obvioulsy that passes

  try { await returnsARejectedPromise() }
  catch (e) {
    // obviously that fails...
    console.log(`Of course that failed :`, e);
  }

  // now...
  const one = await returnsOne();
  // thats fine and one === 1
  console.log(`I waited a regular function, one = ${one}`);

  // So it means that if we dont know if a function returns a promise
  // or just a value
  // we can just
  const result = await unknwnFunction();
  // it is usefull when you are, for example,
  // programmig an npm module and the function you call is
  // provided by the user
  console.log(`unknownFunction returned (wrapped in a promise or not): ${result}`);

};

const regularFunction = (unknwnFunction) => {

  // if we are not in a async function, we can also do :
  return Promise.resolve(unknwnFunction())
  .then(result => {
    console.log(`whatever unknownFunction returned : `, result);
  })
  .then(() => {
    // and yes, it would work even if the function fails :
    return Promise.resolve(returnsARejectedPromise());
  })
  .catch(err => {
    // this code is executed
    console.error(`It failed :`, err);
  });

};

asyncFunction(() => `Hi there !`)
.then(() => regularFunction(() => `Hello ladies !`))


😎 Cool code : async function always return a promise

Posted on: 2017-05-13
Categories: javascript - es6

There is really just two things to know to understand javascript async/await :

  • an async function return a promise
  • await always wait for a promise to be resolved and gives you the value it resolved with (so it raises an error if the promise was rejected)
'use strict';

const myAsyncFunc = async function () {
  await Promise.resolve();
  console.log(`In myAsyncFunc`);
}

const failFunc = async function () {
  await Promise.reject();
  console.log(`In failFunc`);//wont be executed
}

myAsyncFunc()
.then(() => {
  console.log(`After myAsyncFunc`);
})
.then(failFunc)
.catch(err => {
  console.log(`Catch error in failFunc`);
})
}

Result :

In myAsyncFunc
After myAsyncFunc
Catch error in failFunc

Of course we can also resolve promises with try/catch ! 😉


Cool code : concurrent async calls

Posted on: 2017-04-26
Categories: javascript - es6
var myAsyncFunc = async function () {
  const [ a, b ] = await Promise.all([ promiseFunc1(), promiseFunc2() ]);
  // the two calls are made at the same time, and we get back two variable
  // that can be used right away :
  console.log(a);
  console.log(b);
}