Skip to content

Instantly share code, notes, and snippets.

@blazarecki
Created November 25, 2015 09:04
Show Gist options
  • Save blazarecki/f1faecaa3193c4744001 to your computer and use it in GitHub Desktop.
Save blazarecki/f1faecaa3193c4744001 to your computer and use it in GitHub Desktop.
export class HydraNormalizer {
rewriteRules: any;
normalizeRelations(model: string, element: any): void {
if (!this.rewriteRules[model]) {
return;
}
this.rewriteRules[model].forEach((column: string) => {
if (!element[column]) {
return;
}
if ('string' === typeof element[column]) {
element[column] = '/' + model + '/' + element[column];
return;
}
element[column].forEach((value: string, key: string) => {
element[column][key] = '/' + column + '/' + value;
});
});
}
denormalizeRelations(model: string, data: Array<any>): void {
if (!this.rewriteRules[model]) {
return;
}
this.rewriteRules[model].forEach((column: string) => {
if (!data[column]) {
return;
}
if ('string' === typeof data[column]) {
data[column] = this.uriToId(data[column]);
return;
}
data[column].forEach((value: string, key: string) => {
data[column][key] = this.uriToId(value);
});
});
}
uriToId(uri: string): string {
return uri.split('/').pop();
}
normalizeReference(data: any): void {
if (data['@id']) {
data.id = this.uriToId(data['@id']);
}
}
denormalizeCollection(model: string, data: Array<any>): void {
var collectionResponse = data['hydra:member'];
collectionResponse.metadata = {};
// Put metadata in a property of the collection
angular.forEach(data, (value: any, key: string) => {
if ('hydra:member' !== key) {
collectionResponse.metadata[key] = value;
}
});
// Populate href property for all elements of the collection
collectionResponse.forEach((value: any) => {
this.normalizeReference(value);
this.denormalizeRelations(model, value);
});
return collectionResponse;
}
normalizeParams(params: any): void {
if (params._page > 1) {
params.page = params._page;
params.itemsPerPage = params._perPage;
}
params.order = params._sortDir;
delete params._sortDir;
delete params._sortField; // Not implemented
delete params._page;
delete params._perPage;
}
handlePagination(data: any, response: any) {
response.totalCount = data['hydra:totalItems'];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment