This repo is a AdonisJs provider for simplicity work with search in adonis-lucid
Work with AdonisJs 4
npm i --save adonis-search
The provider is registered inside start/app.js
file under providers
array.
const providers = [
'adonis-search/providers/QueryProvider'
]
That's all! Now you can use the query provider as follows.
Request url is GET
/users?search=mark&page=2&order=-email
const Route = use('Route')
const Query = use('Query')
const User = use('App/Models/User')
Route.get('/users', async ({ request, response }) => {
const query = new Query(request, { order: 'id' })
const order = query.order()
const users = await User.query()
.where(query.search([
'first_name',
'last_name',
'email'
]))
.orderBy(order.column, order.direction)
.paginate(query.page(), query.limit())
response.json(users)
})
{
"page": 1,
"limit": 30,
"search": ""
}
You can change defaults by send second argument in Query constructor
const query = new Query(request, {
limit: 50
})
Note 1. Search not fire where clause if search variable is empty.
Note 2. All search columns and values will be translated to lowercase.
For basic usage you need add columns where you make search
const query = new Query(request, { order: 'id' })
const users = await User.query()
.where(query.search([
'first_name',
'last_name',
'email'
]))
If you need search in INT
columns, you need set first argument as object with columns types:
const query = new Query(request, { order: 'id' })
const users = await User.query()
.where(query.search({
id: Query.INT,
first_name: Query.STRING,
last_name: Query.STRING,
email: Query.STRING
}))
You can get parsed values from uri as page
and limit
. Variables are optional.
Route.get('/users', async ({ request, response }) => {
const query = new Query(request)
const users = await User.query()
.paginate(query.page(), query.limit())
response.json(users)
})
For use order by you need set default value order
by column for query
const query = new Query(request, { order: 'id' })
const order = query.order()
const users = await User.query()
.orderBy(order.column, order.direction)
.fetch()
Reverse sort are supported by set first symbol -
before name column. Sample uri as /users?order=-email
It's native support for AngularJS applications.