Skip to content

Instantly share code, notes, and snippets.

@iteufel
Created July 23, 2019 15:48
Show Gist options
  • Save iteufel/09592f8a16279e74a3138c1fdb4926a3 to your computer and use it in GitHub Desktop.
Save iteufel/09592f8a16279e74a3138c1fdb4926a3 to your computer and use it in GitHub Desktop.
Register Typeorm Data Listeners without using decorators
import { EventListenerType } from 'typeorm/metadata/types/EventListenerTypes';
import { getManager, EntitySchema } from 'typeorm';
import { EntityListenerMetadata } from 'typeorm/metadata/EntityListenerMetadata';
export function addDatabaseListener (entity: EntitySchema<any> | Function | string, type: EventListenerType, handler: Function) {
const meta = getManager().connection.getMetadata(entity);
let r = '_' + Math.random().toString(36).substring(7);
(meta.target as any).prototype[r] = handler;
const el = new EntityListenerMetadata({
entityMetadata: meta,
args: {
target: meta.target as any,
propertyName: r,
type: type
}
})
if (type === 'after-insert') {
meta.afterInsertListeners.push(el);
} else if (type === 'before-insert') {
meta.beforeInsertListeners.push(el);
} else if (type === 'after-update') {
meta.afterUpdateListeners.push(el);
} else if (type === 'before-update') {
meta.beforeUpdateListeners.push(el);
} else if (type === 'before-remove') {
meta.beforeRemoveListeners.push(el);
} else if (type === 'after-remove') {
meta.afterRemoveListeners.push(el);
} else if (type === 'after-load') {
meta.afterLoadListeners.push(el);
}
meta.ownListeners.push(el);
meta.listeners.push(el);
}
export function removeDatabaseListener (entity: EntitySchema<any> | Function | string,type: EventListenerType, handler: Function) {
const meta = getManager().connection.getMetadata(entity);
let listeners = [];
if (type === 'after-insert') {
listeners = meta.beforeInsertListeners;
} else if (type === 'before-insert') {
listeners = meta.afterInsertListeners;
} else if (type === 'after-update') {
listeners = meta.afterUpdateListeners;
} else if (type === 'before-update') {
listeners = meta.beforeUpdateListeners;
} else if (type === 'before-remove') {
listeners = meta.beforeRemoveListeners;
} else if (type === 'after-remove') {
listeners = meta.afterRemoveListeners;
} else if (type === 'after-load') {
listeners = meta.afterLoadListeners;
}
const protoHandler = Object.entries((entity as any).prototype).find(e => e[1] === handler);
if (!protoHandler) {
return;
}
const index = listeners.findIndex(e => e.propertyName === protoHandler[0]);
if (index !== -1) {
listeners.splice(index, 1);
delete (entity as any).prototype[protoHandler[0]];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment