Files
social-router/packages/xhs/src/services/xhs-services.ts
2025-05-02 15:39:44 +08:00

57 lines
1.3 KiB
TypeScript

import { XhsClient } from '@/libs/xhs.ts';
type XhsClientOptions = {
key: string;
cookie: string;
signConfig?: {
signUrl: string;
};
[key: string]: any;
};
type XhsClientMap = {
client: XhsClient;
key: string;
options: XhsClientOptions;
};
type XhsServicesOptions = {
root?: string;
};
export class XhsServices {
map: Map<string, XhsClientMap> = new Map();
root: string = 'root';
constructor(opts?: XhsServicesOptions) {
this.root = opts?.root || this.root;
}
createClient(options: XhsClientOptions) {
const { key, cookie, signConfig } = options;
if (this.map.has(key)) {
return this.map.get(key);
}
const client = new XhsClient({ cookie });
client.signConfig = signConfig;
this.map.set(key, { client, key, options });
return client;
}
createRoot(options: Partial<XhsClientOptions>) {
options.key = options.key || this.root;
return this.createClient(options as XhsClientOptions);
}
getKey(key?: string) {
if (!key) key = this.root;
return key;
}
/**
* Get the XhsClient instance by key
* @param key
* @returns
*/
getClient(key?: string) {
const xhsClient = this.map.get(this.getKey(key));
return xhsClient.client;
}
getXhsClient(key?: string) {
const xhsClient = this.map.get(this.getKey(key));
return xhsClient;
}
}