跳转至

需要import Fluent

Filter

http://localhost:8080/api/acronyms/search?term={searchItem}

1
2
3
4
5
6
7
8
router.get("api", "acronyms", "search") { (req) -> Future<[Acronym]> in
    guard let searchItem = req.query[String.self, at: "term"] else {
        throw Abort(.badRequest)
    }
    return Acronym.query(on: req)
    .filter(\.short == searchItem)
    .all()
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
router.get("api", "acronyms", "search") { (req) -> Future<[Acronym]> in
    guard let searchItem = req.query[String.self, at: "term"] else {
        throw Abort(.badRequest)
    }
    return Acronym.query(on: req).group(.or) { (or) in
        or.filter(\.short == searchItem)
        or.filter(\.long == searchItem)
    }
    .all()
}

First

1
2
3
4
5
6
7
8
router.get("api","acronyms","first") { (req) -> Future<Acronym> in
    return Acronym.query(on: req).first().map(to: Acronym.self) { (acronym)  in
        guard let acronym = acronym else {
            throw Abort(.notFound)
        }
        return acronym
    }
}

或者更简单一点就是:

1
2
3
func firstHandler(_ req: Request) throws -> Future<Acronym> {
    return Acronym.query(on: req).first().unwrap(or: Abort(.notFound))
}

Sort

1
2
3
router.get("api","acronyms","sorted") { (req) -> Future<[Acronym]> in
    return Acronym.query(on: req).sort(\.short, .ascending).all()
}