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?