File size: 2,360 Bytes
2b7aae2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import { SolutionStore } from './store';
import { RegulationSolution } from '../../src/starry';
import getSign from '../../src/utils/request/createSign';
import * as asyncAtom from '../../src/utils/asyncAtom';

const getHeaders = (method: string = 'get', data: any = {}): Record<string, string> => {
	const headers = {
		stmp: Date.now(),
		sess: '654a591de5d3a4b0',
		ver: 512,
		orn: '(X11;$Linux x86_64$android$1.0.0$torchTrain',
		sign: '',
		size: 0,
		dst: '',
		type: 1,
		lang: 'zh_CN',
		seq: 0,
		code: 0,
		ext: 'CN',
		desc: '',
	} as any;
	headers.sign = getSign({ method, data, requestHeader: headers });

	return headers;
};

export default class AdminSolutionStore implements SolutionStore {
	env: string;
	host: string;
	fetch: typeof fetch;

	constructor(options: { env: string; host: string; fetch: typeof fetch }) {
		Object.assign(this, options);
	}

	post(path, { data }: any): Promise<any> {
		const headers = getHeaders('post', data);
		headers['content-type'] = 'application/json;charset=UTF-8';

		return this.fetch(this.host + path, {
			method: 'post',
			headers,
			body: JSON.stringify(data),
		}).then((res) => res.json());
	}

	async batchGet(keys: string[]): Promise<RegulationSolution[]> {
		const solutions = (
			await this.post('/torch/musicSet/manage/cache/batchGet', {
				data: {
					env: this.env,
					nameList: keys,
				},
			})
		).data as RegulationSolution[];
		//console.log('AdminSolutionStore.batchGet:', solutions);

		return Promise.all(solutions);
	}

	async get(key: string): Promise<RegulationSolution> {
		const solution = (await this.post('/torch/musicSet/manage/cache/batchGet', {
			data: {
				env: this.env,
				nameList: [key],
			},
		}).then((res) => res.data[0])) as RegulationSolution;
		//console.log('AdminSolutionStore.get:', key, solution);

		return solution;
	}

	async set(key: string, value: RegulationSolution) {
		const request = () =>
			this.post('/torch/musicSet/manage/cache/set', {
				data: {
					env: this.env,
					name: key,
					value: value,
				},
			}).catch((err) => console.warn('failed to set solution:', key, err));
		asyncAtom.queue(this, request);

		//console.log('AdminSolutionStore.set:', key, res.ok);
	}

	/*remove(key: string) {
		return request.post('/torch/musicSet/manage/cache/delete', {
			data: {
				env: this.env,
				name: key,
			},
		});
	}*/
}