• Stars
    star
    102
  • Rank 335,584 (Top 7 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 9 years ago
  • Updated almost 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Build search queries for objection.js models using HTTP query parameters.

Build Status Coverage Status

Topics

Introduction

Note: since Objection.js (which this library is based on) now requires Node 6.0.0 as the minimum, objection-find will not work on node < 6.0.0 either.

Objection-find is a module for building search queries for objection.js models using HTTP query parameters. You can easily filter, order and page the result based on model's properties and relations using simple expressions. Relations can be eagerly fetched for the results using objection.js relation expressions.

Using objection-find in an express route is as easy as this:

const findQuery = require('objection-find');
// Our objection.js model.
const Person = require('../models/Person');

expressApp.get('/api/persons', function (req, res, next) {
  findQuery(Person)
    .allow(['firstName', 'movies.name', 'children.age', 'parent.lastName'])
    .allowEager('[children.movies, movies, parent.movies]')
    .build(req.query)
    .then(function (persons) {
      res.send(persons);
    })
    .catch(next);
});

Objection-find can be used with any node.js framework. Express is not a requirement. The route we just created can be used like this:

$http({
  method: 'GET',
  url: '/api/persons',

  // HTTP Query parameters.
  params: {
    // Select all persons whose first name starts with 'j' or 'J'
    'firstName:likeLower': 'J%',

    // And who have acted in the movie 'Silver Linings Playbook'.
    // This checks if the relation `movies` contains at least
    // one movie whose name equals 'Silver Linings Playbook'.
    'movies.name:eq': 'Silver Linings Playbook',

    // And who have at least one child younger than 10.
    // This checks if the relation `children` contains at least
    // one person whose age is less than 10.
    'children.age:lt': 10,

    // Order the result by person's parent's last name.
    // `parent` is a one-to-one relation.
    'orderBy': 'parent.lastName',

    // Fetch relations for the results. This is an objection.js
    // relation expression. Check out objection.js for more info.
    'eager': '[children, movies, parent.movies]',

    // Fetch only count of entries that satisfy given criteria. Value can include optional alias parameter, e. g. 'id as countId'. '*' is a valid value.
    'count': 'id',

    // Group fetched entries by specified properties. Primarily intended to be used together with 'count' parameter'.
    'groupBy': 'firstName,lastName',

    // Select a range starting from index 0
    'rangeStart': 0,

    // Select a range ending to index 4
    'rangeEnd': 4
  }
}).then(function (res) {
  const persons = res.data.results;

  console.log(persons.length); // --> 5
  console.log(persons[0].children);
  console.log(persons[0].movie);
  console.log(persons[0].parent.movies);

  // Total size of the result if the range wasn't given.
  console.log(res.data.total);
});

In our example Person model had a one-to-one relation parent, a many-to-many relation movies and one-to-many relation children. This example used the $http module of AngularJS but you can use objection-find with anything that can send an HTTP request.

Documentation on the supported query parameters can be found here and API documentation here.

It is recommended to use query builder for constructing query parameters on the client side.

Installation

npm install objection objection-find

Getting started

Easiest way to get started is to use the objection.js example project and copy paste this to the api.js file:

const findQuery = require('objection-find');

app.get('/persons/search', function (req, res, next) {
  findQuery(Person).build(req.query).then(function (persons) {
    res.send(persons);
  }).catch(next);
});

You also need to run this in the root of the example project to install objection-find:

npm install --save objection-find

Now you can start bombing the /persons/search route. Documentation on the supported query parameters can be found here.

Query parameters

Objection-find understands two kinds of query parameters: filters and special parameters.

Filters

A filter parameter has the following format:

<propertyReference>|<propertyReference>|...:<filter>=<value>

A propertyReference is either simply a property name like firstName or a reference to a relation's property like children.age (children is the name of the relation).

filter is one of the built-in filters eq, neq, lt, lte, gt, gte, like, likeLower in, notNull or isNull. Filter can also be a custom filter registered using the registerFilter method.

The following examples explain how filter parameters work. For the examples, assume we have an objection.js model Person that has a one-to-one relation parent, a many-to-many relation movies and one-to-many relation children.

Filter query parameter Explanation
firstName=Jennifer Returns all Persons whose first name is 'Jennifer'.
firstName:eq=Jennifer Returns all Persons whose first name is 'Jennifer'.
children.firstName:like=%rad% Returns all Persons who have at least one child whose first name contains 'rad'.
lastName|movies.name:like=%Gump% Returns all Persons whose last name contains 'Gump' or who acted in a movie whose name contains 'Gump'.
parent.age:lt=60 Returns all persons whose parent's age is less than 60.
parent.age:in=20,22,24 Returns all persons whose parent's age is 20, 22 or 24.

Filters are joined with AND operator so for example the query string:

firstName:eq=Jennifer&parent.age:lt=60&children.firstName:like=%rad%

would return the Persons whose firstName is 'Jennifer' and whose parent's age is less than 60 and who have at least one child whose name contains 'rad'.

Special parameters

In addition to the filter parameters, there is a set of query parameters that have a special meaning:

Special parameter Explanation
eager=[children, parent.movies] Which relations to fetch eagerly for the result models. An objection.js relation expression. That pass to withGraphFetched.
join=[parent, parent.movies] Which relations to join and fetch eagerly for the result models. An objection.js relation expression. That pass to withGraphJoined.
orderBy=firstName Sort the result by certain property.
orderByDesc=firstName Sort the result by certain property in descending order.
rangeStart=10 The start of the result range (inclusive). The result will be {total: 12343, results: [ ... ]}.
rangeEnd=50 The end of the result range (inclusive). The result will be {total: 12343, results: [ ... ]}.

Additional parameters

Any query parameters, that are not listed in Special parameters, such as page, can be passed as query in second parameter.

const findQuery = require('objection-find');

app.get('/persons', function (req, res, next) {
  const { page, ...query } = req.query;
  
  findQuery(Person)
    .build(query, Person.query().page(page, 12))
    .then(function (persons) {
      res.send(persons);
    })
    .catch(next);
});

More Repositories

1

objection.js

An SQL-friendly ORM for Node.js
JavaScript
7,249
star
2

tarn.js

Simple and robust resource pool for node.js
JavaScript
472
star
3

objection-graphql

GraphQL schema generator for objection.js
JavaScript
307
star
4

venia

Clojure(Script) graphql query generation
Clojure
197
star
5

knex-db-manager

Utility for create, drop, truncate etc. administrative database operations.
JavaScript
142
star
6

db-errors

Unified node.js error API for mysql, postgres and sqlite3
JavaScript
85
star
7

objection-db-errors

A plugin that provides better database error handling for objection.js
JavaScript
71
star
8

wordpress-theme-base

Theme base for WordPress, ES2017+ & PHP7+
PHP
63
star
9

objection-rest

REST API generator for objection.js models
JavaScript
30
star
10

satakieli

Satakieli is a i18n library that provides identical API for ClojureScript and Clojure programmers. Localized messages can be written using ICU MessageFormat syntax.
Clojure
26
star
11

wordpress

Addons for WordPress development, using Seravo/wordpress as base
JavaScript
24
star
12

logspout-gelf

Logspout with GELF adapter
Dockerfile
15
star
13

gocd-slack-task

Go CD plugin allowing to send messages to Slack
Java
13
star
14

travis-oracledb-xe

Script and guide to setup Oracle Database Express Edition on Travis CI (without need to create Oracle account)
Shell
13
star
15

summer-2018

JavaScript
6
star
16

spring-boot-word-to-html-example

Java
6
star
17

alkobot

TypeScript
6
star
18

dodo.js

JavaScript
5
star
19

teatime-2018

Teatime 2018 demo project. See https://vincitteatime.fi/
JavaScript
5
star
20

heroku-buildpack-java-nodejs

Heroku buildpack for Java applications with Node.JS and npm.
Shell
4
star
21

multi-user-test-runner

JUnit test runner for running authorization unit/integration tests with multiple users and roles
Java
4
star
22

slurp

JavaScript
3
star
23

proxios

Magical ES6 Proxy wrapper for axios
3
star
24

ffmpeg

C
2
star
25

opendatatre

Open Data TRE Meetup example
JavaScript
2
star
26

wordpress-demo

Demo project, hosted in 5$ Digital Ocean LEMP one click app
PHP
2
star
27

get-a-room

PWA for making ad hoc room reservations easy in Google Workspace environment.
TypeScript
1
star
28

curd

Hassle-free CRUD operations
Clojure
1
star
29

VISDOM-Roadmapper

Roadmapper tool developed as part of ITEA 3 VISDOM project.
TypeScript
1
star
30

pfsense-fauxer

Simple client lib for communicating with pfSense faux-api qith node.
JavaScript
1
star
31

dodo-core-features

Dodo.js framework's core features (cors, auth, gzip, cookies, logging, etc.)
JavaScript
1
star
32

mml-mapserver

Docker image and instructions to serve MML maastokartta
HTML
1
star
33

multi-user-test-runner-examples

Test project for testing multi-user-test-runner
Java
1
star
34

dodo-objection

Objection.js ORM plugin for Dodo.js framework
JavaScript
1
star
35

fastest-tester

Tester for the Fastest test framework
JavaScript
1
star
36

lunch-assistant

Hackfest 2023 Kuopio team lunch assistant
TypeScript
1
star