Skip to content

Instantly share code, notes, and snippets.

@alfari16
Last active December 14, 2020 16:51
Show Gist options
  • Select an option

  • Save alfari16/533dded8aee9ad5dcbf30267c2d90a0d to your computer and use it in GitHub Desktop.

Select an option

Save alfari16/533dded8aee9ad5dcbf30267c2d90a0d to your computer and use it in GitHub Desktop.
// graphql.ts
// ...other codes
enum PaginationSortByEnum {
ASC = 'asc',
DESC = 'desc'
}
interface IPagination {
limit: number
offset: number
orderBy: string
sortBy: PaginationSortByEnum
search: string
}
const loaders = () => {
let productsPagination: IPagination;
const productsByMerchantIdLoader = new Dataloader(async merchantIds => {
const connection = Knex(config.get('database'));
const table = connection('products');
const {limit, offset, orderBy, sortBy, search} = productsPagination;
if(search)
table.where('name', 'LIKE', `%${search}%`)
const products = await connection.union(
merchantIds.map(id =>
table
.where('merchantId', id)
.orderBy(orderBy, sortBy)
.limit(limit)
.offset(offset)
),
true //option for wrap queries
);
return merchantIds.map(merchantId => products.filter(product => product.merchantId === merchantId));
});
return {
getLocationsByMerchantId: new Dataloader(async merchantIds => {
const locations = await Knex(config.get('database'))('locations')
.whereIn('merchantId', merchantIds);
return merchantIds.map(merchantId => locations.find(location => location.merchantId === merchantId));
}),
getProductsByMerchantId(pagination: IPagination){
productsPagination = pagination;
return productsByMerchantIdLoader;
}
};
};
// ...other codes
@rechl
Copy link

rechl commented Dec 14, 2020

@alfari16 thanks for your great article on medium.com. I was wondering how you would return the total number of results to the client.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment