Tag Archives: Javascript

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.

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(
    rules,
    ([field, fieldRules]) => [
        field,
        fieldRules.slice(1).reduce(
            (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>
YouTube iframe API example

YouTube iframe API

YouTube iframe API lets developers control embedded YouTube video on a website. They can for example stop or pause the player, react on player state changes or add their own event listener. I familiarise with it with a YouTube video that’s in fact compilation of couple of songs and I beside it was an ordered list of those songs and I wanted the currently played song to be styled differently.

The idea came to mind when I saw YouTube videos that have in descriptions time markers for each song indicating it start and when you click it it rewinds player to that time.

Here is this example.

User clicks on a song from this list and player moves to the position of this song and starts to play. And song currently being played is styled with bigger font so the user can spot it easily. User can also click on player timeline and song played will be highlighted. I also didn’t forget the scenario when one song ends and another begins so the appropriate song is marked as currently played.

Things to note:

  • Examples from official docs aren’t working because iframe API has changed the way how code runs when iframe API is ready. You need to pass a player initialisation code to YT.ready function, not define onYouTubeIframeAPIReady (I only figured this out by inspecting https://www.youtube.com/iframe_api, which fortunately doesn’t have many lines).
  • YouTube video ID is e.g. bHQqvYy5KYo and not v=bHQqvYy5KYom which is what follows after question mark in URL address.
  • You can create YouTube video player from scratch from JavaScript or use existing iframe as I did. Consult docs and see the 1st example on how to do it.
  • You can get a thumbnail for a YouTube video just by grabbing its ID and depending on desired quality insert it in a URL pattern. All URL patterns are listed in the linked stackoverflow answer (i didn’t use this feature in the demo, but in an app I decided to built later around this iframe api).

Feathers.js makes developing RESTful and realtime apps easier

I discovered Feathers.js via Tutorialzine article that popped in my Facebook timeline, which offered 15 interesting JavaScript and CSS libraries for June 2017. Since then I’ve been toying with it for almost a week now and I’m really liking it.

It has a lot of documentation to start with but I wouldn’t recommend it to someone new to web development since it’s not straightforward, there are a lot of concept to be familiarize with (web development-wise) and it takes some time to learn how it’s supposed to work. In other words, it has some learning curve. But after I connected the dots I started appreciate it because it enables me to quickly bootstrap common tasks while building a web applications (like authentication).

Feathers has a service and hook-based approach when developing web applications. A service takes care of a REST resource and out-of-the-box you can perform all standard operations on it (find all resources, get single resource, or update and delete it). Hooks are where business logic around resource is designed to reside. Hooks are functions that get executed before and after this “out-of-the-box operations” are executed. You can define hooks resource-wise or app-wise (i.e. when user is created or when a resource is created). Hooks should be small and do one thing only. When first learning about them, they reminded me of functions in functional programming which are small and single-purpose too.

So for example if you are writing hook for validating form request, you supply it a validation rules and if rules are not met, you throw an error otherwise request is passed to the next hook in chain. You don’t use the same hook to execute logic in case of validation rules being met because you can use this “form request validation” hook for multiple resources, right? Instead you define another hook as a hook next to this validation hook. When you throw an error in some hook, the rest of them that follows don’t get executed (you can take this as a chain of responsibility design pattern ((It’s similar to decorator pattern with that difference that any link in a chain can interrupt the execution.)))

Aside from create hook there are also update, patch, delete, put, all (accounts for all hooks), find, get.

Another cool thing about Feathers is that it provides browser-side client which ease interacting with feathers-based API. You don’t event need to deal with underlying library that makes AJAX requests – just select which one you want client to use (fetch, axios to name a few).

1 tip for writing more understandable code in JavaScript

I find JavaScript code more understandable if it’s using functions heavily because when written properly ((They are small and do one thing only.)), they typically convey what they do. That does not mean you should start practicing functional programming at once. You can just start by using utility libraries like lodash or underscore more when manipulating data. Even if native implementations exist for certain methods, like filter, map, reduce. That’s because reading first method name and then its arguments make you quicker to understand what’s going on with code at hand.