1.0.1 • Published 7 years ago

express-seqsearch v1.0.1

Weekly downloads
1
License
ISC
Repository
github
Last release
7 years ago

express-seqsearch

Build Status

Express sequelize search & paginate middleware This is a custom middleware to paginate, sort, filter and search Model entries in a Sequelize Express app. It uses sequelize.findAndCountAll.

Installation

use npm to install

$ npm install --save express-seqsearch

Usage

You can add the middleware at the end of your route handlers if the results you want to send are to be paginated.

const express = require('express');
const router = express.Router();
const expressSeqsearch = require('express-seqsearch');

const sequelize = new Sequelize({
    // Sequelize config
});
const User = sequelize.define('user', {
    first_name: Sequelize.STRING,
    last_name: Sequelize.STRING
});
User.public = function() {
    return ['first_name', 'last_name'];
};
User.searchables = function() {
    return ['first_name', 'last_name'];
};

router.get("/users", /* other middlewares ... */, expressSeqsearch(sequelize, User));

Now, when you query the route /users the results will be returned in the following format:

{
    count: # total number of entries
    rows: [data]
}

Most importantly, you can add options to query data either by passing them to function expressSeqsearch directly or by sending them as query params.

Allowed query options

OptionQuery ParamDefaultDescription
queryq=value""Search for "value" in model's searchable attributes
filterf_attribute_name=valuenullAdds sql where clause to query
sorts_attribute_name=(ASCDESC)nullAdds sql order by clause to query
searchables-Model.searchables()Defines which attributes would be searchable
attributes-Model.public()Defines which attributes would to be selected, See sequelize attributes
include-Model.include()See sequelize include
offseto=value0Adds offset to query (for pagination)
limitl=value10Adds limit to query (for pagination)
groupNonenullSee sequelize group

Options passing

The middlewares parses the req.query object and reads from req.list if it exists.
You can pass the same options to req.list directly if they depend on some other sequelize models.
for example:

router.get("/users", function(req, res, next) {
    req.list = { attributes: ['first_name'] };
}, expressSeqsearch(sequelize, User));

// Has the same behavior as

router.get("/users", expressSeqsearch(sequelize, User, { attributes: ['first_name'] }));

Developpement

to run the tests on your local machine you should start postgres service with docker:

$ docker-compose start
$ npm test