Files
mail_manager/src/models/mutation-proxy.ts
Sebastian Krupinski 99a68737d1
Some checks failed
JS Unit Tests / test (pull_request) Failing after 29s
Build Test / test (pull_request) Successful in 31s
PHP Unit Tests / test (pull_request) Successful in 1m12s
feat: lots more improvements
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-04-25 15:41:16 -04:00

61 lines
1.9 KiB
TypeScript

import { clonePlain } from './clone-plain';
export class MutationProxy<T extends object> {
private readonly getOriginal: () => T;
private readonly getMutated: () => Partial<T>;
constructor(
getOriginal: () => T,
getMutated: () => Partial<T>,
) {
this.getOriginal = getOriginal;
this.getMutated = getMutated;
}
create(): T {
return new Proxy({} as T, {
get: (_target, prop: string | symbol) => {
if (typeof prop !== 'string') {
return undefined;
}
const key = prop as keyof T;
const mutated = this.getMutated();
const original = this.getOriginal();
return key in mutated ? mutated[key] : original[key];
},
set: (_target, prop: string | symbol, value: unknown) => {
if (typeof prop === 'string') {
const key = prop as keyof T;
(this.getMutated() as Record<keyof T, unknown>)[key] = clonePlain(value);
}
return true;
},
has: (_target, prop: string | symbol) => {
if (typeof prop !== 'string') {
return false;
}
const mutated = this.getMutated();
const original = this.getOriginal();
return prop in mutated || prop in original;
},
ownKeys: () => {
const mutated = this.getMutated();
const original = this.getOriginal();
return Array.from(new Set([
...Reflect.ownKeys(original),
...Reflect.ownKeys(mutated),
]));
},
getOwnPropertyDescriptor: () => ({
enumerable: true,
configurable: true,
}),
});
}
}