DailyJS

DailyJS

The JavaScript blog.


Tagrest
Featured

rest array ES7 JSON

Array Future, JSONFormData

Posted on .

Array Future

Kiko Beats sent in array-future (GitHub: Kikobeats/array-future, License: MIT, npm: array-future), a module that collects together several ES7 proposals for instance methods on Array:

require('array-future');

[1, 2, 3].average();
// 2

[1, 2, 3].first();
// 1

[1, 2, 3].shuffle();
// [ 2, 3, 1 ]

[1, 2, 3].includes(3);
// true

The includes method is implemented as described by this documentation. Each method is tested with Mocha, and there's documentation in the readme.

JSONFormData

I've been doing a lot of work with the FormData API, and I found a JSONFormData polyfill by Roman Liutikov in the DailyJS submission queue. It implements the W3C HTML JSON form submission API:

Instead of capturing form data as essentially an array of key-value pairs which is the bread and butter of existing form encodings, it relies on a simple name attribute syntax that makes it possible to capture rich data structures as JSON directly.

This implementation lets you submit data to servers as JSON by setting a form's enctype to application/json. It also supports REST API HTTP verbs like PUT and DELETE.

Submitting data with JavaScript is similar to FormData -- just use new JSONFormData(form).formData to get an object based on the form.

If you're writing RESTful services with JSON and want to make a quick web interface, then JSONFormData should help speed things up.

Featured

frameworks libraries v8 node testing rest modules

Node Roundup: io.js 2.0, Bootstruct, JSVerify

Posted on .

io.js 2.0

io.js 2.0 was released this week, and it brings some big changes from V8 and fixes to core modules.

The V8 changes include the class keyword in strict mode without flags, shorthand method and property syntax, rest parameters (with --harmony-rest-parameters), computed property names (with --harmony-computed-property-names), and unicode escapes (with --harmony_unicode and --harmony_unicode_regexps). "Rest parameters" means function(a, b, ...args) {}, and args is actually a real array. MDN has more details.

Unfortunately this release has breaking changes, so you'll want to test it thoroughly. The breaking changes are partly related to V8 because the C++ API has changed. I think this might impact some native modules, but I haven't checked the details. The behaviour of os.tmpdir has changed as well, it no longer returns a path with a trailing slash.

Bootstruct

Bootstruct (GitHub: taitulism/Bootstruct, License: ISC, npm: bootstruct) by Taitu Lizenbaum is a module for creating RESTful frameworks based on files and folders. If you create a file in a folder called post, it will map the methods inside to POST requests.

To write methods, you have to create functions that take a single argument: io. This value has res and req objects, so it looks similar to other Node HTTP frameworks.

The readme has a lot of details on how Bootstruct generates the internal representation of the folders, filenames, and HTTP verbs, and it seems like it would be fairly easy to get used to the pattern. If you consider app.httpVerb to be unnecessary boilerplate, or perhaps have folders of data that you could map to a Bootstruct application with suitable wrapping code, then you might find it useful.

JSVerify

JSVerify

I'll admit that I was a little bit confused by JSVerify (GitHub: jsverify/jsverify, License: MIT, npm: jsverify). It's a "property-based" testing framework, which to my JavaScript-oriented mind interpreted as something that tests properties on objects. Property-based testing actually refers to a style of testing where properties are specifications of a behaviour that should hold certain values. I found a nice and short definition of it by Jessica Kerr:

Property-based tests make statements about the output of your code based on the input, and these statements are verified for many different possible inputs.

JSVerify will generate inputs for a function. This example is taken from the documentation:

// forall (f: json -> bool, b: bool), f (f (f b)) ≡ f(b).
var boolFnAppliedThrice =  
  jsc.forall('bool -> bool', 'bool', function(f, b) {
    return f(f(f(b))) === f(b);
  });

jsc.assert(boolFnAppliedThrice);  
// OK, passed 100 tests

It also includes examples for testing promises. The way it works with JavaScript's syntax and the compatibility with asynchronous code makes the tests look very succinct, but it will take a bit of practice to get the hang of it.

Featured

testing rest ES6 sponsored-content coverage

Wallaby.js Updates, Jasmine ES6 Tests, Chakram

Posted on .

Wallaby.js Updates

I recently wrote about Wallaby.js, and the authors have just released a major update that adds support for ES7, RequireJS, Browserify, and webpack. I'm a fan of Browserify so I was excited to see this -- you can get it at hwallabyjs/wallabify. The webpack postprocessor is available here: jeffling/wallaby-webpack.

Other updates include the news that a full-time developer has joined the project, and a tutorial that introduces the idea of live editing with testing.

Wallaby.js is an intelligent test runner for JavaScript projects, and has some cool features like editor-integrated code coverage reporting, and parallel test execution. It supports React JSX, popular test frameworks like Jasmine and Mocha, and even works with TypeScript and CoffeeScript.

Wallaby.js is a commercial product, but it's currently free during the preview. The site has more details on how to sign up for the preview: http://wallabyjs.com/.

Jasmine ES6 Tests

We're used to using transpilers for client-side code and sometimes Node projects, but what about tests? If ES6 really makes code more readable and maintainable, then I definitely want to use these language features to make my tests better! Torgeir Helgevold sent in a tutorial about writing Jasmine tests with ES6. The basic idea is to add preprocessors to a karma.config.js file that includes settings for Babel.

Karma is the test runner used by AngularJS, and it's test framework agnostic, so you could adapt this technique to work with Mocha as well.

Because Karma can easily be used to manipulate your test files before they execute, then it makes sense for people who want to use transpilers. I haven't done this before (my tests are usually very vanilla Mocha/assert tests), but it seems like a reasonable solution.

Chakram API Testing

Chakram (GitHub: dareid/chakram, License: MIT, npm: chakram) by Dan Reid is an API testing framework, based on promises. It includes Mocha and Chai, but instead of calling done callbacks you can use the wait method:

var chakram = require('chakram');  
var expect = chakram.expect;

describe('Minimal example', function() {  
  it('should provide a simple async testing framework', function() {
    var request = chakram.get('http://httpbin.org/get');
    expect(request).to.have.status(200);
    expect(request).not.to.have.header('non-existing-header');
    return chakram.wait();
  });
});

There's a list of extended chai expectations, and methods for HTTP and promises in the Chakram module documentation. This includes methods for HTTP verbs, so you can do chakram.patch and chakram.put.

Featured

data localStorage rest cache

JSData

Posted on .

Asaf Katz sent in JSData (GitHub: js-data/js-data, License: MIT, npm: js-data, Bower: js-data) by Jason Dobry, a model layer for caching data. It supports adapters for sending data to persistence layers, so you can install DSHttpAdapter (npm/Bower: js-data-http) to send data to a REST server or DSLocalStorageAdapter (npm/Bower: js-data-localstorage) for browser-based storage. There are even adapters for RethinkDB, Firebase, and Redis.

One nice thing about JSData is it uses Object.observe to watch for changes to data, so it doesn't need any special getters or setters. It also supports promises, so you can use then after finding or inserting data.

It also has more advanced ORM-style features like relations, computed properties, lifecycle methods, and data validation. The schema and validation API isn't based on JSON-Schema, but it has the kinds of features you've probably seen in other ORMs and ODMs like Mongoose:

var store = new JSData.DS();

var User = store.defineResource({  
  name: 'user',
  schema: {
    id: {
      type: 'string'
    },
    name: {
      type: 'string',
      maxLength: 255
    },
    email: {
      type: 'string',
      nullable: false
    }
  }
});

User.create({  
  name: 'John'
}).catch(function(err) {
  // Email errors will be in err.email.errors
});

This is an example I adapted from the Schemata and Validation documentation.

JSData was originally written for AngularJS, but is now framework-agnostic. However, there is an Angular integration guide which shows how it can be used with Angular applications.

Because JSData can be used with Node and browsers, you could use it to define reusable models for single-page apps that sync when the server is available. It'll also work well if you're used to Rails-inspired frameworks like Ember, and you're used to working with fat models that include data validation and lifecycle methods.

Featured

libraries ui ajax dom http rest

Databound, Typist

Posted on .

Databound

Databound

If you use Ruby on Rails, then you might like this Rails REST library wrapped: Databound (GitHub: Nedomas/databound, License: MIT, npm: databound, Bower: databound) by Domas Bitvinskas. The API looks a bit like the Rails syntax for database models:

User = new Databound('/users')

User.where({ name: 'John' }).then(function(users) {  
  alert('Users called John');
});

User.find(15).then(function(user) {  
  print('User no. 15: ' + user.name);
});

User.create({ name: 'Peter' }).then(function(user) {  
  print('I am ' + user.name + ' from database');
});

Install it with npm, Bower, or as part of a Rails asset pipeline. The author also notes that you can use it with Angular as an alternative to ngResource.

Typist

Typist (GitHub: positionly/Typist, License: MIT, Bower: Typist) by Oskar Krawczyk is a small library for animating text as if it's being typed. It can work with responsive layouts, and the author claims it has improved click-through-rates on a commercial homepage.

It doesn't have any dependencies, and is invoked by a constructor that accepts options for the animation intervals. The required markup should specify the text to be typed in the data-typist and data-typist-suffix attributes.