2

I have a piece of code that basically repeats itself. The only difference is the type of params and scan invokes this.getDbClient().scan(params) and query invokes this.getDbClient().query(params).

static scanTable = async (params: DynamoDB.DocumentClient.ScanInput) => {
    let items;
    let scanResults: any[] = [];
    do {
        items = await this.getDbClient().scan(params).promise();
        (items.Items || []).forEach((item) => scanResults.push(item));
        params.ExclusiveStartKey = items.LastEvaluatedKey;
    } while (typeof items.LastEvaluatedKey !== 'undefined');

    return scanResults;
}

static queryTable = async (params: DynamoDB.DocumentClient.QueryInput) => {
    let items;
    let scanResults: any[] = [];
    do {
        items = await this.getDbClient().query(params).promise();
        (items.Items || []).forEach((item) => scanResults.push(item));
        params.ExclusiveStartKey = items.LastEvaluatedKey;
    } while (typeof items.LastEvaluatedKey !== 'undefined');

    return scanResults;
}

I tried to extract the function and use

async (params: DynamoDB.DocumentClient.ScanInput | DynamoDB.DocumentClient.QueryInput)

and then trying to do

if params instanceof DynamoDB.DocumentClient.ScanInput call `scan(params)`
else if params instanceof DynamoDB.DocumentClient.QueryInput call `query(params)`

but it seems that instanceof cannot be used

ERROR: Property 'ScanInput' does not exist on type 'typeof DocumentClient'.ts(2339)

ERROR: Property 'QueryInput' does not exist on type 'typeof DocumentClient'.ts(2339)

What can I do here to avoid the duplication of the code? Any idea?

asdasf
  • 93
  • 7
  • try to define the function [this way](https://stackoverflow.com/a/32263803) – ericmp Dec 19 '22 at 14:55
  • that's what I did.. The issue is then how to determine the type of the input since the `instanceof` does not work – asdasf Dec 19 '22 at 14:57
  • if u did it, u may have a typo `params` -> `param`. not sure – ericmp Dec 19 '22 at 14:58
  • you can either sort out your compiler complaint or re-factor to use only one function. but if they do actually accomplish separate things, maybe 2 functions is best – This Guy Dec 19 '22 at 15:14
  • A generic function based on the operation would work, but these are notoriously hard in TS. See [@jcalz answer to "Generic Functions for Various Data Types in TypeScript"](https://stackoverflow.com/a/73613965/15261914). – Darryl Noakes Dec 19 '22 at 16:21

0 Answers0