Skip to content

Instantly share code, notes, and snippets.

@sambhav2612
Created August 23, 2020 08:21
Show Gist options
  • Save sambhav2612/381dbea190c50dd0fca6ffbc88d2884e to your computer and use it in GitHub Desktop.
Save sambhav2612/381dbea190c50dd0fca6ffbc88d2884e to your computer and use it in GitHub Desktop.
a service method to fetch data based on query filters and user subscription while maintaining past search records
async fetch(user: any, query: string, search: boolean): Promise<any> {
const subscription = await this.subscriptionService.findOneByUser(user && user.id);
if (subscription && subscription.isActive) {
const searchRecords = await this.searchService.getForUser(user && user.id);
const todaySearchRecords = searchRecords.filter(ele => new Date(ele.createdAt).toDateString() === new Date().toDateString());
const flag = todaySearchRecords.length < subscription.searchLimit;
if ((flag && search) || !search) {
let records = await getManager().query(query);
let newQuery = query;
newQuery = newQuery.replace(newQuery.substr(newQuery.includes('order') ? newQuery.lastIndexOf('order') : newQuery.lastIndexOf('limit')), ' ');
const allRecords = await getManager().query(newQuery);
if (records.length !== 2500) {
records = allRecords.slice(0, 2500);
console.log('returned records from all records');
}
const condition = newQuery.substr(newQuery.indexOf('where'));
newQuery = `select count(*), sum(cast("totalValueInUsd" as float)) as "totalValueInUsd", sum(cast("fobInInr" as float)) as "totalValueInInr" from export_data\n`;
newQuery += condition;
newQuery += `and ("totalValueInUsd" != 'N/A' and "totalValueInUsd" != 'N?A') and ("fobInInr" != 'N/A' and "fobInInr" != 'N?A')`;
let metadata = await getManager().query(newQuery);
metadata = metadata[0];
const count = Number(metadata.count);
const totalValueInUsd = convertNotation(Number(metadata.totalValueInUsd), 'us');
const totalValueInInr = convertNotation(Number(metadata.totalValueInInr), 'indian');
if (flag && search && count > 0) {
const newSearch = { user, type: 'export' };
await this.searchService.create(newSearch);
}
return {
result: records,
count,
totalValueInInr,
totalValueInUsd,
};
}
throw new HttpException('Your search quota for today has been exhausted, please come back tomorrow!', HttpStatus.FORBIDDEN);
}
throw new HttpException('No active subscription found', HttpStatus.FORBIDDEN);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment