Last active
December 14, 2020 16:51
-
-
Save alfari16/533dded8aee9ad5dcbf30267c2d90a0d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@alfari16 thanks for your great article on medium.com. I was wondering how you would return the total number of results to the client.