Refactor api client to support dynamic server
This commit is contained in:
parent
fa79b4cbe0
commit
70c62c8b52
1 changed files with 45 additions and 32 deletions
|
@ -4,6 +4,7 @@ import { ndType } from './navidrome-types';
|
|||
import { resultWithHeaders } from '/@/renderer/api/utils';
|
||||
import { toast } from '/@/renderer/components';
|
||||
import { useAuthStore } from '/@/renderer/store';
|
||||
import { ServerListItem } from '/@/renderer/types';
|
||||
|
||||
const c = initContract();
|
||||
|
||||
|
@ -163,16 +164,27 @@ axiosClient.interceptors.response.use(
|
|||
},
|
||||
);
|
||||
|
||||
export const ndApiClient = initClient(contract, {
|
||||
export const ndApiClient = (server: ServerListItem | string) => {
|
||||
return initClient(contract, {
|
||||
api: async ({ path, method, headers, body }) => {
|
||||
const server = useAuthStore.getState().currentServer;
|
||||
const baseUrl = `${server?.url}/api`;
|
||||
const token = server?.ndCredential;
|
||||
let baseUrl: string | undefined;
|
||||
let token: string | undefined;
|
||||
|
||||
if (typeof server === 'object') {
|
||||
const selectedServer = useAuthStore.getState().actions.getServer(server.id);
|
||||
baseUrl = `${selectedServer?.url}/api`;
|
||||
token = selectedServer?.ndCredential;
|
||||
} else {
|
||||
baseUrl = server;
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await axiosClient.request({
|
||||
data: body,
|
||||
headers: { ...headers, 'x-nd-authorization': `Bearer ${token}` },
|
||||
headers: {
|
||||
...headers,
|
||||
...(token && { 'x-nd-authorization': `Bearer ${token}` }),
|
||||
},
|
||||
method: method as Method,
|
||||
url: `${baseUrl}/${path}`,
|
||||
});
|
||||
|
@ -197,3 +209,4 @@ export const ndApiClient = initClient(contract, {
|
|||
},
|
||||
baseUrl: '',
|
||||
});
|
||||
};
|
||||
|
|
Reference in a new issue