All files / src/apiProxy ApiProxy.ts

100% Statements 29/29
100% Branches 1/1
100% Functions 9/9
100% Lines 22/22

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 621x               1x 12x     12x   12x 24x 24x   8x   8x   8x         8x                       1x 8x     1x 12x     12x 12x     14x 8x         1x 12x   1x  
import { randomUUID } from "../utils/crypto";
import {IApiConfig} from "../model/IApiConfig";
import {IApiProxy} from "../model/IApiProxy";
import {IRequestPayload} from "../model/IRequestPayload";
import {IResponsePayload} from "../model/IResponsePayload";
 
type outboundFn = (payload: IRequestPayload) => void;
 
export class ApiProxy {
    private proxy: IApiProxy = {};
    private outboundFn: outboundFn;
 
    private promiseMap = new Map<string, {res: Function, rej: Function}>();
 
    constructor(apiConfig: IApiConfig) {
        for (const prop of apiConfig.props) {
            this.proxy[prop] = (...args: unknown[]): Promise<void> => {
 
                const uuid = randomUUID();
 
                return new Promise((res, rej) => {
 
                    this.promiseMap.set(uuid, {
                        res,
                        rej
                    });
 
                    this.getOutboundFn()({
                        uuid,
                        propertyToCall: prop,
                        args
                    });
 
                });
 
            }
        }
    }
 
    private getOutboundFn() {
        return this.outboundFn;
    }
 
    get (): IApiProxy {
        return this.proxy;
    }
 
    getInboundFn() {
        return (payload: IResponsePayload) => {
            //TODO: see how to reject
            //TODO: should remove promise from map?
            if(this.promiseMap.has(payload.uuid)) {
                this.promiseMap.get(payload.uuid).res(payload.returnValue);
            }
        }
    }
 
    setOutboundFn(outboundFn: outboundFn) {
        this.outboundFn = outboundFn;
    }
}