Category Archives: Web development

New React Context API

I like new react API for creating and using context. It feels right. One thing I immediately tried to do was creating a helper which simplifies consuming multiple contexts. Because they create context hell. When you component uses more than one context and because of a children as a function pattern (which is basically the same as render props pattern where component’s children function is specified as a component’s prop named render), code gets familiar indent to the left (callback hell).

For example with the use of this helper,

    { theme => (
            { language => (
                <App theme={theme} language={language} />

would become

<Consume contexts={[Theme, Language]}>
    { (theme, language) => (
        <App theme={theme} language={language} />

But after giving it a second thought, I realized in high-performance web applications this “multiple contexts consumer” case scenario can be a bad idea in most cases. Because If we have for example two contexts that are always used together, it’s better to just have one context anyway. But if a component uses more contexts which aren’t co-dependent, that means parts of component will be re-rendered unnecessary. So the component should be split into components which uses only one context or co-dependant contexts.

If you are interested in Consumer component, you can see it in following snippet with example usage. I’ve also added Provide component which mirrors Consume component for the sake of completeness. It’s no problem though if you specify Providers separately or not at all – in that case it will use context’s default value than).

Auto-reloading (safe-write) issues of application development servers

I have discovered new module bundler for developing applications in JavaScript. It’s called Parcel.js and my initial impressions are positive. That’s what I tweeted about it:

Parcel is a web application bundler, differentiated by its developer experience. It offers blazing fast performance utilizing multicore processing, and requires zero configuration. Basically a fast Webpack alternative only without tons of configuration. Read more about its features here. I discovered it while looking at some library’s package.json checking which dependencies it uses. I use this technique often whatever the language library is written in because that’s how I find new and exciting libraries which makes me more productive.

The first problem I encountered while using it, has actually nothing to do with Parcel.js itself, but the way most editors save files which makes Parcel.js’ and many other development servers’ reloading capabilities limited to only first file save. This feature is called safe-write which doesn’t save changes in original file, but in a temporary file. Temporary file is than renamed and replaces original. This causes development servers with reload capabilities to lose track of file. Luckily we can turn this off (how-to for popular code editors). But before you do this, please educate yourself about the advantages of using safe-write. To sum up, it guards you against data loss if editor crashes. In my case this almost never happens so I don’t see the point of having safe-write enabled.

Avtomatska rokometna lestvica (WordPress plugin)

Last weekend I developed for an acquintance a WordPress plugin which I’ve titled “Avtomatska rokometna lestvica” (translates to “Automatic handball league table” from Slovene). He’s a contributor to an official website of RK Trimo Trebnje, my local handball club and asked me if it’s possible to have a functionality which replaces the manual work of reading a website with statistics for a league table, selecting only a handful of columns and saving it to a blogpost. I had a lot of experiences with web scraping so I was immediately sure it can be done.

Without knowing where the scraped data will be displayed, I coded plugin’s option page using WordPress’s Settings API (and utilizing my library which simplifies creating option’s page). It’s just a textarea which accepts CSV-like data where each league table is represented in one line and one line contains a selection name and URL to its stats.

I have also coded a logic which actually scrapes the necessary data – table of team position, team name and team points and makes new table which is than saved into the database. For reading and constructing HTML tables I’ve used PHP’s DOMDocument. I’ve enjoyed working with this class.

Web-scraping is done periodically at midnight using wp-cron. They way wp-cron works is it launches when first user visits the site after the time it’s set to repeat.

Now comes the part where I learned how it’s going to be displayed. More than one league table needed to be shown (for selections like members, cadets, juniors,…), they were grouped in tabs. Inputs where they are edited were present on certain WordPress page using cusom fields. The problem for me was I had no idea where this fields are stored in the database. So the content from web-scraping process can be saved there.

I fixed this problem quite elegantly, I must say. I saved the content into wp_options table under a key {$package}_{$selection} and for displaying it I’ve coded a shortcode which queries wp_options for the key {$package}_{$selection} and returns HTML stored under that key – selection is specified as an argument to shortcode.

One-liner for serving static files in Go explained

Whenever I want to set up a server for serving static files in Go, which is not often, I always have to spend some time to figure out the following one-liner.

http.Handle("/images/", http.StripPrefix("/images/", http.FileServer(http.Dir("./images"))))

What confuses me probably the most here is all three strings being practically the same.

So in this post I will explain what this does for my future-self so he won’t have to google about it and will have it explained here in a way he’ll like it. 🙂

For this particular example (where one-liner above applies) let’s say we are storing images in ./images folder on a server and accessing them from outside of the server with <server's domain>/images/article2.jpeg

  • We shouldn’t set up a file server at root endpoint if our server accepts other endpoints.
  • http.FileServer(http.Dir("./images"))) exposes folder ./images as a handler.
  • http.StripPrefix is used because images are stored in ./images` folder and not in it’s subfolder images (we want ./images/article2.jpeg not ./images/images/article2.jpeg). It strips prefix from request’s URL.

A friendly reminder

Serving static files is more efficient using dedicated web server (Nginx, Apache,..). This approach also aids to better security of your application.

Input validation with Folktale

In this post I’ll show a way to do input validation in JavaScript using Folktale which is a library for functional programming. The beauty of this approach is having validation rules (is required, is email, is confirmed, etc) specified as a callbacks so they can be reused across different forms and also the absence of control flow structures associated when doing input validation traditional way (using if statements).

Before going straight to the code, I’d also like to mention that if input has multiple validation rules, they are evaluated sequentially and its validating process is interrupted after the first encountered unsatisfied rule and its error returned. As opposite to evaluating all rules for a field and displaying all unsatisfied.

Folktale provides constructs and utilities to make functional programming easier. For input validation, we can use Result or Validation. The main difference between them is that Result stops at first encountered error, while Validation evaluates all rules. You might want to use Result in cases like validating a required email address, because showing that input is required and that this field doesn’t look like email address at the same time is stupid. On the other side, Validation is useful if you want a field to satisfy multiple rules (has specified length, has one uppercase letter, has one symbol etc) and show them all at once.

I’ll be doing input validation using Result since I prefer showing one input error at a time.

Validation rules are specified as functions which takes form object and a key (field name). Why not just field value? Because there are rules that evaluates one field against another field, like password confirmation. If rule’s predicate is satisfied, it returns Result.Ok, otherwise Result.Error.

Examples of validation rules:

import Result from 'folktale/result'

const isRequired = (form, field) => !!form[field].trim()
    ? Result.Ok(form[field])
    : Result.Error("This field is required")

const isEmail = (form, field) => /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(form[field])
    ? Result.Ok(form[field])
    : Result.Error(`${form[field]} doesn't seem to be an email`)

const isConfirmed = (fieldToConfirm, what) => (form, confirmField) => form[fieldToConfirm] === form[confirmField]
    ? Result.Ok(form[confirmField])
    : Result.Error(`${what} don't match`)

They are used like this (in case of registration form):

const rules = {
    username:              [isRequired],
    email:                 [isRequired, isEmail],
    password:              [isRequired],
    password_confirmation: [isRequired, isConfirmed('password', 'Passwords')]

Now we need to write a function that iterates over rules’ entires and for each field constructs a predicate based on its rules. Field’s rules are chained like this (in case of password confirmation): isRequired.chain(isEmail) and its output is an instance of Result.Error or Result.Ok. The function I come up with is quite criptic for inexperienced programmers, but all it does is iterating over rules’ entries using Folktale’s mapEntries and for each field construct a similar chain using reduce.

import {assoc} from 'ramda'
import mapEntries from 'folktale/core/object/map-entries'

const validate = (form, rules) => mapEntries(
    ([field, fieldRules]) => [
            (p, r) => p.chain(_ => r(form, field)),
            fieldRules[0](form, field)
    (result, key, value) => assoc(key, value, result)

mapEntries takes three arguments – object to be iterated over, a function which takes an array of key, value and which returns array of key, value and reduce function. The last argument allow us to skip the field or add additional field to the object so mapEntries isn’t necessary a 1:1 transformation.

Now all we have to do is use it. Field validation has two outcomes, Ok (valid) and Error (invalid). We want to show nothing if input is valid, but for invalid field a message is shown wrapped in html tags. Folktale provides pattern matching for all its constructs that evaluates a specified function based on type (in our case based on Result’s Ok/Error type). It looks like this:

const form = {
    username: 'Jernej',
    email: 'jernej.sila@gmail'
    password: 'pass',
    password_confirmation: 'password'

const rules = {
    username:              [isRequired],
    email:                 [isRequired, isEmail],
    password:              [isRequired],
    password_confirmation: [isRequired, isConfirmed('password', 'Passwords')]

const errors = validate(form, rules)

const usernameError = errors.username.matchWith({
    Ok: ({value}) => undefined,
    Error: ({value}) => `<p class="text-danger">${value}</p>`

const passwordError = errors.password.matchWith({
    Ok: ({value}) => undefined,
    Error: ({value}) => `<p class="text-danger">${value}</p>`
console.log(usernameError) // Output: undefined
console.log(passwordError) // Output: <p class="text-danger">This field is required</p>