summary refs log tree commit diff
path: root/src/util/cache/EntityCache.ts
blob: 9135fef3b8e5ecf3f79923515da2df4c27acbf44 (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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
/*
	Fosscord: A FOSS re-implementation and extension of the Discord.com backend.
	Copyright (C) 2023 Fosscord and Fosscord Contributors
	
	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU Affero General Public License as published
	by the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.
	
	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU Affero General Public License for more details.
	
	You should have received a copy of the GNU Affero General Public License
	along with this program.  If not, see <https://www.gnu.org/licenses/>.
*/
/* eslint-disable */
import {
	DataSource,
	FindOneOptions,
	EntityNotFoundError,
	FindOptionsWhere,
} from "typeorm";
import { QueryDeepPartialEntity } from "typeorm/query-builder/QueryPartialEntity";
import { BaseClassWithId } from "../entities/BaseClass";
import { Config, getDatabase } from "../util";
import { CacheManager } from "./Cache";

function getObjectKeysAsArray(obj?: Record<string, any>) {
	if (!obj) return [];
	if (Array.isArray(obj)) return obj;
	return Object.keys(obj);
}

export type ThisType<T> = {
	new (): T;
} & typeof BaseEntityCache;

interface BaseEntityCache {
	constructor: typeof BaseEntityCache;
}

// @ts-ignore
class BaseEntityCache extends BaseClassWithId {
	static cache: CacheManager;
	static cacheEnabled: boolean;

	public get metadata() {
		return getDatabase()?.getMetadata(this.constructor)!;
	}

	static useDataSource(dataSource: DataSource | null) {
		super.useDataSource(dataSource);
		this.cacheEnabled = Config.get().cache.enabled ?? true;
		if (Config.get().cache.redis) return; // TODO: Redis cache
		if (!this.cacheEnabled) return;
		this.cache = new CacheManager();
	}

	static async findOne<T extends BaseEntityCache>(
		this: ThisType<T>,
		options: FindOneOptions<T>,
	) {
		// @ts-ignore
		if (!this.cacheEnabled) return super.findOne(options);
		let select = getObjectKeysAsArray(options.select);

		if (!select.length) {
			// get all columns that are marked as select
			getDatabase()
				?.getMetadata(this)
				.columns.forEach((x) => {
					if (!x.isSelect) return;
					select.push(x.propertyName);
				});
		}
		if (options.relations) {
			select.push(...getObjectKeysAsArray(options.relations));
		}

		const cacheResult = this.cache.find(options.where as never, select);
		if (cacheResult) {
			const hasAllProps = select.every((key) => {
				if (key.includes(".")) return true; // @ts-ignore
				return cacheResult[key] !== undefined;
			});
			// console.log(`[Cache] get ${cacheResult.id} from ${cacheResult.constructor.name}`,);
			if (hasAllProps) return cacheResult;
		}

		// @ts-ignore
		const result = await super.findOne<T>(options);
		if (!result) return null;

		this.cache.insert(result as any);

		return result;
	}

	static async findOneOrFail<T extends BaseEntityCache>(
		this: ThisType<T>,
		options: FindOneOptions<T>,
	) {
		const result = await this.findOne<T>(options);
		if (!result) throw new EntityNotFoundError(this, options);
		return result;
	}

	save() {
		if (this.constructor.cacheEnabled) this.constructor.cache.insert(this);
		return super.save();
	}

	remove() {
		if (this.constructor.cacheEnabled)
			this.constructor.cache.delete(this.id);
		return super.remove();
	}

	static async update<T extends BaseEntityCache>(
		this: ThisType<T>,
		criteria: FindOptionsWhere<T>,
		partialEntity: QueryDeepPartialEntity<T>,
	) {
		// @ts-ignore
		const result = super.update<T>(criteria, partialEntity);
		if (!this.cacheEnabled) return result;

		const entities = this.cache.filter(criteria as never);
		for (const entity of entities) {
			// @ts-ignore
			partialEntity.id = entity.id;
			this.cache.insert(partialEntity as never);
		}

		return result;
	}

	static async delete<T extends BaseEntityCache>(
		this: ThisType<T>,
		criteria: FindOptionsWhere<T>,
	) {
		// @ts-ignore
		const result = super.delete<T>(criteria);
		if (!this.cacheEnabled) return result;

		const entities = this.cache.filter(criteria as never);
		for (const entity of entities) {
			this.cache.delete(entity.id);
		}

		return result;
	}
}

// needed, because typescript can't infer the type of the static methods with generics
const EntityCache = BaseEntityCache as unknown as typeof BaseClassWithId;

export { EntityCache };