Preface
In some cases users wants to alter existing HTTP API responses, by removing excess fields, changing content or modify result in any other way.
In this chapter we will go trough process step by step and describe how to remove explorer
property from the /node/configuration
route accessible on GET
method.
1{2 "data": {3 "symbol": "TѦ",4 "explorer": "http://texplorer.ark.io",5 "version": 23,6 }7}
Desired response:
1{2 "data": {3 "symbol": "TѦ",4 "version": 23,5 }6}
Process
Get route
First we need get existing route object that we want to modify. Be aware there can be two Server
instances accessible via Identifiers.HTTP
or Identifiers.HTTPS
symbols. Each Server
instance expose getRoute
method which is used for obtaining ServerRoute
.
1const route = this.app.get<Server>(Identifiers.HTTP).getRoute("GET", "/api/node/configuration");
Keep original handler
Save the reference to existing handler. Use bind()
function to bind original object which method belongs to, otherwise you will lose this
reference if one is used inside the handler.
1const originalHandler = route.settings.handler.bind(route.settings.bind);
Create new handler
Replace route handler with new wrapper function. New function will call original handler and set desired property to undefined
. JSON standard defined that undefined properties are not included in stringified response, which will result as removed field in response body. Finally return modified response.
1route.settings.handler = async (request: Hapi.Request, h: Hapi.ResponseToolkit) => {2 const response = await originalHandler(arguments);3 response.data.explorer = undefined;4 return response;5 };
API
Methods
string
, path: string
) : ServerRoute
| undefined
Server.getRoute(method: Parameters:
method - HTTP method eg. “GET”, “POST” path - route path eg. “/api/node/configuration”
Response:
Returns ServerRoute
object or undefined
.
Complete code sample
1// Import 2import Hapi from "@hapi/hapi"; 3 4// Modify route 5const route = this.app.get<Server>(Identifiers.HTTP).getRoute("GET", "/api/node/configuration"); 6if (route) { 7 const originalHandler = route.settings.handler.bind(route.settings.bind); 8 route.settings.handler = async (request: Hapi.Request, h: Hapi.ResponseToolkit) => { 9 const response = await originalHandler(arguments);10 response.data.explorer = undefined;11 return response;12 };13}