How to pass authorization header to NSwag generated fetch client?

Viewed 106

There is an auto-generated API proxy fetch client through NSwag.MSBuild package and it has constructor like this. I need to pass the authorization header throgh init parameter.


export class CustomerClient implements ICustomerClient {
    private http: { fetch(url: RequestInfo, init?: RequestInit): Promise<Response> };
    private baseUrl: string;
    protected jsonParseReviver: ((key: string, value: any) => any) | undefined = undefined;

    constructor(baseUrl?: string, http?: { fetch(url: RequestInfo, init?: RequestInit): Promise<Response> }) {
        this.http = http ? http : <any>window;
        this.baseUrl = baseUrl !== undefined && baseUrl !== null ? baseUrl : "";
    }
...
...
...
}

What is a possible way to pass it?

1 Answers

Maybe this will help you

const apiClient = new CustomerClient(`http://localhost:5000`, {
    async fetch(url: RequestInfo, init: RequestInit) {
        const accessToken = await acquireAccessToken();
        if (accessToken) init.headers['Authorization'] = `Bearer ${accessToken}`;

        return fetch(url, init);
    },
});
Related