Roine

Typescript - Create type definition from object

February 06, 2020

You can generate a type from an object

// base file file.ts
const myObj = {a: 1, b: 2}

in the shell

tsc --declaration file.ts

it’ll generate two files, the compile js file and the type declaration file.

/// type declaration file file.d.ts
declare const myObj: {
    a: number;
    b: number;
};

The JS file can be ignored

Find all the tickets worked on between two commits

October 04, 2019

Find all the ticket starting by DPO between two commit, it relies on the fact that commits are squashed and the merge message contains the branch name.

git log --oneline 653d7e09d49..master --abbrev-commit | grep -E "DPO-\d+" -o

How to prettify a JSON object using the OSX shell

August 29, 2019

I often need to prettify a JSON and always end up googling json format online, pasting my JSON and copying the result. With the following alias I can just copy my JSON, type jsonformat in the shell and magic the formatted JSON is in my clipboard.

alias jsonformat="pbpaste | python -m json.tool | pbcopy"

Colours for Makefile

May 15, 2019

I’ve added colours to Makefiles few times in the past. Each and every single time I have spent way too much time figuring out the code for the colours. So here it is, my most used colours in one place:

COLOUR_GREEN=\033[0;32m
COLOUR_RED=\033[0;31m
COLOUR_BLUE=\033[0;34m
COLOUR_END=\033[0m

Usage:

@echo "$(COLOUR_GREEN)Test Passed$(COLOUR_END)"

More info on stackoverflow.

Bypass cors rules with a proxy server

May 15, 2019

Cors can be a pain as a frontend developer. Maybe you’re on a localhost and want to access the prod API. The problem is that the prod server enforce same origin request. There are few ways around it, my favourite so far is using a proxy server. Let’s see how CORS work and then how the proxy server solves it.

Imagine we are building an application on localhost and need to access the API in production test.com. We work on some data updating and need to make a POST request, wee write our query and try it. The browser detects that the requested resource is on an other domain than the requester. So before to run our POST request, it runs a preflight request (OPTION) to ask whether the server accepts requests from other origin. If the server says no the POST is not executed. At the moment only browsers enforce CORS rules. What if we could have a server that accepts request from any domain, take a URL and make an http request for us.

TL;DR

Enter cors-anywhere. With it you could query your test.com API like so https://cors-anywhere.herokuapp.com/https://test.com/api/login. No more preflight denying you access. Pretty awesome.

Extra

You might not want to add this everywhere.

if(isProd) {
    const domain =  "/api"
}
else {
    const domain =  "https://cors-anywhere.herokuapp.com/https://test.com/api"
}
fetch(domain + "/login")

Elm condition within attribute list

May 09, 2019

Today I was reviewing some ELM code and noticed a nice simple trick that is going to change my life! It has to do with conditional Html.Attributes. Let’s start by how I was doing my conditional Attributes:

[class "hello"] ++ (if bool then [onClick msg] else [])

Pretty ugly, right? Now imagine that I have more than one conditional Attribute.

Enter the empty Attribute.

empty = 
    Html.Attributes.class ""

This blew my mind, how did I never thought of that? It’s so simple and elegant. The code above would then write:

[class "hello", if bool then onClick msg else empty]

Docker Mirror your host folder with the guest

May 08, 2019

To mount a volume that mirrors your files in your host

docker run -p 8080:3000 -v $(pwd):/var/www -w "/var/www" node npm start
  • 8080:3000 your app runs in port 3000 and you want it to be served in 8080 in the host, this will forward the port.
  • -v $(pwd):/var/www, mounts the current directory /var/www
  • -w "/var/www" sets the working directory inside the container to /var/www, so when when we execute our command it’ll execute their
  • node name of the image
  • npm start our command to be executed in the working directory

So it starts the node container, exposes 8080 and forward 3000 to it. Mount a volume to mirror our local files, sets the working directory where the command will be executed. Finally, execute the command.

Get the ip of a docker image

May 08, 2019

If you need the container’s IP

docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' container_id

Replace container_id by yours.

Favourite help for Makefile

May 05, 2019

I always end up looking for the same Makefile help. I’ll pin it here for convenience.

help: ## This help dialog.
	@IFS=$$'\n' ; \
    help_lines=(`fgrep -h "##" $(MAKEFILE_LIST) | fgrep -v fgrep | sed -e 's/\\$$//' | sed -e 's/##/:/'`); \
    printf "%-30s %s\n" "target" "help" ; \
    printf "%-30s %s\n" "------" "----" ; \
    for help_line in $${help_lines[@]}; do \
        IFS=$$':' ; \
        help_split=($$help_line) ; \
        help_command=`echo $${help_split[0]} | sed -e 's/^ *//' -e 's/ *$$//'` ; \
        help_info=`echo $${help_split[2]} | sed -e 's/^ *//' -e 's/ *$$//'` ; \
        printf '\033[36m'; \
        printf "%-30s %s" $$help_command ; \
        printf '\033[0m'; \
        printf "%s\n" $$help_info; \
done

Check all user values attached to window

March 17, 2019

Analyzing production is hard since it’s most the time compressed and unreadable. One trick you can use is to check all the values attached to the window by the user. This snippet does exctly that, by comparing window to an iframe window:

(function () {
    var results, currentWindow,
    // create an iframe and append to body to load a clean window object
    iframe = document.createElement('iframe');
    iframe.style.display = 'none';
    document.body.appendChild(iframe);
    // get the current list of properties on window
    currentWindow = Object.getOwnPropertyNames(window);
    // filter the list against the properties that exist in the clean window
    results = currentWindow.filter(function(prop) {
        return !iframe.contentWindow.hasOwnProperty(prop);
    });
    // log an array of properties that are different
    console.log(results);
    document.body.removeChild(iframe);
}());

Source: https://stackoverflow.com/questions/17246309/get-all-user-defined-window-properties

Pretty print JSON in a file

February 14, 2019

If you try to dump an object in a JSON and for some reason want it to be formatted use this snippet

fs.writeFile('manifest.json', JSON.stringify(res, null, 4), 'utf8', (err) => {
  //...
})

This will add jump line and 4 space indentation after each entry

IntersectionObserver instead of scroll

January 30, 2019

If you want to do something when the viewport reaches a certain element in the view, you would use a scroll event and check that the position of that element is equal to the viewport top position.

You can instead use the IntersectionObserver. You choose a root and target and when they cross path it calls the callback , when root is null then it uses the browser viewport.

const options = {
  root: null, // use browser viewport
  rootMargin: '0px',
  treshold: 0.0
}
const observer = new IntersectionObserver(callback, options)
const target = document.querySelectorAll('#item')
observer.observe(target)

Demo in codepen.

Keep same URL in now.sh

January 24, 2019

In the world of static file hosting there are plenty of solutions. I picked now.sh. It’s free, easy to use and works well. I have had one problem with now.sh so far, it creates a new URL everytime you push. It’s a feature that I dont need in some cases, here’s how to solve. Put this in package.json:

{
  "scripts": {
    "deploy": "now && now alias && now remove YOUR_APP_NAME --safe -y"
  }
}

Replace YOURAPPNAME by the name of your app. Then go to your now.json and add/change:

{
  "name": "YOUR_APP_NAME",
  "alias": "YOUR_UNIQUE_SUBDOMAIN.now.sh"
}

Replace YOURUNIQUESUBDOMAIN by your unique subdomain. Then, run yarn deploy.

touch to update a file timestamp

January 23, 2019

Touch is mainly known for creating files. Touch main purpose is actually to update the file’s timestamp. From the man:

The touch utility sets the modification and access times of files. If any file does not exist, it is created with default permissions.

Pretty format ELM model in browser

January 17, 2019

An example of pretty format in browser

Using Debug.toString is really helpful to help debug the model but the format of the output is hard to read. Looking for solution I stumbled upon this gem (not the ruby gem). I changed it to work in elm 0.19 and fix a minor issue when using custom type for the Model. Here’s the final result on Gist.

Empty Tag in React

December 22, 2018

When you need to return more than one element you have few solutions.

Wrap with an element

<div>
  <span>1</span>
  <span>2</span>
</div>

Return a list (requires a key)

function List() {
    return [<span key='1'>1</span>, <span key='2'>2</span>]
}

Use Fragment (16.2.0+)

<Fragment>
  <span>1</span>
  <span>2</span>
</Fragment>

Use empty tag (some kind of alias for Fragment)

<>
  <span>1</span>
  <span>2</span>
</>

Reuse last argument from previous command

December 20, 2018

If you need to reuse the reuse the last argument from the previous command this is for you:

touch config.js
vi !$

Last command is equivalent to

vi config.js

Bonus: echo $? will display the exit code of therevious command !! will re-execute the previous command, sudo !!

Calendar in shell

December 20, 2018

I love calendars and shell has a way to display the calendar for the current month

$ cal
shell cal output

Building a calendar UI in ELM - Part 2

September 04, 2018

In the previous part of this tutorial we’ve seen how to represent the current month view into a list of dates. Now let’s see how we…

Building a calendar UI in ELM - Part 1

August 26, 2018

ELM was redesign recently and Date and Time have been removed from the core to the Time library. With that in mind let’s build a…

How to use hash parsing in ELM 0.19

August 22, 2018

Before in ELM 0.18 if you used evancz/url-parser you would use parseHash to parse the fragment. But now in 0.19 elm/url doesn’t have…

Common errors in Javascript and how it's solved in ELM

August 15, 2018

One of my favorite things about ELM is the compiler, it will catch errors before they could make their way to production. Let’s have a look…

Why I ditched JS for ELM

August 13, 2018

I’ve been working with ELM for 2 years now. When I started I had very little knowledge about functional programming. I remember being…