如何在loopback 4中实现搜索和过滤操作?

How to implement search and filter operations in loopback 4?

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

现在我想添加列表功能(搜索、筛选分页等)如何实现,在 Loopback 4 文档中没有适当的文档。谁能帮我实现一下。

谢谢

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

同时,您可以在 repository 上同时使用 whereor 参数尝试 find()。对于分页,offsetlimit 参数工作正常。有关可用过滤器的更多详细信息 here on their docs. Details on CrudConnector.find() method is available here

为了您的参考,我会附上我的一段代码,您可以随意使用它。

/**
   * 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,
    }));
  }

如其他答案中所述,LoopBack 4 的文档尚未完成。

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

因此,大多数 LoopBack 3 文档也适用于 LoopBack 4。有关不同筛选字段的更多信息,请参阅 Filters section in Querying data to get started, check sub-pages like Where filter