Winsights

Dynamic Sorting and Paging

Sort and Page based on query parameters passed in the request

     func sortedHandler(_ req: Request) async throws -> Page<Customer> {
        let order = req.query[String.self, at: "order"] ?? "ascending"

        let orderType: DatabaseQuery.Sort.Direction

        switch order {
        case DatabaseQuery.Sort.Direction.ascending.description:
            orderType = DatabaseQuery.Sort.Direction.ascending
        case DatabaseQuery.Sort.Direction.descending.description:
            orderType = DatabaseQuery.Sort.Direction.descending
        default:
            orderType = DatabaseQuery.Sort.Direction.ascending
        }

        if let sortField = req.query[String.self, at: "sort"] {
            let sortByParam = Customer.keys.first{ $0 == FieldKey(stringLiteral: sortField) }

            if let sortByParam = sortByParam {
                return try await Customer.query(on: req.db)
                    .sort(sortByParam, orderType)
                    .paginate(for: req)
            }
            else {
                return try await Customer.query(on: req.db)
                    //.sort(fieldKey, .ascending)
                    .paginate(for: req)
                //.all()
            }
        }
        else {
            throw Abort(.badRequest, reason: "Bad field")
        }
    }
Tagged with: