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 { 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,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 }) => {
|
api: async ({ path, method, headers, body }) => {
|
||||||
const server = useAuthStore.getState().currentServer;
|
let baseUrl: string | undefined;
|
||||||
const baseUrl = `${server?.url}/api`;
|
let token: string | undefined;
|
||||||
const token = server?.ndCredential;
|
|
||||||
|
if (typeof server === 'object') {
|
||||||
|
const selectedServer = useAuthStore.getState().actions.getServer(server.id);
|
||||||
|
baseUrl = `${selectedServer?.url}/api`;
|
||||||
|
token = selectedServer?.ndCredential;
|
||||||
|
} else {
|
||||||
|
baseUrl = server;
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const result = await axiosClient.request({
|
const result = await axiosClient.request({
|
||||||
data: body,
|
data: body,
|
||||||
headers: { ...headers, 'x-nd-authorization': `Bearer ${token}` },
|
headers: {
|
||||||
|
...headers,
|
||||||
|
...(token && { 'x-nd-authorization': `Bearer ${token}` }),
|
||||||
|
},
|
||||||
method: method as Method,
|
method: method as Method,
|
||||||
url: `${baseUrl}/${path}`,
|
url: `${baseUrl}/${path}`,
|
||||||
});
|
});
|
||||||
|
@ -197,3 +209,4 @@ export const ndApiClient = initClient(contract, {
|
||||||
},
|
},
|
||||||
baseUrl: '',
|
baseUrl: '',
|
||||||
});
|
});
|
||||||
|
};
|
||||||
|
|
Reference in a new issue