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?

5
  • try to define the function this way Commented Dec 19, 2022 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 Commented Dec 19, 2022 at 14:57
  • if u did it, u may have a typo params -> param. not sure Commented Dec 19, 2022 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 Commented Dec 19, 2022 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". Commented Dec 19, 2022 at 16:21

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.