Skip to content

Instantly share code, notes, and snippets.

@patrickmichalina
Created March 25, 2017 20:16
Show Gist options
  • Save patrickmichalina/85120ec41e521502c9e7919db21faa31 to your computer and use it in GitHub Desktop.
Save patrickmichalina/85120ec41e521502c9e7919db21faa31 to your computer and use it in GitHub Desktop.
Paging example with hapi and typescript
import { applyToDefaults } from 'hoek';
import { Request } from 'hapi';
var URI = require('URIjs');
export class Collection {
public count: number;
constructor(public items: any[] = [], public total: number) {
this.count = this.items.length;
this.total = total || this.items.length;
}
toHal(rep: any, done: () => void) {
let request = rep.request as Request;
var pageSize = Number(request.query.pageSize) || 10;
var pageNumber = Number(request.query.pageNumber) || 1;
var totalPages = Math.ceil(this.total / pageSize);
var uri = new URI(rep.self);
var current = pageNumber;
var prev = pageNumber - 1;
var next = pageNumber + 1;
var query = uri.search(true);
if (pageNumber > 1) {
rep.link('prev', uri.search(applyToDefaults(query, { pageNumber: prev, pageSize })).toString());
}
rep.link('current', uri.search(applyToDefaults(query, { pageNumber: current, pageSize })).toString());
if (pageNumber < totalPages) {
rep.link('next', uri.search(applyToDefaults(query, { pageNumber: next, pageSize })).toString());
}
rep.link('last', uri.search(applyToDefaults(query, { pageNumber: totalPages, pageSize })).toString());
done();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment