2

我想为我在 Loopback 4 中创建的模型实现搜索、过滤和分页功能。我为我创建的模型提供了默认的 7 个 CRUD api,但一切正常。

现在我想添加列表功能(搜索、过滤分页等)如何实现 Loopback 4 文档中没有适当的文档。任何人都可以帮我实现它。

谢谢

4

2 回答 2

2

是的,文档不完整,但似乎他们正在研究它。

同时,您可以同时尝试find()使用repositorywithwhereor参数。对于分页,offset参数limit工作正常。有关过滤器的更多详细信息,请参阅他们的文档。有关CrudConnector.find()方法的详细信息可在此处获得。

供您参考,我将附上我的一段代码并按照您的意愿使用它。

/**
   * customer.repository.ts
   * mongodb datasource
   * @param [searchKey] Search in `firstName`, `lastName`, or `email`
   * @param [pageIndex] page number. If provided, `pageSize` is required
   * @param [pageSize] records per page. If provided, `pageIndex` is required
   * @returns {CustomerInfoInterface[]} List of customers sorted by `firstName`
   */
  async getCustomerList(searchKey?: string, pageIndex?: number, pageSize?: number): Promise<CustomerInfoInterface[]> {
    const searchParam = searchKey || '';
    const searchParams = [
      {firstName: {like: searchParam, options: 'i'}},
      {lastName: {like: searchParam, options: 'i'}},
      {email: {like: searchParam, options: 'i'}},
    ];
    var filterObject = {where: {or: searchParams}, order: ['firstName ASC']};
    if (pageIndex && pageSize) {
      const offset = (pageIndex - 1) * pageSize;
      const limit = pageSize;
      filterObject = Object.assign(filterObject, {limit, offset});
    }
    logger.debug('search user list with search query');
    logger.debug(filterObject);
    const customerList = await this.find(filterObject);
    return customerList.map(i => ({
      customerId: i.customerId,
      firstName: i.firstName,
      lastName: i.lastName,
      phone: i.phone,
      address: i.address,
      id: i.customerId,
    }));
  }
于 2019-09-11T06:12:37.797 回答
2

如另一个答案中所述,LoopBack 4 的文档尚未完成。

对于搜索和过滤记录,LoopBack 4 使用与 LoopBack 3 相同的查询语法,在 TypeScript 级别(请参阅 loopback-datasource-juggler 的文件query.d.ts中的类型定义)和 REST API 级别(通过由lb4 controller命令搭建的控制器) )。

因此,大多数 LoopBack 3 文档也适用于 LoopBack 4。请参阅查询数据中的过滤器部分以开始使用,检查子页面(如过滤器)以获取有关不同过滤字段的更多信息。

于 2019-09-13T07:25:07.930 回答