-
Notifications
You must be signed in to change notification settings - Fork 76
Usage of Custom HTTP Client & Pipeline Policies
Sarangan Rajamanickam edited this page Sep 17, 2021
·
1 revision
The following sample code shows the usage of custom HTTP Client and also custom pipeline policies as Middleware
import {
createHttpHeaders,
HttpClient,
} from "@azure/core-rest-pipeline";
import { AdditionalPropertiesClient } from ".";
async function main() {
// Define a custom client to send the requests
// In this example we just log the request and
// send back a dummy response, but this could be
// plugged into any implementation
const customClient: HttpClient = {
sendRequest: async request => {
console.log(`Sending a ${request.method} request to ${request.url}`);
return {
headers: createHttpHeaders(),
bodyAsText: `{"foo": "bar"}`,
status: 200,
request
};
}
};
// Pass the custom HttpClient to the generated client
const client = new AdditionalPropertiesClient({
httpClient: customClient
});
// You can also use pipelines as middleware
client.pipeline.addPolicy({
name: "customPolicy",
sendRequest: async (request, next) => {
// You can manipulate the request before handing it off to the pipeline and eventually
// get sent.
request.headers.set("test-header", "hello world!");
// Handing it off to the pipeline to process all remaining policies and eventually
// reach the sendRequest on the HttpClient that we defined above (or the default if no custom HttpClient is provided)
const response = await next(request);
// You can also manipulate the response before handing it back to the pipeline and eventually reaching your client's method
const parsedBody = JSON.parse(response.bodyAsText ?? "{}");
parsedBody.testValue = "Added this is a pipeline policy!";
response.bodyAsText = JSON.stringify(parsedBody);
// And off the response to the pipeline
return response;
}
});
const result = await client.pets.createAPInProperties({ id: 1, name: "Foo" });
console.log(result);
// Output:
// Sending a PUT request to http://localhost:3000/additionalProperties/in/properties
// { foo: 'bar' }
}
main();