Scenario:
In my set of services, I find myself repeatedly writing code for data calls which results in a lot of duplicated code. To streamline the process and reduce redundancy, I am looking to implement a wrapper function:
All these functions essentially perform the same task:
- They require a return parameter.
- They utilize either a post/get/delete method.
- They return a promise.
Here is an example of how I tried to create a generalized wrapper function specifically for the get method:
public httpGetPromise<T extends any>(endpoint: string, returnType: T): Promise<T> {
const promise: Promise<returnType> = new Promise<returnType>((resolve,reject) => {
this.http.get<returnType>(`${this.endpointBaseUri}+${endpoint})
.toPromise().then((response) => {
resolve(response);
}, (err) => {
reject(response);
});
});
return promise;
}
While this does simplify the process somewhat, I am convinced that there are better approaches available.
Is there a more efficient way to write this wrapper function to make it more versatile and adaptable to different input types?
Below are snippets demonstrating typical Get / Post / Delete
functions without the use of a wrapper:
public saveMachine(newMachine: Machine): Promise<Machine> {
// Code for saving a machine
}
public deleteMachine(machine: Machine): Promise<Machine> {
// Code for deleting a machine
}
public getMachinesConfigs(machineId: string): Promise<MachineConfig[]> {
// Code for retrieving machine configurations
}
As evident from the provided examples, there is ample room for generalizing these functions using wrappers.
With the implementation of my suggested wrapper function for 'get', the calls would look something like this:
public getMachinesConfig(machineId:string, MachineConfig[]): MachineConfig[] {
// Implementation using the wrapper function
}
I am using TypeScript version 3.2.4
.
Sidenote: Is it feasible to pass along the HTTP method type within the wrapper parameters? For instance:
public promiseFunc(httpMethod:HttpClient,..., data?:any, etc...)
This way, a single function could cater to all post, get, and delete promises efficiently.