Interceptors in the Obsidian API

Hi, I created my own plugin. For HTTP requests I used Axios and it works fine for me. However, after reviewing the pull request - I was offered to remove Axios and replace it with requestUrl from the Obsidian API. How to do with get, put, etc. I understand, but how do I rewrite interceptors on the Obsidian API?
I would be grateful for any answer.

There are no interceptors in the Obsidian API, and you don’t need those for your plugin.

A quick helper function does the job.

function requestWrapper(url: string, method: 'GET' | 'POST' | 'PATCH') {
	const response = await requestUrl({
		url: url,
		method: method,
		headers: {
			'Authorization': //api-key here
		}
	});
	if(response.status === 401) {
		//show notice
	}
	else if(response.status === 402) {
		//do stuff
	}
	return response.json();
}

Thanks for your code. Unfortunately, the requestUrl function doesn’t work at all. When I use it, I don’t see a single request in the network. What could be the reason?

Requests made with requestUrl won’t show up in the network inspector, as they go through the electron main process.

The request should still be successful, you can check by logging the response object.

In this code I get no response console.log(response.json()); I don’t understand why

    public async requestWrapper<T>(
        url: string,
        method: 'GET' | 'POST' | 'PATCH' | 'DELETE',
    ): Promise<T> {
        const response = await requestUrl({
            url: `${environment.serverURL}${environment.apiUrl}/${url}`,
            method: method,
            headers: {
                Authorization: usePluginState.getState().settings?.apiKey,
            },
        });

        console.log(response.json());

        if (response.status === 401) {
            console.log('401');
        } else if (response.status === 402) {
            console.log('402');
        }

        return response.json();
    }

hm, maybe the server does not return json or there is an error.
log the response object itself.

I don’t see anything in the network. I cannot understand what the reason is. Everything works on axios

How can I find out what the problem is?

Instead of console.log(response.json()); do console.log(response);
What does it show?

I have already tried and done. Unfortunately, I don’t get anything

Hi, do you have any suggestions?

How do you trigger the call to this requestWrapper()?

Or put another way, can you add some debug statements in front and/or after the const response = ... , to ensure the wrapper is actually called?

After ensuring it does get called, I would venture out verifying that all the parameters to requestUrl is actually set in that context.

I already tried to check like this

    public async requestWrapper<T>(
        url: string,
        method: 'GET' | 'POST' | 'PATCH' | 'DELETE',
    ): Promise<T> {
        console.log('Before');

        const response = await requestUrl({
            url: `${environment.serverURL}${environment.apiUrl}/${url}`,
            method: method,
            headers: {
                Authorization: usePluginState.getState().settings?.apiKey,
            },
        });

        console.log('After');

        console.log(response);

        if (response.status === 401) {
            console.log('401');
        } else if (response.status === 402) {
            console.log('402');
        }

        return response.json();
    }

I get “before” but never “after”. I am confused by the fact that everything works fine on Axios. Here is an example

    public async get<T>(
        url: string,
        config?: AxiosRequestConfig<any> | undefined,
    ): Promise<T> {
        return await this.api
            .get<HttpResponse<T>>(url, config)
            .then(({ data }) => data)
            .then(({ data }) => data.payload);
    }

@savylovskij 'After' doesn’t appear because there’s an error, so catch it and find out what it is.

try {
  const res = await requestUrl('https://example.com/nothing-here')
  console.log('This will not appear')
} catch (e) {
  console.log('This will appear')
  console.log(e)        // output the error
  console.log(e.status) // output the statuscode - 404 in this case
}

@joethei FYI you can’t get anything other than a 200 from requestUrl - it throws an error.

1 Like

Thank you. You are right. I got 500.

Just a guess - is the issue that you’re sending

headers: {
    Authorization: usePluginState.getState().settings?.apiKey,
}

when you should be sending

headers: {
    Authorization: 'Bearer ' + usePluginState.getState().settings?.apiKey,
}

I’m not sure if this will work for me because I had it on Axios and it worked

        this.api.interceptors.request.use((config) => {
            config.headers.Authorization =
                usePluginState.getState().settings?.apiKey;
            return config;
        });

Thank you all. Helped - adding headers ‘Content-Type’: ‘application/json’,
Accept: ‘application/json’,

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.