Permalink
Browse files

feat(IdentityMap): Added a IdentityMap

  • Loading branch information...
RWOverdijk committed Sep 21, 2016
1 parent d82db41 commit d79dd6d0f956d0cfc9325ea0a7d4b3c46b3c969a
Showing with 54 additions and 0 deletions.
  1. +54 −0 src/IdentityMap.ts
@@ -0,0 +1,54 @@
import {Mapping} from './Mapping';
import {EntityInterface} from './EntityInterface';
export class IdentityMap {
/**
* Map entities to objects.
*
* @type {WeakMap<Function, Object>}
*/
private map: WeakMap<Function, Object> = new WeakMap;
/**
* Get the PK map for entity.
*
* @param {Function | EntityInterface} entity
*
* @returns {Object}
*/
public getMapForEntity(entity: Function | EntityInterface): Object {
let entityReference = (typeof entity === 'function' ? entity : entity.constructor) as Function;
let map = this.map.get(entityReference);
if (!map) {
this.map.set(entityReference, {});
}
return this.map.get(entityReference);
}
/**
* Register an entity with the map.
*
* @param {EntityInterface} entity
*
* @returns {IdentityMap}
*/
public register(entity: EntityInterface) {
this.getMapForEntity(entity)[entity[Mapping.forEntity(entity).getPrimaryKey()]] = entity;
return this;
}
/**
* Fetch an entity from the map.
*
* @param {EntityInterface|Function} entity
* @param {*} primaryKey
*
* @returns {EntityInterface|null}
*/
public fetch(entity: EntityInterface | Function, primaryKey: any): EntityInterface | null {
return this.getMapForEntity(entity)[primaryKey] || null;
}
}

0 comments on commit d79dd6d

Please sign in to comment.