I suggest pulling from the work in https://github.com/rethinkdb/horizon/pull/865 since it's a much better version of the code