I have a class which manages few requests. So requests are set up as a collection. I've done this way to avoid having to write lengthy switch/if else statements.
// Manager class
class makeManagerRequests() {
private list = [];
private createList(body) {
this.list.push(body)
}
createEmployee(body) {
this.createlist(body);
}
updateManager(body);
deleteManager(body);
}
// Employee class
class makeEmployeeRequests() {
private list = [];
private createList(body) {
this.list.push(body)
}
createEmployee(body) {
this.createlist(body);
}
updateEmployee(body)
deleteEmployee(body)
}
// Usage in a generic widget
class makeRequests() {
requestMap = new Map();
constructor(makeManagerRequests, makeEmployeeRequests) {
}
createRequestMap() {
requestMap.set('createManager', this.makeManagerRequest.createManager.bind(this));
requestMap.set('updateManager', this.makeManagerRequest.updateManager.bind(this));
requestMap.set('deleteManager', this.makeManagerRequest.deleteManager.bind(this));
requestMap.set('createEmployee', this.makeManagerRequest.createEmployee.bind(this));
requestMap.set('updateEmployee', this.makeManagerRequest.updateEmployee.bind(this));
requestMap.set('deleteEmployee', this.makeManagerRequest.deleteEmployee.bind(this));
}
makeRequest(data) {
let req = requestMap.get(data.requestType);
req(data.body)
}
}
This itself works.
First thing I noticed was keyword "this" change scope when using get Map from "service" to the "widget" so that createlist()
become undefined. BUT if I just do this without bind it works.
// I can test this with mocking the makeManagerRequest
makeRequest(data) {
this.makeManagerRequest.updateEmployee(body)
}
When using map I need .bind(this)
. Not sure why "this" change? Issue this creates is when I try to test and mock the service and spy on service. I get spy never been called. So I think what happens is bind create new function when creating the map. So I can't spy on
spyOn(MockMakeManagerRequest, 'updateEmployee')
So I am trying to figure out how does the functions themselves stored in the Map(). I am looking for technical implications this collection and how I can make this work so I can implement tests around this.
This is actually being used with in Angular 2 app. But I don't think it would make much difference as I am trying to figure what happens to/test functions when stored as a value in Map();