summaryrefslogtreecommitdiffstatshomepage
path: root/frontend/src/lib/Update.ts
blob: 507dd52bf57bb6096fae2c14e1a479a56f6bb174 (plain) (blame)
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
97
import {
	UpdateMode,
	type UpdateComicInput,
	type UpdateOptions,
	type UpdateTagInput
} from '$gql/graphql';

type Key = string | number | symbol;

interface AssociationUpdate {
	ids?: number[] | string[] | null;
	options?: UpdateOptions | null;
}

type Input<T, K extends Key> = {
	[Property in K]?: T | null;
};

abstract class Entry<K extends Key> {
	key: K;

	constructor(key: K) {
		this.key = key;
	}

	abstract integrate(input: Input<unknown, K>): void;
	abstract hasInput(): boolean;
}

class Association<K extends Key> extends Entry<K> {
	ids = [];
	options = {
		mode: UpdateMode.Add
	};

	constructor(key: K) {
		super(key);
	}

	integrate(input: Input<AssociationUpdate, K>) {
		if (this.hasInput()) {
			input[this.key] = { ids: this.ids, options: this.options };
		}
	}

	hasInput() {
		return this.ids.length > 0;
	}
}

class Enum<K extends Key> extends Entry<K> {
	value?: string = undefined;

	constructor(key: K) {
		super(key);
	}

	integrate(input: Input<string, K>): void {
		if (this.hasInput()) {
			input[this.key] = this.value;
		}
	}

	hasInput() {
		return this.value !== undefined && this.value !== null;
	}
}

abstract class Controls<I> {
	toInput() {
		const input = {} as I;
		Object.values(this).forEach((v: Entry<keyof I>) => v.integrate(input));
		return input;
	}

	hasInput() {
		return Object.values(this).some((i: Entry<keyof I>) => i.hasInput());
	}
}

export class UpdateTagsControls extends Controls<UpdateTagInput> {
	namespaces = new Association('namespaces');
}

export class UpdateComicsControls extends Controls<UpdateComicInput> {
	artists = new Association('artists');
	category = new Enum('category');
	censorship = new Enum('censorship');
	direction = new Enum('direction');
	layout = new Enum('layout');
	characters = new Association('characters');
	circles = new Association('circles');
	language = new Enum('language');
	rating = new Enum('rating');
	tags = new Association('tags');
	worlds = new Association('worlds');
}