Refactor api client to support dynamic server

This commit is contained in:
jeffvli 2023-04-23 14:26:41 -07:00
parent fa79b4cbe0
commit 70c62c8b52

View file

@ -4,6 +4,7 @@ import { ndType } from './navidrome-types';
import { resultWithHeaders } from '/@/renderer/api/utils'; import { resultWithHeaders } from '/@/renderer/api/utils';
import { toast } from '/@/renderer/components'; import { toast } from '/@/renderer/components';
import { useAuthStore } from '/@/renderer/store'; import { useAuthStore } from '/@/renderer/store';
import { ServerListItem } from '/@/renderer/types';
const c = initContract(); const c = initContract();
@ -163,37 +164,49 @@ axiosClient.interceptors.response.use(
}, },
); );
export const ndApiClient = initClient(contract, { export const ndApiClient = (server: ServerListItem | string) => {
api: async ({ path, method, headers, body }) => { return initClient(contract, {
const server = useAuthStore.getState().currentServer; api: async ({ path, method, headers, body }) => {
const baseUrl = `${server?.url}/api`; let baseUrl: string | undefined;
const token = server?.ndCredential; let token: string | undefined;
try { if (typeof server === 'object') {
const result = await axiosClient.request({ const selectedServer = useAuthStore.getState().actions.getServer(server.id);
data: body, baseUrl = `${selectedServer?.url}/api`;
headers: { ...headers, 'x-nd-authorization': `Bearer ${token}` }, token = selectedServer?.ndCredential;
method: method as Method, } else {
url: `${baseUrl}/${path}`, baseUrl = server;
});
return {
body: { data: result.data, headers: result.headers },
status: result.status,
};
} catch (e: Error | AxiosError | any) {
if (isAxiosError(e)) {
const error = e as AxiosError;
const response = error.response as AxiosResponse;
return {
body: { data: response.data, headers: response.headers },
status: response.status,
};
} }
throw e;
} try {
}, const result = await axiosClient.request({
baseHeaders: { data: body,
'Content-Type': 'application/json', headers: {
}, ...headers,
baseUrl: '', ...(token && { 'x-nd-authorization': `Bearer ${token}` }),
}); },
method: method as Method,
url: `${baseUrl}/${path}`,
});
return {
body: { data: result.data, headers: result.headers },
status: result.status,
};
} catch (e: Error | AxiosError | any) {
if (isAxiosError(e)) {
const error = e as AxiosError;
const response = error.response as AxiosResponse;
return {
body: { data: response.data, headers: response.headers },
status: response.status,
};
}
throw e;
}
},
baseHeaders: {
'Content-Type': 'application/json',
},
baseUrl: '',
});
};